http://stackoverflow.com/comment/89030113
type: Comment
has text: This answer worked exactly like I wanted! Thank you so much and for not downvoting me :)
comment on: http://stackoverflow.com/a/51018588
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89082085
type: QuestionComment
has text: You should edit your question to be nicer...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51045309

http://stackoverflow.com/a/51032990
has comment: http://stackoverflow.com/comment/89157791
answers question: http://stackoverflow.com/q/51019134
accepted answer of: http://stackoverflow.com/q/51019134
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89124195
score: 2
has comment: http://stackoverflow.com/comment/89176560
has body: The X and Y must have the same length. In your error message one is twice as long as the other. In your MatPlotLib code example is some code that seems reshape the self.data_plot into two rows. self.data_plot.shape = -1, 2 self.data_plot = self.data_plot.T This functionality is missing in the PyQtGraph code.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89100826
downvote count: 0
has comment: http://stackoverflow.com/comment/89163055

http://stackoverflow.com/q/51033251
answer count: 1
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51033846
tagged with: python
has answer: http://stackoverflow.com/a/51033846
has body: I have three Pandas dataframes, indexed by datetime: df1, df2, and df3. Each has pairs of dates in the index. I would like to combine these three dataframes together, retaining any datetime index pairs that are unique, but combining any repeated pairs so that these date pairs aren't listed multiple times (not a simple concat). Here are samples of the dataframes: In [1]: print df1 CurTempMid id fldDate 1997-12-23 0.0 recent 1997-12-23 -2.0 hist 1997-12-27 9.0 recent 1997-12-27 7.0 hist 1998-02-10 9.0 recent 1998-02-10 7.0 hist ... ... ... 2001-01-04 27.0 recent 2001-01-04 26.0 hist 2001-03-16 12.0 recent 2001-03-16 11.0 hist 2001-04-06 23.0 recent 2001-04-06 22.0 hist In [2]: print df2 MaxTempMid id fldDate 1998-01-02 29.0 recent 1998-01-02 28.0 hist 1998-02-15 18.0 recent 1998-02-15 23.0 hist 1998-02-23 24.0 recent 1998-02-23 15.0 hist ... ... ... 2001-01-01 16.0 recent 2001-01-01 22.0 hist 2001-01-04 30.0 recent 2001-01-04 37.0 hist 2001-02-16 14.0 recent 2001-02-16 11.0 hist In [3]: print df3 MinTempMid id fldDate 1997-12-23 0.0 recent 1997-12-23 -2.0 hist 1997-12-26 -3.0 recent 1997-12-26 -2.0 hist 1997-12-27 -1.0 recent 1997-12-27 0.0 hist ... ... ... 2001-02-18 9.0 recent 2001-02-18 36.0 hist 2001-03-11 18.0 recent 2001-03-11 38.0 hist 2001-03-12 13.0 recent 2001-03-12 16.0 hist The desired result looks like this: CurTempMid MaxTempMid MinTempMid id fldDate 1997-12-23 0.0 Nan 0.0 recent 1997-12-23 -2.0 NaN -2.0 hist 1997-12-26 Nan NaN -3.0 recent 1997-12-26 NaN NaN -2.0 hist 1997-12-27 9.0 NaN -1.0 recent 1997-12-27 7.0 NaN 0.0 hist ... ... ... ... ... Once combined, the 'id' column should be identical, so I only need to retain a single 'id' column.
has title: Combine multiple Pandas dataframes with duplicate datetime index pairs
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/51039538
answer count: 2
has answer: http://stackoverflow.com/a/51042599
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51040595
tagged with: python
has comment: http://stackoverflow.com/comment/89070415
has answer: http://stackoverflow.com/a/51040595
has title: Django aggregation taking a lot of time
accepted answer: http://stackoverflow.com/a/51042599
tagged with: django
has body: I have a model defined as bellow class Image(model.Models): # Stages STAGE_TRAIN = 'train' STAGE_VAL = 'val' STAGE_TEST = 'test' STAGE_TRASH = 'trash' STAGE_CHOICES = ( (STAGE_TRAIN, 'Train'), (STAGE_VAL, 'Validation'), (STAGE_TEST, 'Test'), (STAGE_TRASH, 'Trash'), ) stage = models.CharField(max_length=5, choices=STAGE_CHOICES, default=STAGE_TRAIN) commit = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name="images", related_query_name="image") In my database I have 170k images and I try to have an endpoint that will count all the images by stage Currently I have something like that base_query = Image.objects.filter(commit=commit_uuid).only('id', 'stage') count_query = base_query.aggregate(count_train=Count('id', filter=Q(stage='train')), count_val=Count('id', filter=Q(stage='val')), count_trash=Count('id', filter=Q(stage='trash'))) but it takes around 40sec and when I try to see the SQL request in my shell I have something that looks ok {'sql': 'SELECT COUNT("image"."id") FILTER (WHERE "image"."stage" = \'train\') AS "count_train", COUNT("image"."id") FILTER (WHERE "image"."stage" = \'val\') AS "count_val", COUNT("image"."id") FILTER (WHERE "image"."stage" = \'trash\') AS "count_trash" FROM "image" WHERE "image"."commit_id" = \'333681ff-886a-42d0-b88a-5d38f1e9fe94\'::uuid', 'time': '42.140'} an other strange thing is that if I change my aggregate function with count_query = base_query.aggregate(count_train=Count('id', filter=Q(stage='train')&amp;Q(commit=commit_uuid)), count_val=Count('id', filter=Q(stage='val')&amp;Q(commit=commit_uuid)), count_trash=Count('id', filter=Q(stage='trash')&amp;Q(commit=commit_uuid))) When I do that the query is twice as fast (still 20sec) and when I display the SQL I see that the filter on the commit is done inside the FILTER So I have two questions: Can I do something different to improve the speed of the query or should I store the count somewhere and change the values each time I change an image ? I was expecting the …
upvote count: 1
type: AnsweredQuestion
type: Question

decorator
tags question: http://stackoverflow.com/q/51089327
tags question: http://stackoverflow.com/q/51077539
tags question: http://stackoverflow.com/q/51023322
tag name: decorator
tags question: http://stackoverflow.com/q/51089206
tags question: http://stackoverflow.com/q/51022747
type: Tag
tags question: http://stackoverflow.com/q/51128074

http://stackoverflow.com/a/51182496
score: 0
answers question: http://stackoverflow.com/q/51139170
type: Answer
has comment: http://stackoverflow.com/comment/89490915
has body: What strikes me first thing scanning the code above is the PATH for IMAGES_STORE. the / means that you are going to the absolute root path of your machine, so you either put the absolute path to where you want to save or just do a relative path from where you are running your crawler I'm on a linux machine so my absolute path will be something like IMAGES_STORE = /home/pk/myProjects/scraper/images OR IMAGES_STORE = 'images' Also, most importantly, if you are using default pipeline, the variable which holds the extracted image, (where you do extract_first()) must literally be image_urls. You are also missing a couple of steps. In your spider, add this: class ImgData(Item): image_urls=scrapy.Field() images=scrapy.Field() In the yield step, modify to: yield ImgData(image_urls=response.urljoin(q.css("::attr(src)").extract_first()))

http://stackoverflow.com/a/51016254
type: Answer
has comment: http://stackoverflow.com/comment/89025574
has body: Using a parser is the way to go here. I'm most comfortable with lxml so that's what I'll be using in my answer here, but there are others you may choose from. import lxml.etree as ET The first thing to do is to have the XML read in somehow. Here, I just assumed it is in a string. xml = """ 0 1 a 0 1 a """ Now the actual work can be done on it. First we parse the tree so that we aren't working on raw text and are instead working on a structured object. We'll be using a special parser to be able to get a nice printed output later. More details may be found here. parser = ET.XMLParser(remove_blank_text=True) tree = ET.fromstring(xml, parser=parser) So now we have a nice tree structure to work with. We need to find the label that you are targeting to change. To find the label in question, I'll be using XPATH. XPATH isn't exactly the smoothest process if you're not familiar with it so I'd recommend looking into how to select exactly what you want. Here is a pretty good tutorial with interactive examples that you can play around with. I believe the examples are in HTML but the ideas are transferable. In our example here, we're finding a label with an id of 1. target = tree.find(".//label[@id='1']") Next order of business is to create new tag. You can add attributes as you please but for a minimal example, we'll just add a simple tag called "mynewtag". mynewtag = ET.Element("mynewtag") Let's add in the created tag to the label we found earlier. Since there is just one element, I'll be using append. However, if order matters to you (for example, you want it to be the first child of some other element), you may use insert instead of append. target.append(newtag) Now the changes have been made to the tree! All that's left to do is to print out the resulting XML. We turn the tree back into a string and then print it out. The decode call is because the tostring method returns a byte-string and I want the newlines to be properly rendered. The pretty_print option makes the output…
answers question: http://stackoverflow.com/q/51015997
accepted answer of: http://stackoverflow.com/q/51015997
score: 0
type: AcceptedAnswer

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

http://stackoverflow.com/a/51105795
score: 0
has body: Turns out I have 32 bit python, not 64. Choosing the latest (1.15) numpy enabled it to install, and now scipy.interpolate loads and runs.
type: Answer
answers question: http://stackoverflow.com/q/51085455

http://stackoverflow.com/q/51120245
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm using django-dbbackup to back up my postgresql database to my s3 bucket. It's connected to my S3 bucket via the following settings: draft1.settings.py DBBACKUP_STORAGE = 'draft1.aws.utils.BackupRootS3BotoStorage' DBBACKUP_S3_BUCKET = AWS_STORAGE_BUCKET_NAME DBBACKUP_S3_ACCESS_KEY = AWS_ACCESS_KEY_ID DBBACKUP_S3_SECRET_KEY = AWS_SECRET_ACCESS_KEY draft1.aws.utils BackupRootS3BotoStorage = lambda: S3Boto3Storage(location='backup') Bucket policy { "Version": "2012-10-17", "Statement": [ { "Sid": "Allow All", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::****-bucket/*" }, { "Sid": "Deny All Actions On All But Media and Static Unless Defined User", "Effect": "Deny", "NotPrincipal": { "AWS": "arn:aws:iam::********:root" }, "Action": "s3:*", "NotResource": [ "arn:aws:s3:::****-bucket/media/*", "arn:aws:s3:::****-bucket/static/*", "arn:aws:s3:::****-bucket/media_thumbnail/*" ] } ] } As you can see I'm trying to back it up to the backup folder. Full error: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/utils.py", line 116, in wrapper func(*args, **kwargs) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/management/commands/dbbackup.py", line 61, in…
has title: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
tagged with: amazon-s3
type: Question
score: 5
has comment: http://stackoverflow.com/comment/94383492
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/53842816
tagged with: amazon-web-services
tagged with: postgresql
answer count: 1
has comment: http://stackoverflow.com/comment/132661938

http://stackoverflow.com/q/51163720
tagged with: refactoring
type: Question
has answer: http://stackoverflow.com/a/51164769
has answer: http://stackoverflow.com/a/51163761
score: 0
has title: How to reduce number of python code?
has comment: http://stackoverflow.com/comment/89310749
possible better answer: http://stackoverflow.com/a/51163751
has answer: http://stackoverflow.com/a/51163751
accepted answer: http://stackoverflow.com/a/51164769
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51163759
answer count: 4
has comment: http://stackoverflow.com/comment/89310736
has body: How to reduce number of code when element does not already exist in dictionary? Otherwise assign it to the object. Prove of python concept: class MyClass: pass key = "test python" item = MyClass() d = {} if d.get(key) is None: d[key] = item else: item = d[key] print(item) Is it possible to remove if else statement?
type: AnsweredQuestion
tagged with: coding-style

http://stackoverflow.com/q/51036326
type: Question
answer count: 2
downvote count: 5
has comment: http://stackoverflow.com/comment/89064440
has comment: http://stackoverflow.com/comment/89064332
favorite count: 0
possible better answer: http://stackoverflow.com/a/51036369
has title: Reverse accessing a list in python
has answer: http://stackoverflow.com/a/51036378
has answer: http://stackoverflow.com/a/51036369
score: -4
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51036378
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89064396
linked to: http://stackoverflow.com/q/3940128
has comment: http://stackoverflow.com/comment/89064466
has body: a=[0,1,2,3] for a[-1] in a : print a[-1] This Program gives me an output 0 1 2 2 I am not able to decode it. I was expecting it to print the list in reverse direction. or at least print 3 alone. Can someone help me to understand this output
has comment: http://stackoverflow.com/comment/89064370

http://stackoverflow.com/comment/89275864
comment on: http://stackoverflow.com/a/51145737
type: AnswerComment
score: 0
type: Comment
has text: @NathanielSaul Well, if you want it to be more explicit then nothing stops you doing the same thing with `collections.OrderedDict.fromkeys(...)`. Personally, I prefer to see the dict comprehension, as long as you don't need to support older Python versions.

http://stackoverflow.com/q/51104595
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has title: How to make a ternary contour plot with Python Plotly?
tagged with: plotly
has answer: http://stackoverflow.com/a/53194800
type: Question
has body: I am trying to plot a function defined on a simplex. Apparently, you can do it very nicely using the Matlab API. But I cannot figure out how to do this using the Python API. The reference has a section named Ternary Contour Plots in Python but it does not plot a numeric function, but a function mapping the simplex to a given discrete set. I tried to emulate the Matlab code: import plotly as py A = [0, .2, .2, .2, 0, .6, .75, .9, 0, 1, .8, .3] B = [1, .2, .4, .1, 0, .4, .05, 0, .8, 0, .05, .3] C = [0, .6, .4, .7, 1, 0, .2, .1, .2, 0, .15, .4] Z = [.1, .5, .1, .2, 1, .8, .4, 0, .1, .6, 1, .7] trace = { "type": 'scatterternary', "carpet": 'scattercontour', "a": A, "b": B, "c": C, "z": Z } layout = { 'title': 'Simple Ternary Contour Plot with Python' } figure = dict(data=[trace], layout=layout) py.offline.plot(figure, validate=False) But I get this plot instead:
score: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51139408

http://stackoverflow.com/q/51144474
tagged with: python
tagged with: jupyter-notebook
tagged with: tensorflow.js
has title: Unable to Import tensorflow.js in jupyter notebook(SyntaxError: Unexpected token import)
accepted answer: http://stackoverflow.com/a/51145079
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51145079
has body: Kindly look at the below screenshot: I am trying to import tensorflow.js from javascript kernel of jupyter notebook.The image shows how I installed the module via terminal and how I am importing it and what's the error. How to resolve it considering I am a newbie to javascript.
type: Question
answer count: 2
upvote count: 1
downvote count: 1
tagged with: javascript
has answer: http://stackoverflow.com/a/51159186
favorite count: 0
score: 0
possible better answer: http://stackoverflow.com/a/51159186

http://stackoverflow.com/comment/89283834
comment on: http://stackoverflow.com/a/51146438
type: AnswerComment
has text: There are probably other ways of doing it, but I found this to be pretty short and simple. :)
type: Comment
score: 1

http://stackoverflow.com/q/51163871
upvote count: 5
accepted answer: http://stackoverflow.com/a/52869992
tagged with: tensorflow
type: Question
score: 5
has title: Tensorboard Image Summaries
downvote count: 0
answer count: 1
tagged with: tensorboard
favorite count: 0
has body: I use Matplotlib to create custom t-SNE embedding plots at each epoch during trainging. I would like the plots to be displayed on Tensorboard in a slider format, like this MNST example: But instead each batch of plots is displayed as separate summaries per epoch, which is really hard to review later. See below: It appears to be creating multiple image summaries with the same name, so appending _X suffix instead of overwriting or adding to slider like I want. Similarly, when I use the family param, the images are grouped differently but still append _X to the summary name scope. This is my code to create custom plots and add to tf.summary.image using custom plots and add evaluated summary to summary writer. def _visualise_embedding(step, summary_writer, features, silhouettes, sample_size=1000): ''' Visualise features embedding image by adding plot to summary writer to track on Tensorboard ''' # Select random sample feats_to_sils = list(zip(features, silhouettes)) shuffle(feats_to_sils) feats, sils = zip(*feats_to_sils) feats = feats[:sample_size] sils = sils[:sample_size] # Embed feats to 2 dim space embedded_feats = perform_tsne(2, feats) # Plot features embedding im_bytes = plot_embedding(embedded_feats, sils) # Convert PNG buffer to TF image image = tf.image.decode_png(im_bytes, channels=4) # Add the batch dimension image = tf.expand_dims(image, 0) summary_op = tf.summary.image("model_projections", image, max_outputs=1, family='family_name') # Summary has to be evaluated (converted into a string) before adding to the writer summary_writer.add_summary(summary_op.eval(), step) I understand I might get the slider plots I want if I add the visualise method as an operation to the graph so as to avoid the name duplication issue. But I need to be able to loop through my evaluated tensor values to perform t-SNE to create the embeddings... I've been stuck on this for a while so any advise is appreciated!
tagged with: python
has answer: http://stackoverflow.com/a/52869992
type: AnsweredQuestion

http://stackoverflow.com/comment/89120017
score: 1
comment on: http://stackoverflow.com/q/51065046
type: QuestionComment
type: Comment
has text: Can you please provide an example of your CSV file?

machine-learning
tags question: http://stackoverflow.com/q/51056479
tags question: http://stackoverflow.com/q/51041128
tags question: http://stackoverflow.com/q/51091132
tags question: http://stackoverflow.com/q/51031691
tags question: http://stackoverflow.com/q/51119808
tags question: http://stackoverflow.com/q/51152582
tags question: http://stackoverflow.com/q/51149072
tags question: http://stackoverflow.com/q/51146933
tags question: http://stackoverflow.com/q/51096161
tags question: http://stackoverflow.com/q/51124307
tags question: http://stackoverflow.com/q/51087854
tags question: http://stackoverflow.com/q/51052420
tags question: http://stackoverflow.com/q/51161782
tags question: http://stackoverflow.com/q/51057993
tags question: http://stackoverflow.com/q/51085553
tags question: http://stackoverflow.com/q/51144993
tags question: http://stackoverflow.com/q/51099500
tags question: http://stackoverflow.com/q/51054627
tags question: http://stackoverflow.com/q/51106402
tags question: http://stackoverflow.com/q/51148876
tags question: http://stackoverflow.com/q/51081439
tags question: http://stackoverflow.com/q/51069750
tags question: http://stackoverflow.com/q/51129912
tags question: http://stackoverflow.com/q/51110110
tags question: http://stackoverflow.com/q/51088761
tags question: http://stackoverflow.com/q/51023968
tags question: http://stackoverflow.com/q/51017483
tags question: http://stackoverflow.com/q/51035303
tags question: http://stackoverflow.com/q/51108486
tags question: http://stackoverflow.com/q/51159532
tags question: http://stackoverflow.com/q/51055302
tag name: machine-learning
tags question: http://stackoverflow.com/q/51100057
tags question: http://stackoverflow.com/q/51055909
tags question: http://stackoverflow.com/q/51040078
tags question: http://stackoverflow.com/q/51154180
tags question: http://stackoverflow.com/q/51050857
tags question: http://stackoverflow.com/q/51137773
tags question: http://stackoverflow.com/q/51069380
tags question: http://stackoverflow.com/q/51058488
tags question: http://stackoverflow.com/q/51089207
tags question: http://stackoverflow.com/q/51027357
tags question: http://stackoverflow.com/q/51033792
tags question: http://stackoverflow.com/q/51015259
tags question: http://stackoverflow.com/q/51051373
tags question: http://stackoverflow.com/q/51138290
tags question: http://stackoverflow.com/q/51152088
tags question: http://stackoverflow.com/q/51083843
type: Tag
tags question: http://stackoverflow.com/q/51027885
tags question: http://stackoverflow.com/q/51116772
tags question: http://stackoverflow.com/q/51105333
tags question: http://stackoverflow.com/q/51145682
tags question: http://stackoverflow.com/q/51054958
tags question: http://stackoverflow.com/q/51055193
tags question: http://stackoverflow.com/q/51133162
tags question: http://stackoverflow.com/q/51149995
tags question: http://stackoverflow.com/q/51041066
tags question: http://stackoverflow.com/q/51056650
tags question: http://stackoverflow.com/q/51148675
tags question: http://stackoverflow.com/q/51080746
tags question: http://stackoverflow.com/q/51065222
tags question: http://stackoverflow.com/q/51121607
tags question: http://stackoverflow.com/q/51044904
tags question: http://stackoverflow.com/q/51071756
tags question: http://stackoverflow.com/q/51048142
tags question: http://stackoverflow.com/q/51145007
tags question: http://stackoverflow.com/q/51073614
tags question: http://stackoverflow.com/q/51152330
tags question: http://stackoverflow.com/q/51079983
tags question: http://stackoverflow.com/q/51058877
tags question: http://stackoverflow.com/q/51060886
tags question: http://stackoverflow.com/q/51141408
tags question: http://stackoverflow.com/q/51155881
tags question: http://stackoverflow.com/q/51143639
tags question: http://stackoverflow.com/q/51103493
tags question: http://stackoverflow.com/q/51113885
tags question: http://stackoverflow.com/q/51046450
tags question: http://stackoverflow.com/q/51148326
tags question: http://stackoverflow.com/q/51039749

http://stackoverflow.com/q/51072399
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89135753
has title: str.replace method not working within a user defined function when map to pandas series; however, it works on a normal function call. Why?
tagged with: python
linked to: http://stackoverflow.com/q/44227748
has comment: http://stackoverflow.com/comment/89134958
answer count: 0
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89134554
type: Question
has comment: http://stackoverflow.com/comment/89135116
tagged with: arrays
tagged with: pandas
tagged with: function
has comment: http://stackoverflow.com/comment/89134944
favorite count: 0
tagged with: python-3.x
has body: str.replace method not working within a user defined function when map to pandas series; however, it works on a normal function call. Why? RE_EMOJI = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) def clean_story(x): x = x.strip() # trims leading and trailing whitespace only x = x.replace('\r', '').replace('\n', '') # remove all 3 types of line breaks translator = str.maketrans('','',string.punctuation) # strip punctuation, function x = x.translate(translator) # strip punctuation x = RE_EMOJI.sub(r'', x) # remove emojis x = re.sub(r'http\S+', '', x, flags=re.MULTILINE) # remove url http x = re.sub(r'\(http\S+', '', x, flags=re.MULTILINE) # remove url (http x = re.sub(r'@\S+\s', '', x, flags=re.MULTILINE) # remove words starting with @ x = re.sub(' +', ' ', x) # remove duplicated space x = x.lower() # lower case return x x is an example text x = " Overview \n Using \r Home #; automation: to- control applications \r is cool, but we can further leverage its power to simplify our daily tasks like checking gas, geysers, heaters, AC temperature etc. before leaving home. \n Scope \n The server (Raspberry pi 2 running on Windows 10) is running at home. Family members will stay connected through their smart devices like Mobile phones with Windows Operating systems or Android. The server will be connected to gas, heat and smoke detection sensors. And will push notifications to all the clients (family members), on any changes detected. The server will push notifications to all the clients using Microsoft Azure- Notification Hubs. \n Components and supplies Software and applications Summary \n " Use this text as an example: calling clean_story(x) results in the proper removal of all "\n" 'overview using home automation to control applications is cool but we can further leverage its power to simplify our daily tasks like checking gas geysers heaters ac temperature etc before leaving home scope the server raspberry pi 2 running on windows 10 is running at home family mem…
has comment: http://stackoverflow.com/comment/89134785

http://stackoverflow.com/a/51117708
type: Answer
answers question: http://stackoverflow.com/q/51115651
has body: There are a few errors here. root and alias are not the same thing and actually are totally unnecessary here anyway. You should specify root once, outside the location directives. They will inherit it from the server directive anyway and your are basically doing the same thing. upstream django { server 127.0.0.1:8001; } server { listen 8000; server_name taopinpin.cn; root /root/mysite; # you should really use a standard location, like /var/www charset utf-8; client_max_body_size 75M; location / { try_files $uri $uri/ @proxy; } location @proxy { inlcude /root/mysite/mysite/uwsgi_params; # is this correct? Mine is in /etc/nginx uwsgi_pass django; } }
score: 0

data-processing
tags question: http://stackoverflow.com/q/51157514
type: Tag
tags question: http://stackoverflow.com/q/51121607
tag name: data-processing

http://stackoverflow.com/q/51120615
has body: I have the following code to calculate the normals of the weights and then the gaussian PDFs for these. normals = [] for k in range(len(weights)): normals.append(multivariate_normal(mean=means[k],cov=covariances[k])) gaussian_pdfs = [] for sample in img_descriptors: inside_array = np.array([]) for g_k in normals: inside_array = np.append(inside_array, g_k.pdf(sample)) gaussian_pdfs.append(inside_array) Please help me in vectorizing the above code to achieve faster computations.
tagged with: python
tagged with: vectorization
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89228440
has comment: http://stackoverflow.com/comment/89227315
tagged with: gaussian
type: Question
tagged with: numpy
has title: How to vectorize this Python code
has comment: http://stackoverflow.com/comment/89236954
downvote count: 0
has comment: http://stackoverflow.com/comment/89236937
favorite count: 0

http://stackoverflow.com/comment/89292103
type: Comment
has text: Thanks for your detailed reply. I realized that making func[123] async works. However, the whole idea was to hide how the data is received and getData should return actual data whether it comes from file or socket. I am wondering if there is a way to make 'await' actually wait on result and resume execution when socket read is complete.
type: AnswerComment
comment on: http://stackoverflow.com/a/51147818
score: 0

http://stackoverflow.com/a/51085353
downvote count: 0
has body: A simple_tag can also be used to set a variable in the context: {% is_home as is_home %} {% if is_home %} {# now testing the `is_home` var #} &lt;svg data-src="{% static 'images/cart_white.svg' %}" width="35" height="30"/&gt; {% else %} &lt;svg data-src="{% static 'images/cart.svg' %}" width="35" height="30"/&gt; {% endif %}
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51085254
accepted answer of: http://stackoverflow.com/q/51085254
type: AcceptedAnswer

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51154674
tags question: http://stackoverflow.com/q/51012506
tags question: http://stackoverflow.com/q/51163571
tags question: http://stackoverflow.com/q/51032116
tags question: http://stackoverflow.com/q/51140048
tags question: http://stackoverflow.com/q/51149221
tags question: http://stackoverflow.com/q/51062760
tags question: http://stackoverflow.com/q/51043974
tags question: http://stackoverflow.com/q/51120313
tags question: http://stackoverflow.com/q/51117208
tags question: http://stackoverflow.com/q/51144514
tags question: http://stackoverflow.com/q/51016896
tags question: http://stackoverflow.com/q/51148893
type: Tag
tags question: http://stackoverflow.com/q/51056816
tags question: http://stackoverflow.com/q/51081730
tags question: http://stackoverflow.com/q/51113494
tags question: http://stackoverflow.com/q/51089460
tags question: http://stackoverflow.com/q/51132321
tags question: http://stackoverflow.com/q/51162264
tags question: http://stackoverflow.com/q/51069935
tags question: http://stackoverflow.com/q/51159866
tags question: http://stackoverflow.com/q/51163120
tags question: http://stackoverflow.com/q/51155549
tags question: http://stackoverflow.com/q/51166785
tags question: http://stackoverflow.com/q/51042086
tags question: http://stackoverflow.com/q/51167150
tags question: http://stackoverflow.com/q/51021907
tags question: http://stackoverflow.com/q/51164887
tags question: http://stackoverflow.com/q/51013909
tags question: http://stackoverflow.com/q/51088835
tags question: http://stackoverflow.com/q/51069826
tags question: http://stackoverflow.com/q/51013537
tags question: http://stackoverflow.com/q/51014092
tags question: http://stackoverflow.com/q/51158299

http://stackoverflow.com/a/51093855
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89175868
score: 4
answers question: http://stackoverflow.com/q/51093754
has body: I am not sure if a website will block my server's IP address if I continue to use that IP. I aggregate their feed every now and then. You can't do that (legally/easily...) without actually being able to send traffic from another source address. If you really want to avoid getting blocked, look at ways to tunnel your traffic through other places. For example: starting your process on a new hosted instance, using vpns, tor.
has comment: http://stackoverflow.com/comment/89176186

http://stackoverflow.com/comment/89232560
has text: Lists are ordered, but not sorted. 1. I find it weird that your x data are strings, I don't know how mpl handles that (try converting to ints), 2. Make sure the data are sorted (and watch out for lexicographical string sorting).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51123726
score: 0

http://stackoverflow.com/comment/89089352
comment on: http://stackoverflow.com/a/51049054
type: AnswerComment
score: 0
type: Comment
has text: I just had the same idea and `pop()`-ed it out in the pipeline. I think i just got confused searching for an overly `scrapy`-like way to do it, thanks!

http://stackoverflow.com/comment/89159840
type: Comment
score: 0
has text: Your project layout isn't clear to me. Please show where `manage.py` and `settings.py` is. Is there a `static` directory alongside `pyapp` and `pyweb`?
comment on: http://stackoverflow.com/q/51084617
type: QuestionComment

http://stackoverflow.com/q/51160955
has body: Pylint reports an error E0202 (method-hidden) for Python code that uses a self-defined property decorator. My attempts to use the property-classes option have failed. Here are props.py from functools import wraps def myproperty(func): @wraps(func) def fget(self): return func(self) return property(fget) and testimport.py: #!/usr/bin/python from props import myproperty class E0202(object): def __init__(self): self._attr = 'attr' self._myattr = 'myattr' @property def attr(self): return self._attr @attr.setter def attr(self, value): self._attr = value @myproperty def myattr(self): return self._myattr @myattr.setter def myattr(self, value): self._myattr = value def assign_values(self): self.attr = 'value' self.myattr = 'myvalue' if __name__ == '__main__': o = E0202() print(o.attr, o.myattr) o.assign_values() print(o.attr, o.myattr) Running the code with Python 2.7.13 produces the expected results: $ python test.py ('attr', 'myattr') ('value', 'myvalue') Pylint 1.6.5 reports an error for the self-defined property, but not for the regular property: $ pylint -E --property-classes=props.myproperty testimport.py No config file found, using default configuration ************* Module testimport E: 20, 4: An attribute defined in testimport line 29 hides this method (method-hidden) Line 29 is the use of the setter of the self-defined property: self.myattr = 'myvalue' What would be the proper options for pylint? Or is this a false positive?
score: 3
answer count: 1
has answer: http://stackoverflow.com/a/52322338
favorite count: 0
type: UnansweredQuestion
tagged with: pylint
tagged with: python
tagged with: properties
upvote count: 3
has title: Pylint: How to specify a self-defined property decorator with property-classes?
type: Question
downvote count: 0

http://stackoverflow.com/comment/89075333
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51037933
has text: Understood, I'll edit my answer, but one question. Are the old and new subdirectories names the same? Like is the name of B == name of L?

http://stackoverflow.com/comment/89057626
has text: no worries, i'm interested to see what the issues were. i've never actually sent an api trade to any of the crypto exchanges, just used them to monitor pricing
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51014226

http://stackoverflow.com/comment/89126442
score: 0
type: Comment
has text: @AsherMetzger, Not sure, I can't reproduce your error. The code works with the data you provided.
comment on: http://stackoverflow.com/a/51047542
type: AnswerComment

http://stackoverflow.com/comment/89182931
type: AnswerComment
type: Comment
has text: thanks for your help, unfortunatly it works well on this example, but not on my real problem. I will try to add more explainations
score: 1
comment on: http://stackoverflow.com/a/51096834

http://stackoverflow.com/q/51137946
tagged with: list
type: Question
tagged with: for-loop
tagged with: nltk
answer count: 1
has title: NLTK Wordnet getting the list of Synsets in Python
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51146919
accepted answer: http://stackoverflow.com/a/51146919
has body: I'm creating lemmas and synsets for Italian language using NLTK Wordnet, it looks okay: from nltk.corpus import wordnet as wn ll=wn.synsets('carta', lang='ita') ll [Synset('card.n.01'), Synset('map.n.01'), Synset('sheet.n.02'), Synset('document.n.01'), Synset('charter.n.01'), Synset('menu.n.01'), Synset('paper.n.01')] hypernyms[0].lemmas(lang="ita") [Lemma('paper.n.01.carta')] But I'm trying to receive after the last operation not only one list value but list with all values for all synsets I have in ll. Used couple approaches but they don't work: First one, still using NLTK: lemmas = wn.lemmas(ll, lang="ita") 'list' object has no attribute 'lower' And another with a loop: i = iter(list(range(6))) for i in ll[i].lemmas(lang='ita'): print(ll[i].lemmas(lang='ita')) list indices must be integers or slices, not list_iterator How this could be solved?
tagged with: wordnet
type: AnsweredQuestion

http://stackoverflow.com/comment/89148023
type: QuestionComment
has text: Just a quick note, you shouldn't be continuously opening the PyAudio stream; i.e. set it up in an init function call or something similar, before the streaming starts. Then access the stream object to read from it when you need with your `record()` method. Or at least close it if you want to keep opening it.
score: 0
comment on: http://stackoverflow.com/q/51079338
type: Comment

http://stackoverflow.com/q/51065102
type: Question
has comment: http://stackoverflow.com/comment/89120517
has body: I am trying to paste get an image from clipboard and paste it into the textbox/label in tkinter. My code is below. # page4 buttons and functions f7 = Frame(page4) f7.grid(row=0, column=0, sticky='NESW') f8 = Frame(page4) f8.grid(row=0, column=0, columnspan=2, sticky='NESW') tb8 = Label(f7, width=82) tb8.grid(row=0, column=0, sticky='NESW') tb9 = Text(f7, width=30) tb9.grid(row=0, column=1, sticky='NESW') def imgps(): try: image = root.selection_get(selection='CLIPBOARD') img = ImageTk.PhotoImage(Image.open(image)) tb8.config(page4, image=img) tb8.clipboard_clear() except: messagebox.showinfo(message="Clipboard is Empty.") pbtn11 = Button(f8, text="IMAGE", activebackground="lavender", activeforeground="RoyalBlue", bd="5", bg="aquamarine2", command=imgps, fg="purple", font=('arial', 10, 'bold')) pbtn11.grid(row=0, column=0, sticky='NESW') Nothing appears on the area intended and neither any error is shown up. But, whence I close the application. the Messagebox turns up. Seems like weird coding. Can somebody help.
has comment: http://stackoverflow.com/comment/89120262
has title: Tkinter paste image in textbox from clipboard
score: 1
has answer: http://stackoverflow.com/a/51065493
tagged with: image
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89120329
has comment: http://stackoverflow.com/comment/89120216
tagged with: python
favorite count: 0
tagged with: tkinter
downvote count: 0
tagged with: clipboard
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89120429

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51135026
tags question: http://stackoverflow.com/q/51108478
tags question: http://stackoverflow.com/q/51163854
tags question: http://stackoverflow.com/q/51090424
tags question: http://stackoverflow.com/q/51123581
tags question: http://stackoverflow.com/q/51073292
tags question: http://stackoverflow.com/q/51157987
tags question: http://stackoverflow.com/q/51135444
tags question: http://stackoverflow.com/q/51136174
tags question: http://stackoverflow.com/q/51070273
tags question: http://stackoverflow.com/q/51092602
tags question: http://stackoverflow.com/q/51112877
tags question: http://stackoverflow.com/q/51084663
tags question: http://stackoverflow.com/q/51091969
tags question: http://stackoverflow.com/q/51093034
tags question: http://stackoverflow.com/q/51133034
tags question: http://stackoverflow.com/q/51152036
tags question: http://stackoverflow.com/q/51023448
tags question: http://stackoverflow.com/q/51131805
tags question: http://stackoverflow.com/q/51149314
tags question: http://stackoverflow.com/q/51076948
tags question: http://stackoverflow.com/q/51140483
tags question: http://stackoverflow.com/q/51012350
tags question: http://stackoverflow.com/q/51046440
tags question: http://stackoverflow.com/q/51126902
tags question: http://stackoverflow.com/q/51114563
tags question: http://stackoverflow.com/q/51129840
tags question: http://stackoverflow.com/q/51023116
tags question: http://stackoverflow.com/q/51058236
tags question: http://stackoverflow.com/q/51064581
tags question: http://stackoverflow.com/q/51106914
tags question: http://stackoverflow.com/q/51049779
tags question: http://stackoverflow.com/q/51036674
tags question: http://stackoverflow.com/q/51020346
tags question: http://stackoverflow.com/q/51063145
tags question: http://stackoverflow.com/q/51119616
tag name: pyqt
tags question: http://stackoverflow.com/q/51092302
tags question: http://stackoverflow.com/q/51032311
tags question: http://stackoverflow.com/q/51066404
tags question: http://stackoverflow.com/q/51089331
tags question: http://stackoverflow.com/q/51133678

http://stackoverflow.com/comment/107458668
comment on: http://stackoverflow.com/a/60735648
type: Comment
has text: This is for Ubuntu - can you post the centos version also please
score: 0
type: AnswerComment

http://stackoverflow.com/a/51037950
has comment: http://stackoverflow.com/comment/89072821
has body: I think you have mixed the arguements for mean_squared_error, it should be rmse=numpy.sqrt(mean_squared_error(y_test,y_prediction)) Update : as per the latest error, try this fig, bx = plt.subplots(figsize=(19,8)) bx.plot(y_prediction, scaled_wind_speed_test,'bs') fig.suptitle('Wind Power Prediction v Wind Speed', fontsize=20) plt.xlabel('Wind Power Data') plt.ylabel('Predicted Power') plt.xticks(rotation=30) plt.show() Update 2 In case you get error on the other plot try this fig, bx = plt.subplots(figsize=(19,8)) bx.plot( y_prediction, y_test) fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20) plt.xlabel('Wind Power Data') plt.ylabel('Predicted Power')
has comment: http://stackoverflow.com/comment/89068032
has comment: http://stackoverflow.com/comment/89068712
downvote count: 0
has comment: http://stackoverflow.com/comment/89068612
score: 1
has comment: http://stackoverflow.com/comment/89068819
upvote count: 1
has comment: http://stackoverflow.com/comment/89071348
has comment: http://stackoverflow.com/comment/89075432
has comment: http://stackoverflow.com/comment/89068869
has comment: http://stackoverflow.com/comment/89067808
has comment: http://stackoverflow.com/comment/89069326
answers question: http://stackoverflow.com/q/51037737
has comment: http://stackoverflow.com/comment/89067520
has comment: http://stackoverflow.com/comment/89068565
type: Answer
has comment: http://stackoverflow.com/comment/89068093

http://stackoverflow.com/a/51063328
has comment: http://stackoverflow.com/comment/89140906
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51060627
has body: I'd try by putting your steps as strings, sequences as substrings: import pandas as pd def get_seq(s): return [s[a:b] for a in range(len(s)) for b in range(a+2, len(s)+1)] df = pd.DataFrame({'steps': ['ABCD', 'ACD', 'ADB']}) df['seq'] = df.steps.apply(get_seq) df Out: steps seq 0 ABCD [AB, ABC, ABCD, BC, BCD, CD] 1 ACD [AC, ACD, CD] 2 ADB [AD, ADB, DB] first requested result: sequence counter all_seq = df.seq.apply(pd.Series).stack().values all_seq Out: array(['AB', 'ABC', 'ABCD', 'BC', 'BCD', 'CD', 'AC', 'ACD', 'CD', 'AD', 'ADB', 'DB'], dtype=object) df_count = pd.DataFrame({'seq': all_seq, 'cntr': 1}) df_count.groupby('seq').count().T # .T only for shorter output here below Out: seq AB ABC ABCD AC ACD AD ADB BC BCD CD DB cntr 1 1 1 1 1 1 1 1 1 2 1 second requested result: one hot encoded table df_ohe = pd.DataFrame() for seq in set(all_seq): df_ohe[seq] = df.steps.str.contains(seq) df_ohe Out: ABCD BCD AC AB ABC AD ADB DB BC ACD CD 0 True True False True True False False False True False True 1 False False True False False False False False False True True 2 False False False False False True True True False False False or if you rather like zeros and ones: df_ohe.astype(int) Out: ABCD BCD AC AB ABC AD ADB DB BC ACD CD 0 1 1 0 1 1 0 0 0 1 0 1 1 0 0 1 0 0 0 0 0 0 1 1 2 0 0 0 0 0 1 1 1 0 0 0
answers question: http://stackoverflow.com/q/51060627
has comment: http://stackoverflow.com/comment/89119170
has comment: http://stackoverflow.com/comment/89127685
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/89019734
score: 0
comment on: http://stackoverflow.com/q/51013520
has text: How working `data[Indexlist]` ?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51017831
has comment: http://stackoverflow.com/comment/89054340
accepted answer of: http://stackoverflow.com/q/51014205
score: 4
answers question: http://stackoverflow.com/q/51014205
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: Try this code: # opens 'More actions' menu more_action_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@aria-label = 'More actions']"))) more_action_btn.click() # clicks on 'open transcription' button open_trancript_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//paper-listbox[@id = 'items']/ytd-menu-service-item-renderer"))) open_trancript_btn.click()
has comment: http://stackoverflow.com/comment/89054926
downvote count: 0
has comment: http://stackoverflow.com/comment/110348418

http://stackoverflow.com/comment/89248211
score: 0
comment on: http://stackoverflow.com/a/51104145
type: AnswerComment
type: Comment
has text: thanks for advice! I think that's the problem as well, since they are multiple dictionaries in my variable. and it only print one to excel. And I have no idea how to fix it.

http://stackoverflow.com/a/51147818
has comment: http://stackoverflow.com/comment/89299420
has comment: http://stackoverflow.com/comment/89292103
score: 3
has comment: http://stackoverflow.com/comment/89299540
answers question: http://stackoverflow.com/q/51144365
upvote count: 3
type: Answer
downvote count: 0
has body: if one function deep in the callstack is async, do I need to make the whole stack async and put await at every call? The answer depends on what exactly the functions in the call stack do, but most likely yes. await affects requires the async function to communicate with its caller - either the awaiter or the event loop driver - in order to ensure suspension/resumption of its execution. A non-async function can participate in the call stack without awaiting, but then it can only be used to transmit the coroutine object and it cannot examine the data. For example, func3 could be implemented as either: async def func3(datasource): return await datasource.getData() or: def func3(datasource): return datasource.getData() But the first function could examine (or log, etc.) the data returned by getData, whereas the second one exits immediately and returns the coroutine object which someone else must await. Can I interchangeably pass FileDataSource and SocketDataSource to func1 or do I need to change the whole call hierarchy based on async vs non-async calls? Once you make all the functions in the call stack async, you won't be able to pass FileDataSource, but that doesn't mean you have to have two separate call hierarchies. Just implement FileDataSource as trivially "async" by changing def getData() to async def getData() (and otherwise leaving the implementation unchanged), and it will work for async usage, provided it doesn't actually block.

http://stackoverflow.com/comment/89170675
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51091105
has text: From the [documentation](http://pyautogui.readthedocs.io/en/latest/screenshot.html), `locateOnScreen` returns `None` if the image is not within the screen.

http://stackoverflow.com/q/51133892
favorite count: 0
accepted answer: http://stackoverflow.com/a/51133947
has title: How would I alter this integer item to concatenate into a list correctly? (Python)
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I am attempting to create a new multidimensional list, with each item consisting of a list of words taken from a list of taggedDocuments, and an integer representing a label. The issue I am having is that attempting to append both the list of words and the integer value for the label to the new list returns: TypeError: can only concatenate list (not "int") to list My code is as follows: labelled_docs = [] def DocLabel(docs,labels): i = 0 while i &lt; len(docs): templist = [] templist.append(docs[i]) labelled_docs.append(templist + labels[i]) del templist [:] i += 1 listed_docs = list(documents) listed_labels = clusterer.labels_.tolist() DocLabel(listed_docs,listed_labels) I'm struggling to work out how I need to change the listed_labels item in order to allow the lists to concatenate correctly. I've done some research into the problem, however I can't seem to find anything pertaining to the particular issue i'm having.
type: Question
has comment: http://stackoverflow.com/comment/89252220
has answer: http://stackoverflow.com/a/51133947
score: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51043766
has comment: http://stackoverflow.com/comment/89079136
favorite count: 0
has title: Mapping dictionary key values in a list
has comment: http://stackoverflow.com/comment/89079026
has comment: http://stackoverflow.com/comment/89078685
has comment: http://stackoverflow.com/comment/89079051
has answer: http://stackoverflow.com/a/51044121
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89079197
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51044121
has body: Suppose I have list t=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0] and it's subset as t_old=[3, 3, 4, 0, 0] now I have to calculate the fequency of items which are not in t_old( [3,1, 0, 4, 3, 3, 3, 0]), which I have calculatedN={0:2,1:1,3:3,4:1} but after that, I have to map these values in a list Nk of size 5 such that N={0:2,1:1,3:4,4:1} so list will be NK=[2,1,0,4,1] 0->2,1->1,2->0 (since no frequency of 2),3->3,4->1 so NK is[2,1,0,4,1] also the order is important My code is from collections import Counter, defaultdict import operator t=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0] t_old=[3 ,3, 4, 0, 0] cluster=5 nr=[] k=len(t)-len(t_old) print("Value of k is\n",k) z=len(t_old) while(k): nr.append(t[z]) z+=1 k-=1 print("Value of z is\n",nr) nr=Counter(nr) #Counter that calculates the item that are not in t_old print("counter is\n",nr) d1 = dict(sorted(nr.items(), key = lambda x:x[0])) #Sorting the nr according to the key print("Value of sorted dictonary is\n",d1) So I want the output in the form of list NK is[2,1,0,4,1] how can I get that output pls help thanks in advance
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89078652
has comment: http://stackoverflow.com/comment/89078814

http://stackoverflow.com/q/51027813
has title: How to do Math Functions on Lists within a List
score: 1
tagged with: math
has answer: http://stackoverflow.com/a/51027948
type: Question
has answer: http://stackoverflow.com/a/51027865
downvote count: 0
has body: I'm very new to python (using python3) and I'm trying to add numbers from one list to another list. The only problem is that the second list is a list of lists. For example: [[1, 2, 3], [4, 5, 6]] What I want is to, say, add 1 to each item in the first list and 2 to each item in the second, returning something like this: [[2, 3, 4], [6, 7, 8]] I tried this: original_lst = [[1, 2, 3], [4, 5, 6]] trasposition_lst = [1, 2] new_lst = [x+y for x,y in zip(original_lst, transposition_ls)] print(new_lst) When I do this, I get an error can only concatenate list (not "int") to list This leads me to believe that I can't operate in this way on the lists as long as they are nested within another list. I want to do this operation without flattening the nested list. Is there a solution?
favorite count: 0
has comment: http://stackoverflow.com/comment/89048611
tagged with: python-3.x
tagged with: nested-lists
has answer: http://stackoverflow.com/a/51027867
answer count: 5
possible better answer: http://stackoverflow.com/a/51027865
upvote count: 1
has answer: http://stackoverflow.com/a/51028105
tagged with: python
has comment: http://stackoverflow.com/comment/89048893
accepted answer: http://stackoverflow.com/a/51028105
has answer: http://stackoverflow.com/a/51027929
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/51094498
has comment: http://stackoverflow.com/comment/89176869
has answer: http://stackoverflow.com/a/58051189
has body: I'm trying to solve this problem. I have seen other solutions that involve lists and using recursion but I'm interested in learning how to solve this with loops and I can't seem to get the right output. (i.e. no regular expressions, no tuples, no methods of string, etc.) input: caaabbbaacdddd expected output:empty string input:abbabd expected output:bd below is my code i have found other methods to solve this problem im just looking for the most basic solution for this. answer = input("enter a string: ") new_answer = "" #while answer != new_answer: if answer == "": print("goodBye!") #break p = "" for c in answer: if p != c: new_answer += p p = c else: p = c print(new_answer) the commented out part is to make the whole program loop through to verify thier is no more duplicates.
has answer: http://stackoverflow.com/a/51094884
has answer: http://stackoverflow.com/a/51094591
has answer: http://stackoverflow.com/a/51094719
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89176951
has answer: http://stackoverflow.com/a/51094629
has comment: http://stackoverflow.com/comment/89176842
has title: Remove all adjacent duplicates using loops
type: Question
has comment: http://stackoverflow.com/comment/89176877
score: 0

http://stackoverflow.com/comment/89275392
score: 0
has text: python3 makes your pythonic life much easier! @MattClark
comment on: http://stackoverflow.com/a/51145499
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89268927
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51142349
score: 1
has text: I'm not sure how this would run in Spyder and not the regular Python interpreter.

http://stackoverflow.com/comment/89250594
type: Comment
has text: @kabanus Yes. df1 contains some nan values. Does it affect the equality?
comment on: http://stackoverflow.com/q/51132934
score: 0
type: QuestionComment

http://stackoverflow.com/q/51137110
accepted answer: http://stackoverflow.com/a/51211958
type: Question
upvote count: 5
has title: Right place to put custom nbconvert templates
linked to: http://stackoverflow.com/q/64127278
has answer: http://stackoverflow.com/a/62658376
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
has body: I've made a custom nbconvert template and want it to be accessible from any folder where I launch nbconvert utility. Where should I put my template? I couldn't find anything in official docs. I have already tried usual places for jupyter configs, like /usr/share/jupyter, ~/.local/share/jupyter, ~/.jupyter, to no avail. The only place I've found so far is the folder where python package lives: $ pip show nbconvert | grep Location | cut -d" " -f2 /usr/lib/python3.6/site-packages If I create nbconvert/templates/html directory there and put my template in it, nbconvert --to html --template &lt;my_template_name&gt; ... works fine. But this is an ugly hack which I'll need to re-do every time I update nbconvert. Seems that I can provide nbconvert with environment variable, but I would prefer to avoid this option.
has answer: http://stackoverflow.com/a/51211958
tagged with: nbconvert
score: 5
possible better answer: http://stackoverflow.com/a/58907598
tagged with: python
has answer: http://stackoverflow.com/a/58907598
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65036772
tagged with: jinja2

http://stackoverflow.com/q/51023739
has comment: http://stackoverflow.com/comment/89072159
answer count: 1
tagged with: neural-network
tagged with: keras
has body: I want to predict an x, y coordinate based on n inputs using keras. I am unclear why my network won't improve after about 5 epochs. I don't understand why the network values such as x=2.9 and y=2.1 if my input variables vary from 5-14(x) and 5-11(y). How can i get better predictions? Data: input: [[-92. 0. -83. 0. 0. 0. ] [ 0. 0. 0. -82. 0. 0. ] ... [-65.5 -82. 0. 0. 0. 0. ]] output: [[ 5 5] [ 5 5] ... [11 14]] Results: Predicted: [4.396636 4.019871] label: [11 14] Difference: 16.583492755889893 Predicted: [2.9728146 2.1784768] label: [11 14] Difference: 19.848708629608154 Predicted: [3.9281645 4.2113876] label: [11 14] Difference: 16.860447883605957 Network: from keras.models import Sequential from keras.layers import * model = Sequential() model.add(Dense(16, input_dim = ipad_test_numpy_input.shape[1], activation='linear')) model.add(Dense(8, activation='linear')) model.add(Dense(2, activation='linear')) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(ipad_numpy_input, ipad_numpy_labels, epochs=50, batch_size=5) score = model.evaluate(ipad_test_numpy_input, ipad_test_numpy_labels, batch_size=5)
score: 0
tagged with: python
tagged with: prediction
type: UnansweredQuestion
tagged with: regression
has answer: http://stackoverflow.com/a/51024203
type: Question
has title: Multidimensional regression with keras

http://stackoverflow.com/comment/102739994
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51119857
score: 0
has text: pd.to_numeric didn't work for me. as_type(float) did.

http://stackoverflow.com/q/51014274
favorite count: 0
has comment: http://stackoverflow.com/comment/89021337
has comment: http://stackoverflow.com/comment/89021804
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89021309
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51014476
type: Question
has body: I'm trying to assign a unique value to each new car. How do I add the items via d[new_ID] = (new dictionary items) or the update() method? # Create blank dictionary d = {} # The for loop executes until user has filled in each statement for i in range(5): brand = str(input("Enter you car brand: ")) model = str(input("Enter you car model: ")) begodometer = str(input("Enter your starting odometer reading: ")) endodometer = str(input("Enter your ending odometer reading: ")) estmpg = str(input("Enter estimated miles per gallon: ")) # Not sure how to add ID key items to dictionary and then use update() # Print dictionary print(d) break
answer count: 1
tagged with: key
score: 0
has title: Can't figure out how to store input to dictionary
accepted answer: http://stackoverflow.com/a/51014476
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/89259512
score: 0
comment on: http://stackoverflow.com/q/51137309
type: Comment
has text: If that's the only blank line, don't go looking for "find me" and then try to get rid of the blank line before that: Instead, just look for the blank line itself.
type: QuestionComment

http://stackoverflow.com/a/51071549
score: 0
answers question: http://stackoverflow.com/q/51071467
has body: You can simply treat Y as a list of indices for your desired partition. xs = [[],[]] for a, b in zip(X, Y): xs[b].append(a) bad, good = xs
type: Answer

http://stackoverflow.com/q/51071288
tagged with: regex
has comment: http://stackoverflow.com/comment/89132943
duplicate of: http://stackoverflow.com/q/29771901
answer count: 0
has body: I am not sure where the small mistake is being made, but I want to remove all special characters including numbers from a text. I used this: def remove_special_chars(text): """ Method to remove special characters """ print("original Text: {}\n".format(text)) pattern=r'[^a-zA-z.\s]' text=re.sub(pattern,"",text) print("Modified text: {}".format(text)) And I get this: remove_special_chars("Hi How_abc.com_are you!. hello_123@gmail.com?_") original Text: Hi How_abc.com_are you!. hello_123@gmail.com?_ Modified text: Hi How_abc.com_are you. hello_gmail.com_ So while everything else seems to work fine, I am not sure why _ is not getting removed when it is not there in character class?
has comment: http://stackoverflow.com/comment/89132550
type: Question
linked to: http://stackoverflow.com/q/29771901
score: 0
has comment: http://stackoverflow.com/comment/89132807
has comment: http://stackoverflow.com/comment/89132443
has title: Removing Underscore from text
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89300851
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51158537
type: QuestionComment
has text: What are you using to open the file, where you see the special character? Could you show what you’ve tried to remove it? Note that U+00A0 is a no-break space, so it’s already whitespace.

http://stackoverflow.com/q/51118805
score: 1
has title: Can't find text element with selenium
has body: I'm trying to use Selenium to create a new message in my mailbox. I have a problem with finding napisz (en: 'write') button on my e-mail website. I tried to use driver.find_element_by_link_text but it doesn't work. I've managed to go workaround this problem using xpath but I'm very curious why the first method fails. import time from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('https://profil.wp.pl/login.html?zaloguj=poczta&amp;url=https://poczta.wp.pl/profil/') elem_login = browser.find_element_by_name('login_username') elem_login.send_keys('stack_scraper_wp@wp.pl') elem_password = browser.find_element_by_name('password') elem_password.send_keys('thankyouforhelp') elem_zaloguj_button = browser.find_element_by_id('btnSubmit') elem_zaloguj_button.click() browser.get('https://poczta.wp.pl/d635/indexgwt.html#start') elem_napisz_button = browser.find_element_by_link_text('napisz') elem_napisz_button.click() EDIT: I've tried to used same xpath today but it failed. Is it possible that it's somehow dynamic causing the problem?
type: Question
has comment: http://stackoverflow.com/comment/89223806
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89226478
tagged with: selenium
tagged with: web-scraping
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89223766
has comment: http://stackoverflow.com/comment/89223638
has answer: http://stackoverflow.com/a/51118868
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51118868
downvote count: 0

http://stackoverflow.com/comment/89420602
has text: Have you tried using a different file to test that its not image.asp that is broken?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51165448

http://stackoverflow.com/comment/89108718
type: Comment
comment on: http://stackoverflow.com/a/51058966
has text: the asker clearly stated that he knows how to do it for one string. I intended to give direction instead of solving the homework. But haters gonna hate ¯\_(ツ)_/¯
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89275566
type: QuestionComment
comment on: http://stackoverflow.com/q/51145637
has text: Share your current code. Remember to format the code with { } or ctrl-k
score: 0
type: Comment

http://stackoverflow.com/comment/89303725
has text: @Agile_Eagle, I've amended the both of my comments, apologies about the confusion. You can see the full stack in my previous comment.
type: Comment
comment on: http://stackoverflow.com/q/51157679
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89191780
has text: What is the meaning of a dot product and a scalar in Python? Is the scalar broadcast to a vector? Does that make sense?
type: AnswerComment
comment on: http://stackoverflow.com/a/51095430
type: Comment
score: 0

http://stackoverflow.com/comment/89027093
has text: Uhm that makes more sense now. Thank you for your response. :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51015385

http://stackoverflow.com/comment/89181206
comment on: http://stackoverflow.com/a/51096795
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the quick answer!

http://stackoverflow.com/comment/89172646
type: AnswerComment
type: Comment
has text: @ZelelB: Check my new answer, with more details and an improved routine.
comment on: http://stackoverflow.com/a/51091744
score: 1

http://stackoverflow.com/a/69870245
score: 0
answers question: http://stackoverflow.com/q/51124383
type: Answer
has body: Using a JSON tokenizer makes this a very simple and efficient task, as long as you have an anchor to search for in the original document that allows you to at least identify the beginning of the JSON blob. This uses json-five to extract JSON from HTML: import json5.tokenizer with open('5f32d5b4e2c432f660e1df44.html') as f: document = f.read() search_for = "window.__INITIAL_STATE__=" i = document.index(search_for) j = i + len(search_for) extract_from = document[j:] tokens = json5.tokenizer.tokenize(extract_from) stack = [] collected = [] for token in tokens: collected.append(token.value) if token.type in ('LBRACE', 'LBRACKET'): stack.append(token) elif token.type in ('RBRACE', 'RBRACKET'): stack.pop() if not stack: break json_blob = ''.join(collected) Note that this accounts for the JSON both being a complex (object, list) or scalar type.

http://stackoverflow.com/comment/89169404
comment on: http://stackoverflow.com/q/51090548
type: Comment
type: QuestionComment
has text: I find this to be a super helpful tool in learning about regex https://regex101.com/
score: 1

http://stackoverflow.com/comment/89258579
type: QuestionComment
comment on: http://stackoverflow.com/q/51137262
score: 0
type: Comment
has text: `timedelta` is a period. So you can't compare a period with a datetime

http://stackoverflow.com/comment/89303583
type: Comment
type: QuestionComment
has text: Your favorite binary file viewer is your friend in this case. I don't know python or would suggest a powershell script to dump a bit of your file as hex.
comment on: http://stackoverflow.com/q/51160071
score: 0

http://stackoverflow.com/a/51061448
answers question: http://stackoverflow.com/q/51060585
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89112791
type: Answer
has body: You can use a singleton class wrapper. In brief in singleton design pattern you will only have one instance from a class not more and every time you instantiate that class it will return that one instance. do it once for ever. like this. class SingletonMb: instance = None def __new__(cls, *args, **kwargs): if not cls.instance: cls.instance = mb cls.instance.set_useragent("**", "1.0", "**@gmail.com") cls.instance.set_hostname("http://sss") return cls.instance else: return cls.instance and whenever you want to use the configured mb you can use SingletonMb() that refers to that one single configured object that is made from mb. and use package capability like this: configuredMb = SingletonMb() configuredMb.package_capability("param")

http://stackoverflow.com/q/51124037
linked to: http://stackoverflow.com/q/11848381
type: Question
tagged with: multiprocessing
has title: Trying to copy back elements in Array works with integers but not with strings in Multiprocessing Python module
tagged with: string
has body: I am trying to write a process which does some computation on an Array filled with strings using the multiprocessing module. However, I am not able to get back the results. This is just a minimalist code example: from multiprocessing import Process, Value, Array from ctypes import c_char_p # Process def f(n, a): for i in range(0,10): a[i] = "test2".encode('latin-1') if __name__ == '__main__': # Set up array arr = Array(c_char_p, range(10)) # Fill it with values for i in range(0,10): arr[i] = "test".encode('latin-1') x = [] for i in range(0,10): num = Value('d', float(i)*F) p = Process(target=f, args=(num, arr,)) x.append(p) p.start() for p in x: p.join() # THis works print(num.value) # This will not give out anything print(arr[0]) The last line won't print out anything, despite it being filled or altered. The main thing that concerns me, is when changing the code to just simply using integers it will work: from multiprocessing import Process, Value, Array from ctypes import c_char_p def f(n, a): for i in range(0,10): a[i] = 5 if __name__ == '__main__': arr = Array('i',range(10)) for i in tqdm(range(0,10)): arr[i] = 10 x = [] for i in range(0,10): num = Value('d', float(i)*F) p = Process(target=f, args=(num, arr,)) x.append(p) p.start() for p in x: p.join() print(num.value) print(arr[0]) My Best guess is that this has something to do with the fact that the string array is acutally filled with char arrays and an integer is just one value, but I do not know how to fix this
score: 0
has answer: http://stackoverflow.com/a/51131743
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51103991
type: Answer
has comment: http://stackoverflow.com/comment/89196408
downvote count: 0
has comment: http://stackoverflow.com/comment/89196221
answers question: http://stackoverflow.com/q/51103952
score: 2
has body: Numpy can do this by telling shape what you want the shape to be: import numpy as np X1 = np.zeros((768, 1024, 9)) X = X1.reshape(768*1024, 9) print(X.shape)
upvote count: 2
has comment: http://stackoverflow.com/comment/89196438
has comment: http://stackoverflow.com/comment/89206652
has comment: http://stackoverflow.com/comment/89214450
has comment: http://stackoverflow.com/comment/89208917

http://stackoverflow.com/a/51158904
has comment: http://stackoverflow.com/comment/89301928
answers question: http://stackoverflow.com/q/51158551
has comment: http://stackoverflow.com/comment/89305557
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51158551
type: Answer
has body: According to the docs, eval "parses and evaluates the argument as a python expression". In other words, it's applying the same processing that is applied if you write x = "foobar \n" inside a program or the IDLE. In this example, \n gets turned into a newline-character (which, note, is not identical to the literal \n). If you typed x = "\x27" into the IDLE, you'd get x == "'". The x27 is escaped because of the backslash and thus changed during evaluation. If you escape the backslash, then x27 is not changed during evaluation. Instead, you simply get a string with a backslash followed by x27. Now if you evaluated that string again, you only have one backslash left - seemingly escaping x27. Thus, it is changed to '. Another way to look at this: eval("\x27") evaluates the argument twice, but it is only changed the first time, to "'". eval("\\x27") also evaluates the argument twice, first to \x27, then to "'". Here's an easier example to demonstrate how this works: &gt;&gt;&gt; x = "\"foobar\"" &gt;&gt;&gt; x == "foobar" False &gt;&gt;&gt; x == "\"foobar\"" True &gt;&gt;&gt; x = eval(x) # changes value of x from "foobar" to just foobar. Still string though, thus still "" &gt;&gt;&gt; x == "foobar" True &gt;&gt;&gt; x == "\"foobar\"" False Look at it like this: The right hand side of y = "2" contains two components: the information that y should be of type string, expressed using the two ", and the value of that string, expressed by the character 2. The separation of these two aspects is done during evaluation of the code you write. The string object itself never sees the " during initialization. So in the above example, after the first line, we have x of type str with value "foobar". If you evaluate that again, the " are interpreted this time not as part of the value of x but as the type of x. So eval("\"foobar\"") basically transforms the string "foobar" to foobar, which, if you want to use that using the language Python, you have to write as "\"foobar\"" and "foobar".
upvote count: 3
has comment: http://stackoverflow.com/comment/89301976
score: 3
has comment: http://stackoverflow.com/comment/89302333

terminal
tags question: http://stackoverflow.com/q/51067991
tags question: http://stackoverflow.com/q/51071560
tag name: terminal
tags question: http://stackoverflow.com/q/51019622
tags question: http://stackoverflow.com/q/51126787
tags question: http://stackoverflow.com/q/51105540
tags question: http://stackoverflow.com/q/51029426
tags question: http://stackoverflow.com/q/51092023
type: Tag
tags question: http://stackoverflow.com/q/51128298
tags question: http://stackoverflow.com/q/51069486
tags question: http://stackoverflow.com/q/51116277

http://stackoverflow.com/comment/89152559
has text: @zindarod I have removed noise in my image and wrote the answer. I need to smoothen the text clearer without noise. Can you please suggest me a solution for smoothening my output image?
comment on: http://stackoverflow.com/q/51077990
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/101504569
type: QuestionComment
comment on: http://stackoverflow.com/q/51045716
has text: I'm running into this exact issue as well. Did you ever find a solution?
score: 0
type: Comment

http://stackoverflow.com/comment/89207922
type: Comment
comment on: http://stackoverflow.com/q/51109250
has text: I've never used them so not going to mark this as an answer as it might be wrong but sockets might be worth looking into. [Flask-SocketIO](https://flask-socketio.readthedocs.io/en/latest/) The reason your view isn't updating is when you hit the endpoint /home in your browser it runs the method `output_log` once and calls `render_template`. That method handles the conversion to html/what to send to your browser along with subbing values into Jinja templates. That only happens once. Your browser would have to initiate another request to get an update. That's why we use AJAX and sockets.
score: 1
type: QuestionComment

http://stackoverflow.com/a/51122290
type: Answer
has comment: http://stackoverflow.com/comment/89231253
has body: It seems the go to approach for persistent threads is to run a cprofile instance per thread, then combine the results, better explained here: https://stackoverflow.com/a/2218592/9981387
answers question: http://stackoverflow.com/q/51121515
score: 0

http://stackoverflow.com/comment/89192570
comment on: http://stackoverflow.com/a/51102626
type: Comment
has text: Your a life saver! Thank you for all your help.
type: AnswerComment
score: 0

http://stackoverflow.com/a/51054354
upvote count: 2
has body: The reason why you fail with assign , cause in each for loop you are assign a Math with new value , like below which will only show the last one and present to the result after the for loop 0 0.0 1 10.0 2 NaN 3 NaN 4 NaN 5 NaN Name: col3, dtype: float64 0 NaN 1 NaN 2 NaN 3 NaN 4 20.0 5 NaN Name: col3, dtype: float64 You can do it with below df.loc[df.col1.isin(items),'math']=df.col3*10 df Out[85]: col1 col2 col3 math 0 A 2 0 0.0 1 A 1 1 10.0 2 B 9 9 NaN 3 NaN 8 4 NaN 4 D 7 2 20.0 5 C 4 3 NaN
answers question: http://stackoverflow.com/q/51054253
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/51064563
tagged with: range
tagged with: python
has title: Verify if a string consists only of a range of numbers Python 2.7
accepted answer: http://stackoverflow.com/a/51065234
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51064989
score: 1
has answer: http://stackoverflow.com/a/51065442
has body: I need to verify if a string is a correctly formatted range of numbers in Python2.7, i mean the range that we use for example when choosing some specific pages to print, like this: 1,3,5-7, 10, 15 - 20 I would like it to accept white-spaces around the dashes and the comma, since often people tend to use white-spaces in such ranges: I tried regex with not much luck. There is re.fullmatch in Python 3 that apparently only matches if the whole string matches the pattern, it does not exist in Python 2.7, however i tried this way of doing it in Python 2 withch apparently works properly but my regex seems to be wrong. I tried many different regexs and all of them failed in one or another way, the last one allowed wrong characters in the beginning of the line (this is for commas only, didn't get to dashes yet): ^\d+$|(\d+)(\s?)(,{1})(\s?)(\d+) I am not bound to use the regex for this, however it would be nice to know how this can be fixed with regex.
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51065108
has comment: http://stackoverflow.com/comment/89119349
possible better answer: http://stackoverflow.com/a/51064989
has comment: http://stackoverflow.com/comment/89119129
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51065234
tagged with: regex
linked to: http://stackoverflow.com/q/30212413
favorite count: 0
has answer: http://stackoverflow.com/a/51065511
upvote count: 2
answer count: 5

http://stackoverflow.com/comment/122378488
type: Comment
type: QuestionComment
has text: this just points out the issue, but does not resolve it. for example properties with no default value passed in to `__init__` is an unhandled case.
score: 1
comment on: http://stackoverflow.com/q/51079503

http://stackoverflow.com/q/51129452
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51133278
has title: How to join tables from two different databases using sqlalchemy expression language / sqlalchemy core?
type: AnsweredQuestion
tagged with: mysql
tagged with: cross-database
tagged with: sqlalchemy
type: Question
linked to: http://stackoverflow.com/q/44564369
upvote count: 5
has comment: http://stackoverflow.com/comment/89250481
has body: I am using MySql. I was however able to find ways to do this using sqlalchemy orm but not using expression language.So I am specifically looking for core / expression language based solutions. The databases lie on the same server This is how my connection looks like: connection = engine.connect().execution_options( schema_translate_map = {current_database_schema: new_database_schema}) engine_1=create_engine("mysql+mysqldb://root:user@*******/DB_1") engine_2=create_engine("mysql+mysqldb://root:user@*******/DB_2",pool_size=5) metadata_1=MetaData(engine_1) metadata_2=MetaData(engine_2) metadata.reflect(bind=engine_1) metadata.reflect(bind=engine_2) table_1=metadata_1.tables['table_1'] table_2=metadata_2.tables['table_2'] query=select([table_1.c.name,table_2.c.name]).select_from(join(table_2,table_1.c.id==table_2.c.id,'left') result=connection.execute(query).fetchall() However, when I try to join tables from different databases it throws an error obviously because the connection belongs to one of the databases. And I haven't tried anything else because I could not find a way to solve this. Another way to put the question (maybe) is 'how to connect to multiple databases using a single connection in sqlalchemy core'.
has answer: http://stackoverflow.com/a/51133278
score: 5
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89116830
has text: First you need to fix your imports and indention. You are importing tkinter twice and trying to import Image and ImageTK twice without even referencing PIL.
score: 1
comment on: http://stackoverflow.com/q/51063462
type: Comment
type: QuestionComment

regex
tags question: http://stackoverflow.com/q/51122020
tags question: http://stackoverflow.com/q/51126527
tags question: http://stackoverflow.com/q/51094378
tags question: http://stackoverflow.com/q/51085492
tags question: http://stackoverflow.com/q/51114418
tags question: http://stackoverflow.com/q/51152680
tags question: http://stackoverflow.com/q/51159898
tags question: http://stackoverflow.com/q/51144050
tags question: http://stackoverflow.com/q/51089650
tags question: http://stackoverflow.com/q/51124383
tags question: http://stackoverflow.com/q/51030955
tags question: http://stackoverflow.com/q/51146989
tag name: regex
tags question: http://stackoverflow.com/q/51114168
tags question: http://stackoverflow.com/q/51071288
tags question: http://stackoverflow.com/q/51111522
tags question: http://stackoverflow.com/q/51013354
tags question: http://stackoverflow.com/q/51033858
tags question: http://stackoverflow.com/q/51021497
tags question: http://stackoverflow.com/q/51122413
tags question: http://stackoverflow.com/q/51096743
tags question: http://stackoverflow.com/q/51031139
tags question: http://stackoverflow.com/q/51090471
tags question: http://stackoverflow.com/q/51042791
tags question: http://stackoverflow.com/q/51073982
tags question: http://stackoverflow.com/q/51041085
tags question: http://stackoverflow.com/q/51043847
tags question: http://stackoverflow.com/q/51107648
tags question: http://stackoverflow.com/q/51111992
tags question: http://stackoverflow.com/q/51050082
tags question: http://stackoverflow.com/q/51085069
tags question: http://stackoverflow.com/q/51025302
tags question: http://stackoverflow.com/q/51048031
tags question: http://stackoverflow.com/q/51053334
tags question: http://stackoverflow.com/q/51023884
tags question: http://stackoverflow.com/q/51074615
tags question: http://stackoverflow.com/q/51162422
tags question: http://stackoverflow.com/q/51066934
tags question: http://stackoverflow.com/q/51044993
tags question: http://stackoverflow.com/q/51051136
tags question: http://stackoverflow.com/q/51064427
tags question: http://stackoverflow.com/q/51144283
tags question: http://stackoverflow.com/q/51161507
tags question: http://stackoverflow.com/q/51122337
tags question: http://stackoverflow.com/q/51065365
tags question: http://stackoverflow.com/q/51145994
tags question: http://stackoverflow.com/q/51121583
tags question: http://stackoverflow.com/q/51154765
tags question: http://stackoverflow.com/q/51069426
tags question: http://stackoverflow.com/q/51109956
tags question: http://stackoverflow.com/q/51124618
tags question: http://stackoverflow.com/q/51153569
tags question: http://stackoverflow.com/q/51073838
tags question: http://stackoverflow.com/q/51050397
tags question: http://stackoverflow.com/q/51154993
tags question: http://stackoverflow.com/q/51021110
tags question: http://stackoverflow.com/q/51124019
tags question: http://stackoverflow.com/q/51141485
tags question: http://stackoverflow.com/q/51067741
tags question: http://stackoverflow.com/q/51143250
tags question: http://stackoverflow.com/q/51159622
tags question: http://stackoverflow.com/q/51032291
tags question: http://stackoverflow.com/q/51138833
tags question: http://stackoverflow.com/q/51035150
tags question: http://stackoverflow.com/q/51027151
tags question: http://stackoverflow.com/q/51090548
tags question: http://stackoverflow.com/q/51069610
tags question: http://stackoverflow.com/q/51129427
tags question: http://stackoverflow.com/q/51109792
tags question: http://stackoverflow.com/q/51064563
tags question: http://stackoverflow.com/q/51035444
tags question: http://stackoverflow.com/q/51130230
tags question: http://stackoverflow.com/q/51091078
tags question: http://stackoverflow.com/q/51079333
tags question: http://stackoverflow.com/q/51092015
tags question: http://stackoverflow.com/q/51028076
tags question: http://stackoverflow.com/q/51166996
tags question: http://stackoverflow.com/q/51052506
tags question: http://stackoverflow.com/q/51027372
tags question: http://stackoverflow.com/q/51047954

http://stackoverflow.com/comment/89147247
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51078910
has text: I don't know what format the keys come in/what the function mapping the values from the text file to them would be. It *seems* (based on the single example provided) that it would be `'C:\\Users\\user\\Desktop\\a\\{}\\{}.shp'.format(shape1, shape1)`.
score: 0

http://stackoverflow.com/a/51060918
downvote count: 2
upvote count: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/51060842
has comment: http://stackoverflow.com/comment/89127481
answers question: http://stackoverflow.com/q/51060842
has comment: http://stackoverflow.com/comment/132520344
score: 5
type: AcceptedAnswer
has body: For Shapely 1.x, you could index the resulting MultiPoint: &gt;&gt;&gt; str(x) 'MULTIPOINT (1 1, 2 0)' &gt;&gt;&gt; print(len(x)) 2 &gt;&gt;&gt; print(x[0].x) 1.0 &gt;&gt;&gt; print(x[0].y) 1.0 If you want a new list with the coordinates, you can use: &gt;&gt;&gt; [(p.x, p.y) for p in x] [(1.0, 1.0), (2.0, 0.0)]
has comment: http://stackoverflow.com/comment/132553513

finance
tags question: http://stackoverflow.com/q/51159950
type: Tag
tags question: http://stackoverflow.com/q/51147667
tags question: http://stackoverflow.com/q/51162010
tag name: finance

http://stackoverflow.com/a/51035767
score: 4
upvote count: 4
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89074602
answers question: http://stackoverflow.com/q/51035246
has body: As far as I can see in the docs, there's class google.appengine.api.mail.Attachment, but class google.appengine.api.mail.EmailMessage does not have any method attach(). Class google.appengine.api.mail.EmailMessage does have an attachment property, and that's why it works when you initialize the email with attachments=[(foo,bar),(foo,bar)]. You're actually creating new instances of google.appengine.api.mail.Attachment (using the tuples as explained in the docs), adding them to an array, and using this array as the attachments property when initializing the email. Notice that in the docs, when they write attachment = mail.Attachment('foo.jpg', 'data'), that mail is a reference to the imported google.appengine.api.mail, and not an instantiated mail object. Getting back to your example (please note that I'm not a python dev and I have not tried it, I'm just looking through the docs and making assumptions), instead of message.attach("certificate.pdf", new_file, "application/pdf") you should probably go more on the way of attachment1 = mail.Attachment("certificate.pdf", new_file, "application/pdf") attachment2 = mail.Attachment("another_certificate.pdf", new_file, "application/pdf") message.attachments = [attachment1, attachment2] It's been years since I played with python, but feel free to explore this ideas and edit my answer in case I got anything wrong (or post your own answer).

http://stackoverflow.com/a/51103523
upvote count: 16
downvote count: 0
type: Answer
score: 16
has body: Dataclasses is much more like namedtuple and the popular attrs package than SimpleNamespace (which isn't even mentioned in the PEP). They serve two different intended purposes. Dataclasses Structured Typed (by default, but optional) Writes most of the boilerplate for basic dunder methods (__init__, __hash__, __eq__, and many more) Provide easy mechanism for default values for attributes Can easily add __slots__ and methods SimpleNamespace "Grab bag" data structure Used where you need more than a dictionary but less than a class Not intended to be use things like __slots__ From the SimpleNamespace documentation: SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead. Since @dataclass is supposed to replace a lot of the use cases of namedtuple, named records/structs should be done with @dataclass, not SimpleNamespace. You may also want to look at this PyCon talk by Raymond Hettinger, where he goes into the backstory of @dataclass and it's use.
answers question: http://stackoverflow.com/q/51082418

http://stackoverflow.com/q/51120502
tagged with: python
has title: Shuffle rows of a dataframe in pandas python brings about different regression results?
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51120651
has body: I am trying to randomise my rows in the dataframe - data before applying linear regression, but i realised the regression results differs after the rows are randomised which shouldn't be the case? Codes which i have tried using: Without row randomisation: data X = data[feature_col] y = data['median_price'] lr = LinearRegression() lr.fit(X, y) With row randomisation: Method 1: data = data.sample(frac=1) Method 2: data = data.sample(frac=1, axis=1) Method 3: from sklearn.utils import shuffle data = shuffle(data) Method 4: data = data.sample(frac=1, axis=1).reset_index(drop=True) Out of the 4 row randomisation methods i have tried, only Method 4 gives the same results as the one where no randomisation is applied. I thought row randomisation does not affects the regression results in any case?
tagged with: dataframe
tagged with: rows
type: Question
tagged with: random
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51120651
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89240480
favorite count: 0
has comment: http://stackoverflow.com/comment/89226628

http://stackoverflow.com/comment/89024090
has text: I have fixed it, I made it str(a) == str(answer):
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51015695

http://stackoverflow.com/comment/89021502
score: 3
type: Comment
has text: Flask doesn't need pip in order to run
type: QuestionComment
comment on: http://stackoverflow.com/q/51014386

http://stackoverflow.com/a/51092109
type: Answer
answers question: http://stackoverflow.com/q/51092035
has body: When you press the "Classify" button, your form on your web-app will pass a multipart form data to the flask application. Then within Python, you'll intercept that and save the file. Python has a great intro on this here: http://flask.pocoo.org/docs/1.0/patterns/fileuploads/
score: 0

http://stackoverflow.com/comment/89280279
score: 0
type: QuestionComment
has text: Why are you not going with the regex option? It should suit your purpose (although if you really want to catch every possible notation, you should go for something bigger like a parser, but I think this is out of this context)
type: Comment
comment on: http://stackoverflow.com/q/51148129

http://stackoverflow.com/q/51032877
has body: Consider this code: client.py import socket import json s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(('127.0.0.1', 8000)) s.send(json.dumps({'text': 'hello world'}).encode("utf-8")) data = s.recv(1024) s.close() print("received data:", data) except Exception as e: print("--&gt;", e) server.py import sys import json from PyQt5.Qt import * # noqa class Server(QDialog): def __init__(self): super().__init__() self.tcp_server = None def run(self): self.tcp_server = QTcpServer(self) if not self.tcp_server.listen(QHostAddress('127.0.0.1'), 8000): print("Can't listen!") self.close() return self.tcp_server.newConnection.connect(self.on_new_connection) def on_new_connection(self): client_connection = self.tcp_server.nextPendingConnection() client_connection.waitForReadyRead() message_dct = json.loads( client_connection.readAll().data().decode("utf-8")) print("received json:", message_dct) block = QByteArray() out = QDataStream(block, QIODevice.ReadWrite) out.writeString(json.dumps({'response': len(message_dct["text"])}).encode("utf-8")) client_connection.disconnected.connect(client_connection.deleteLater) client_connection.write(block) client_connection.disconnectFromHost() if __name__ == '__main__': app = QApplication(sys.argv) server = Server() server.run() sys.exit(server.exec_()) After running server.py and client.py, client.py will print: received data: b'\x00\x00\x00\x11{"response": 11}\x00' I don't understand what's the meaning of the extra bytes around the dictionary (the initial 4 bytes \x00\x00\x00\x11) and the last one (\x00), do they represent TCP metadata information added by QTcpServer? Anyway, I'd like to know what's the proper way to decode the dictionary on client.py so you'll get the dictionary {"response": 11} NS: client.py is intended to run on a python3.3.6 python process where the easiest way to go is by using the standard library (ie: using twisted or external deps is tricky), also... asyncio is not available... that's why I'm us…
tagged with: protocols
answer count: 1
tagged with: python-3.3
has answer: http://stackoverflow.com/a/51033350
tagged with: python
has title: How do you decode QByteArray sent by QTcpServer using python socket module?
type: AnsweredQuestion
score: 0
tagged with: tcp
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/51033350

http://stackoverflow.com/a/51136248
downvote count: 0
has comment: http://stackoverflow.com/comment/89258143
score: 1
has body: I recreated your DataFrame by doing : dat = pd.DataFrame({'Key' : ['A','A','B','B'], 'Measure' : ["# of exams","# of people","# of exams","# of people"],'01/01/18' : [121,1327,124,1110],'01/02/18' : [130,1326,132,1115],'01/03/18' : [115,1323,110,1113],'01/04/18' : [120,1323,118,1116],'01/05/18' : [123,1336,125,1118]}) and I obtained : 01/01/18 01/02/18 01/03/18 01/04/18 01/05/18 Key Measure 0 121 130 115 120 123 A # of exams 1 1327 1326 1323 1323 1336 A # of people 2 124 132 110 118 125 B # of exams 3 1110 1115 1113 1116 1118 B # of people You can obtain what you need to compute by doing something like : listOfSeries = [] for i in range(0,2): listOfSeries += [dat.iloc[:, 0:5].iloc[2*i]/dat.iloc[:, 0:5].iloc[2*i+1]] dnew = pd.DataFrame(listOfSeries) Please note that my columns are not ordered like yours, so you should replace [0:5] by [2:7]. Here's the result : 01/01/18 01/02/18 01/03/18 01/04/18 01/05/18 0 0.091183 0.098039 0.086924 0.090703 0.092066 1 0.111712 0.118386 0.098832 0.105735 0.111807 Now you simply need to add the extra columns you want (the non numeric ones). You can add columns by writing : dnew['Key'] = pd.Series(['A', 'B']) dnew['Measure'] = pd.Series(['# of exams/ppl', '# of exams/ppl']) Since your columns are ordered, you can do it by hand without any loss of information or error. This gives you : 01/01/18 01/02/18 01/03/18 01/04/18 01/05/18 Key Measure 0 0.091183 0.098039 0.086924 0.090703 0.092066 A # of exams/ppl 1 0.111712 0.118386 0.098832 0.105735 0.111807 B # of exams/ppl Hope this solution suits you, and if you need complementary explanations, feel free to ask. -- EDIT -- If you want to do it automatically with respect to the Key column, you can do something like : listOfKeys = list(set(dat['Key'].values)) listOfSeries = [] for i in range(0,len(listOfKeys)): dtemp = dat.loc[dat['Key'] == listOfKeys[i]] serie = dat.iloc[:, 0:5].iloc[dtemp.index[0]]/dat.iloc[:, 0:5].iloc[dtemp.index[1]] serie['Key'] = listOfKeys[i] listOfSeries += [serie] dn…
accepted answer of: http://stackoverflow.com/q/51135558
has comment: http://stackoverflow.com/comment/89257544
has comment: http://stackoverflow.com/comment/89256858
answers question: http://stackoverflow.com/q/51135558
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89257428
type: Answer
has comment: http://stackoverflow.com/comment/89257164

http://stackoverflow.com/comment/89020505
has text: You should probably elaborate on what you expect your function to do. The example you give does not actually process its arguments. The question if multiprocessing is a good way to speed up your code really depends on what you try to accomplish.
comment on: http://stackoverflow.com/q/51013615
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89223994
type: QuestionComment
comment on: http://stackoverflow.com/q/51118799
has text: The test script worked after adding an absolute path, yet my full script is not working even with absolute paths. The issue seems to be somewhere else..
score: 0
type: Comment

http://stackoverflow.com/comment/89105609
type: QuestionComment
comment on: http://stackoverflow.com/q/51056479
score: 0
has text: I've installed tensorflow version 1.8.0 @SuryaTej ok,i'll try using tensorflow 1.5
type: Comment

http://stackoverflow.com/q/51058078
has body: I have to create sub groups with the position of element from a list based on the value of elements which means sub groups will contain the same elements from the list. However, the size of the sub group will depend on the value of the group. Example: A = [2,1,1,2,1] will create [0, 3] [1] [2] [4] I have written the below code. However, all the test cases are not getting passed. I am not getting correct output if A = [2,1,2,1,2,2]. For my case I am getting: 0 2 4 5 1 3 However, expectation is: 0 2 1 3 4 5 Below is my code: A = [2,1,1,2,1] uniqueCounts = [] for x in A: if x not in uniqueCounts: uniqueCounts.append(x) for i in range(len(uniqueCounts)): n = uniqueCounts[i] p = [i for i,x in enumerate(A) if x == n] if(len(p)==1): print(*p) else: q = int(len(p)/n) count = 0 c = 0 while count &lt; q: print(*p[c:n+c]) c = c + n count = count + 1
type: Question
has answer: http://stackoverflow.com/a/51059122
score: -1
answer count: 2
downvote count: 1
tagged with: sublist
favorite count: 0
has answer: http://stackoverflow.com/a/51058126
type: UnansweredQuestion
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/89106546
has comment: http://stackoverflow.com/comment/89119950
has title: Create sub groups with the position of element from a list

http://stackoverflow.com/comment/89200009
score: 1
has text: no matter what you put in STATICFILES_DIRS, it will always look in static folders. for current setup STATICFILES_DIRS is not adding any value. but sure if you put monkey in there it would go and look in monkey folder.
type: AnswerComment
comment on: http://stackoverflow.com/a/51106296
type: Comment

http://stackoverflow.com/a/51142038
has comment: http://stackoverflow.com/comment/89269654
has comment: http://stackoverflow.com/comment/89268750
accepted answer of: http://stackoverflow.com/q/51141989
score: 0
answers question: http://stackoverflow.com/q/51141989
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89269282
has comment: http://stackoverflow.com/comment/89269519
type: Answer
has body: Try printing data. If data is a singleton (a tuple with one element), then you can simply use data = data[0] and then return statement(data). If not, you may just want to use cursor.fetchone() to guarantee that you are returned a singleton.

http://stackoverflow.com/comment/89202357
score: 0
type: Comment
type: QuestionComment
has text: can you sidestep the issue by going directly to the redirected URL? monitor the web traffic going on thru the redirect via the Network tab in Dev tools, and try and replicate it if possible. sometimes it's easier to handle those things w/ `requests` too, but depending on your use case that may not be an option.
comment on: http://stackoverflow.com/q/51107309

image
tags question: http://stackoverflow.com/q/51135742
tags question: http://stackoverflow.com/q/51152059
tags question: http://stackoverflow.com/q/51164445
tags question: http://stackoverflow.com/q/51069729
tags question: http://stackoverflow.com/q/51111247
tags question: http://stackoverflow.com/q/51030150
tags question: http://stackoverflow.com/q/51141800
tags question: http://stackoverflow.com/q/51157322
tags question: http://stackoverflow.com/q/51087390
tags question: http://stackoverflow.com/q/51110497
tags question: http://stackoverflow.com/q/51163040
tags question: http://stackoverflow.com/q/51158106
tags question: http://stackoverflow.com/q/51139028
tags question: http://stackoverflow.com/q/51129506
tags question: http://stackoverflow.com/q/51065102
tags question: http://stackoverflow.com/q/51095013
tags question: http://stackoverflow.com/q/51037616
tags question: http://stackoverflow.com/q/51093801
tags question: http://stackoverflow.com/q/51088946
tags question: http://stackoverflow.com/q/51133545
tags question: http://stackoverflow.com/q/51015662
tags question: http://stackoverflow.com/q/51104612
tags question: http://stackoverflow.com/q/51166806
tags question: http://stackoverflow.com/q/51134632
tags question: http://stackoverflow.com/q/51133962
tags question: http://stackoverflow.com/q/51116707
tags question: http://stackoverflow.com/q/51165514
tags question: http://stackoverflow.com/q/51047220
tags question: http://stackoverflow.com/q/51128826
tags question: http://stackoverflow.com/q/51164645
tags question: http://stackoverflow.com/q/51160298
tag name: image
tags question: http://stackoverflow.com/q/51118032
tags question: http://stackoverflow.com/q/51044836
tags question: http://stackoverflow.com/q/51069677
type: Tag
tags question: http://stackoverflow.com/q/51025418

python
tags question: http://stackoverflow.com/q/51067109
tags question: http://stackoverflow.com/q/51097431
tags question: http://stackoverflow.com/q/51073838
tags question: http://stackoverflow.com/q/51084078
tags question: http://stackoverflow.com/q/51088271
tags question: http://stackoverflow.com/q/51145380
tags question: http://stackoverflow.com/q/51011961
tags question: http://stackoverflow.com/q/51161012
tags question: http://stackoverflow.com/q/51141613
tags question: http://stackoverflow.com/q/51034637
tags question: http://stackoverflow.com/q/51054294
tags question: http://stackoverflow.com/q/51132321
tags question: http://stackoverflow.com/q/51024659
tags question: http://stackoverflow.com/q/51018297
tags question: http://stackoverflow.com/q/51028785
tags question: http://stackoverflow.com/q/51129506
tags question: http://stackoverflow.com/q/51078971
tags question: http://stackoverflow.com/q/51083852
tags question: http://stackoverflow.com/q/51133340
tags question: http://stackoverflow.com/q/51103285
tags question: http://stackoverflow.com/q/51127720
tags question: http://stackoverflow.com/q/51064456
tags question: http://stackoverflow.com/q/51088676
tags question: http://stackoverflow.com/q/51094598
tags question: http://stackoverflow.com/q/51099939
tags question: http://stackoverflow.com/q/51144779
tags question: http://stackoverflow.com/q/51056148
tags question: http://stackoverflow.com/q/51108117
tags question: http://stackoverflow.com/q/51109636
tags question: http://stackoverflow.com/q/51076032
tags question: http://stackoverflow.com/q/51093366
tags question: http://stackoverflow.com/q/51091144
tags question: http://stackoverflow.com/q/51141517
tags question: http://stackoverflow.com/q/51037880
tags question: http://stackoverflow.com/q/51023322
tags question: http://stackoverflow.com/q/51103012
tags question: http://stackoverflow.com/q/51106422
tags question: http://stackoverflow.com/q/51045207
tags question: http://stackoverflow.com/q/51157481
tags question: http://stackoverflow.com/q/51077804
tags question: http://stackoverflow.com/q/51108716
tags question: http://stackoverflow.com/q/51163941
tags question: http://stackoverflow.com/q/51115365
tags question: http://stackoverflow.com/q/51087496
tags question: http://stackoverflow.com/q/51023884
tags question: http://stackoverflow.com/q/51164281
tags question: http://stackoverflow.com/q/51043372
tags question: http://stackoverflow.com/q/51027453
tags question: http://stackoverflow.com/q/51018628
tags question: http://stackoverflow.com/q/51045799
tags question: http://stackoverflow.com/q/51164163
tags question: http://stackoverflow.com/q/51087174
tags question: http://stackoverflow.com/q/51046087
tags question: http://stackoverflow.com/q/51099873
tags question: http://stackoverflow.com/q/51127402
tags question: http://stackoverflow.com/q/51056888
tags question: http://stackoverflow.com/q/51034341
tags question: http://stackoverflow.com/q/51118650
tags question: http://stackoverflow.com/q/51023435
tags question: http://stackoverflow.com/q/51094106
tags question: http://stackoverflow.com/q/51029111
tags question: http://stackoverflow.com/q/51117659
tags question: http://stackoverflow.com/q/51048334
tags question: http://stackoverflow.com/q/51021110
tags question: http://stackoverflow.com/q/51037433
tags question: http://stackoverflow.com/q/51044731
tags question: http://stackoverflow.com/q/51036056
tags question: http://stackoverflow.com/q/51030272
tags question: http://stackoverflow.com/q/51149735
tags question: http://stackoverflow.com/q/51124186
tags question: http://stackoverflow.com/q/51054636
tags question: http://stackoverflow.com/q/51024428
tags question: http://stackoverflow.com/q/51053683
tags question: http://stackoverflow.com/q/51072059
tags question: http://stackoverflow.com/q/51067221
tags question: http://stackoverflow.com/q/51110764
tags question: http://stackoverflow.com/q/51159578
tags question: http://stackoverflow.com/q/51135404
tags question: http://stackoverflow.com/q/51028340
tags question: http://stackoverflow.com/q/51072593

http://stackoverflow.com/comment/89263204
comment on: http://stackoverflow.com/q/51138654
has text: ~ $ pip --version pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89195518
score: 0
type: Comment
type: QuestionComment
has text: I think in your example 0 is seen as a str and not a int, you should verify if x belongs to [0-9] then cast it to int
comment on: http://stackoverflow.com/q/51104040

http://stackoverflow.com/comment/89025940
comment on: http://stackoverflow.com/q/51016711
type: QuestionComment
type: Comment
score: 2
has text: line breaks between `()` are legal so you can hit Enter after the first `join(` for example

http://stackoverflow.com/q/51157212
has body: Getting TypeError when submitting with spark-submit --py-files udf TypeError: 'in &lt;string&gt;' requires string as left operand, not NoneType I have written all the UDF`s in proj_udf.py group_1 =['EAST','NORTH','SOUTH','SOUTHEAST','SOUTHWEST'] group_2 =['AUTORX','CAREWORKS','CHIROSPORT'] mearged_list = group_1 + group_2 str1 = ''.join(mearged_list) def search_list(column): return any(column in item for item in str1) sqlContext.udf.register("search_list_udf", search_list, BooleanType()) When calling this function from pyspark-shell its not throwing any error. When I run this with spark-submit getting following error. Error: File "/hd_data/disk23/hadoop/yarn/local/usercache/hscrsawd/appcache/application_1530205632093_12027/container_1530205632093_12027_01_000007/pyspark.zip/pyspark/worker.py", line 177, in main process() File "/hd_data/disk23/hadoop/yarn/local/usercache/hscrsawd/appcache/application_1530205632093_12027/container_1530205632093_12027_01_000007/pyspark.zip/pyspark/worker.py", line 172, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/hd_data/disk23/hadoop/yarn/local/usercache/hscrsawd/appcache/application_1530205632093_12027/container_1530205632093_12027_01_000007/pyspark.zip/pyspark/worker.py", line 104, in &lt;lambda&gt; func = lambda _, it: map(mapper, it) File "&lt;string&gt;", line 1, in &lt;lambda&gt; File "/hd_data/disk23/hadoop/yarn/local/usercache/hscrsawd/appcache/application_1530205632093_12027/container_1530205632093_12027_01_000007/pyspark.zip/pyspark/worker.py", line 71, in &lt;lambda&gt; return lambda *a: f(*a) File "NAM_Udfs.py", line 115, in search_list return any(column in item for item in str1) File "NAM_Udfs.py", line 115, in &lt;genexpr&gt; return any(column in item for item in str1) TypeError: 'in &lt;string&gt;' requires string as left operand, not NoneType at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193) at org.apache.spark.api.python.PythonRunner$$anon$1.&lt;init&gt;(Py…
has answer: http://stackoverflow.com/a/51160324
score: -3
type: Question
accepted answer: http://stackoverflow.com/a/51160324
tagged with: pyspark
downvote count: 3
upvote count: 0
answer count: 1
favorite count: 0
tagged with: apache-spark
tagged with: python
has title: Type error while submitting custom udf with spark submit
type: AnsweredQuestion

http://stackoverflow.com/q/51126087
has comment: http://stackoverflow.com/comment/89237484
has answer: http://stackoverflow.com/a/51126099
has comment: http://stackoverflow.com/comment/89237542
answer count: 1
has comment: http://stackoverflow.com/comment/89237232
tagged with: python
has comment: http://stackoverflow.com/comment/89237522
has comment: http://stackoverflow.com/comment/89237430
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89237438
has comment: http://stackoverflow.com/comment/89237377
upvote count: 1
has comment: http://stackoverflow.com/comment/89237325
has comment: http://stackoverflow.com/comment/89237360
has comment: http://stackoverflow.com/comment/89237347
downvote count: 1
accepted answer: http://stackoverflow.com/a/51126099
has comment: http://stackoverflow.com/comment/89237257
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89237463
has comment: http://stackoverflow.com/comment/89237304
has comment: http://stackoverflow.com/comment/89237586
has comment: http://stackoverflow.com/comment/89237597
type: Question
has comment: http://stackoverflow.com/comment/89237272
has comment: http://stackoverflow.com/comment/89237303
has body: I have list like this: x = [(('abc', 'def'), 1), (('foo', 'bar'), 0), (('def', 'abc'), 3)] I want to make a list which contains unique elements with its corresponding sum in which the order should not matter.I want list like this: [(('abc', 'def'), 4), (('foo', 'bar'), 0)] What is the efficient way to do this in python? It is different from this as I am asking about tuple of tuple in which the first parameter is unordered.
linked to: http://stackoverflow.com/q/18194712
has title: Convert the list of tuples into set with its corresponding sum efficiently
score: 0

http://stackoverflow.com/a/51025702
answers question: http://stackoverflow.com/q/51025590
accepted answer of: http://stackoverflow.com/q/51025590
type: Answer
score: 3
downvote count: 0
has body: Your csv is delimited by a semi-colon ';', by default the separator for read_csv is ',', pass param sep=';': In[21]: import io t="""col1;col2;col3;col4;col5 6943000;11;1.0;2016-01-01 15:30:31;? 6943000;19;1.0;2016-01-01 15:38:07;? 6943000;13;1.0;2016-01-01 15:54:27;? 6942992;10;1.0;2016-01-01 00:52:59;? 6942993;8;1.0;2016-01-01 12:08:36;?""" df = pd.read_csv(io.StringIO(t), sep=';') df = df.sort_values(by=['col1', 'col4']) df [21]: col1 col2 col3 col4 col5 3 6942992 10 1.0 2016-01-01 00:52:59 ? 4 6942993 8 1.0 2016-01-01 12:08:36 ? 0 6943000 11 1.0 2016-01-01 15:30:31 ? 1 6943000 19 1.0 2016-01-01 15:38:07 ? 2 6943000 13 1.0 2016-01-01 15:54:27 ? Also note that your timestamps are being interpreted as strings, if you want datetime dtype then tell pandas to parse them: In[26]: import io t="""col1;col2;col3;col4;col5 6943000;11;1.0;2016-01-01 15:30:31;? 6943000;19;1.0;2016-01-01 15:38:07;? 6943000;13;1.0;2016-01-01 15:54:27;? 6942992;10;1.0;2016-01-01 00:52:59;? 6942993;8;1.0;2016-01-01 12:08:36;?""" df = pd.read_csv(io.StringIO(t), sep=';', parse_dates=['col4']) df = df.sort_values(by=['col1', 'col4']) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 5 entries, 3 to 2 Data columns (total 5 columns): col1 5 non-null int64 col2 5 non-null int64 col3 5 non-null float64 col4 5 non-null datetime64[ns] col5 5 non-null object dtypes: datetime64[ns](1), float64(1), int64(2), object(1) memory usage: 240.0+ bytes
upvote count: 3
has comment: http://stackoverflow.com/comment/89043908
type: AcceptedAnswer

http://stackoverflow.com/comment/89259609
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51137021
has text: some may think it's missing an attempt. Yes, it's better with an attempt, but I think it's already okay. I'll try to have it reopened
score: 0

http://stackoverflow.com/q/51042742
type: Question
has answer: http://stackoverflow.com/a/51044677
has answer: http://stackoverflow.com/a/51043410
has comment: http://stackoverflow.com/comment/89076601
answer count: 2
has title: Counting number of elements in non-overlapping sub-intervals of array
has body: I want to count the number of elements in non-overlapping subsequences of a list.for example, in lst shown below: lst = [0.2,1.3,2.2,3.5] L = 0.5 for x in lst: lb = x # lowebound ub = x+L # upperbound print(lb,ub) The output is 0.2 0.7 count=1 1.3 1.8 count=1 2.2 2.7 count=1 3.5 4.0 count=1 As we can see, these intervals are non-overlapping. Also,in each of the interval [lb, ub], we have only one element which belongs to lst so count = 1 per interval. However there is a complex case as given below nlst = [0.2,0.6,2.2,3.8] Using above code will create overlapping intervals which we do not want. for instance using above code, we get 0.2 0.7 0.6 1.1 2.2 2.7 3.8 4.3 Now since 0.6 is included in first [0.2,0.7] interval, there is an overlap which we do not want. The desired output is 0.2 0.7 count = 2 2.2 2.7 count = 1 3.8 4.3 count = 1 This problem can be easily solved if the original array is broken down to sub-arrays however in the arrays containing thousands of numbers, such methods become computationally intensive. In the examples above, I am showing intervals as outputs which is just to explain my problem. I only want the count per interval. Could I be helped? Thanks in advance.
tagged with: arrays
downvote count: 0
tagged with: counting
favorite count: 0
accepted answer: http://stackoverflow.com/a/51043410
tagged with: python
has comment: http://stackoverflow.com/comment/89076838
score: 2
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/51044677

http://stackoverflow.com/comment/89035695
comment on: http://stackoverflow.com/a/51021593
score: 0
type: Comment
has text: Same output: "The requested operation requires elevation."
type: AnswerComment

http://stackoverflow.com/q/51072938
upvote count: 5
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51073626
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/89137177
has body: I have a dataframe called "dataframe" that contains a bunch of information of sales on a certain date. Each date entry is in the format of YYYY-MM-DD, and data ranges from 2012 to 2017. I would like to split this data frame into 6 separate dataframes, one for each year. So for example, the first split dataframe will have all the entries from 2012. I think I was able to do this in the code below. I split the dataframe into one for each year and put them in the list "years". However, when I try to run auto_arima on each dataframe I get the error "Found input variables with inconsistent numbers of samples." I think this is because I'm not properly splitting my original dataframe correctly. How do I properly split my dataframe based on year? #Partition data into years years = [g for n, g in dataframe.set_index('Date').groupby(pd.Grouper(freq='Y'))] #Create a list that will hold all auto_arima results for every dataframe stepwise_models = [] #Call auto_arima on every dataframe for x in range(len(years)-1): currentDf = years[x] model = auto_arima(currentDf['price'], exogenous=xreg, start_p=1, start_q=1, max_p=3, max_q=3, m=12, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True) stepwise_models.append(model) #Store current auto_arima result in our stepwise_models[] list
tagged with: data-science
tagged with: statistics
tagged with: pandas
has title: How to split dataframe based on years in python?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pyramid-arima
has answer: http://stackoverflow.com/a/62299655

http://stackoverflow.com/comment/89202252
has text: I think I get my problem I am printing the pair, url and current_url several times, to see if it is able to figure out the redirected url. Till the redirect happens it prints identical thing but breaks when redirects.
comment on: http://stackoverflow.com/q/51107309
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89292369
type: Comment
has text: I will try to do exponential smoothening , but before that I want to ask is changing the date time index to the days variable the right thing to do? Is there any other day to creating the day variables?
type: QuestionComment
comment on: http://stackoverflow.com/q/51154383
score: 1

http://stackoverflow.com/comment/89136634
has text: thanks Wiktor... wil try that
type: QuestionComment
comment on: http://stackoverflow.com/q/51065365
score: 0
type: Comment

http://stackoverflow.com/q/51144569
has comment: http://stackoverflow.com/comment/89273632
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/89275203
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89275096
has answer: http://stackoverflow.com/a/51145436
downvote count: 0
has body: I have three main sections of a main window, where the left side (critical data) should take the entire height of the window, while the data on the right should be split between top and bottom. Data in the lower right is related, but not critical - which is why I'd like it to be un-dockable/closable. The Qt documentation shows an example of this in C++, but I have no idea how to turn this into Python code, as I have no C++ experience. The Qt Designer application limits the user to Left/Right/Top/Bottom, and limiting the maximum width of the widget doesn't allow me to occupy the un-used space (i.e. doesn't allow the list widget on the left to take up the full height of the main window) Long story short, to get a Qdockwidget into the lower right corner, you have to put another dock widget above it (it's still limited to Right/Left/Top/Bottom DockWidgetArea). After looking at the answer from eyllanesc below, I'll post two solutions. First, a simplified version of his code and then a modified version of the code I originally posted. Eyllanesc's translation from the C++ example from I mentioned above: from PyQt4 import QtCore, QtGui class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.resize(600, 600) self.centralWidget = QtGui.QTextEdit() self.setCentralWidget(self.centralWidget) # Upper table widget dock = QtGui.QDockWidget("Upper", self.centralWidget) dock.setAllowedAreas(QtCore.Qt.RightDockWidgetArea) self.tableWidget = QtGui.QTableWidget(dock) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(6) self.tableWidget.setRowCount(7) for i in range(7): item = QtGui.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(i, item) self.tableWidget.verticalHeaderItem(i).setText("Item " + str(i + 1)) for i in range(6): item = QtGui.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(i, item) dock.setWidget(self.tableWidget) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock…
has comment: http://stackoverflow.com/comment/89274182
has comment: http://stackoverflow.com/comment/89274313
has comment: http://stackoverflow.com/comment/89274272
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89274987
has comment: http://stackoverflow.com/comment/89274327
tagged with: python
has comment: http://stackoverflow.com/comment/89273933
has comment: http://stackoverflow.com/comment/89273959
has comment: http://stackoverflow.com/comment/89274245
has title: Restrict a Qdockwidget to a quadrant rather than Left/Right/Top/Bottom
tagged with: qdockwidget
has comment: http://stackoverflow.com/comment/89274251
accepted answer: http://stackoverflow.com/a/51145436
upvote count: 3
has comment: http://stackoverflow.com/comment/89274211
answer count: 1
has comment: http://stackoverflow.com/comment/89274115
has comment: http://stackoverflow.com/comment/89274218

http://stackoverflow.com/a/51080865
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51080695
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51080695
has body: There are 2 possible solutions - add zeros as pointed @Zero in comments: df['day-hour'] = ('Day' + (df['hour'] // 24).add(1).astype(str).str.zfill(2) + ' - ' + (df['hour'] % 24).astype(str).str.zfill(2) ) Or sorted by custom function with 2 fields: df = df[sorted(df.columns,key=lambda x: (int(x.split(' - ')[0][3:]), int(x.split(' - ')[1])))] Better readable: def f(x): a = x.split(' - ') return (int(a[0][3:]), int(a[1])) df = df[sorted(df.columns, key=f)] print (df) Day1 - 10 Day6 - 3 Day9 - 14 Day21 - 9 1 1 1 0 1 2 0 0 1 0

http://stackoverflow.com/comment/89054476
comment on: http://stackoverflow.com/q/51031046
score: 0
has text: `ast.literal_eval` or `eval` may help.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89340526
comment on: http://stackoverflow.com/a/51126207
score: 0
type: Comment
has text: @Topto Yes, I agree. My second attempt would have been ideal if the links order was consistent, but here are a fiew 'gaps' between numbers. The first method produces correct results, but the number of required requests is huge - 40,590 for this query!
type: AnswerComment

http://stackoverflow.com/comment/110230242
type: AnswerComment
has text: I needed Java & Python3 as well (but no pip & flask needed) this solution created a 170mb Docker image. Using openjdk:slim and apt-getting python3 I got >400mb. Both images build roughly equally fast.
type: Comment
comment on: http://stackoverflow.com/a/51171447
score: 0

http://stackoverflow.com/a/51063505
has body: Are you 100% certain the data is stored in UTF-8? Running the command SELECT SERVERPROPERTY('Collation'); should help you determine how data is encoded in the database. I think the default encoding is Latin-1 and that would mean 0xCA is "capital E circumflex (Ê)". You can configure pymssql to access the database using that encoding by adding the argument charset="ISO-8859-1" to your connection arguments.
upvote count: 2
answers question: http://stackoverflow.com/q/51036394
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51121016
type: UnansweredQuestion
tagged with: dart
tagged with: xcode
has body: Facing "Missing XCode Dependency: Python Module "Six" " even after installing six Pip Already installed pip install six Requirement already satisfied: six in /usr/local/lib/python2.7/site-packages (1.11.0) But still flutter doctor asks to install pip Shivas-MacBook-Pro:Flutter shivapokala$ flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel beta, v0.5.1, on Mac OS X 10.13.5 17F77, locale en-US) [✓] Android toolchain - develop for Android devices (Android SDK 27.0.0) [!] iOS toolchain - develop for iOS devices (Xcode 9.4.1) ✗ Missing Xcode dependency: Python module "six". Install via 'pip install six' or 'sudo easy_install six'. [✓] Android Studio (version 3.1) [!] Connected devices ! No devices available ! Doctor found issues in 2 categories.
tagged with: python-module
tagged with: python
has answer: http://stackoverflow.com/a/51121980
has title: Facing "Missing XCode Dependency: Python Module "Six" " even after installing six
tagged with: flutter
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/51024455
has body: I want to input a date/time into influx db from python but not sure how to do this. Python code datetime.datetime.now() currently gives out a format like this : 2018-06-25 13:59:36.698000. I know this format is accepted by influx "1529932431998" which is "2018-06-25T13:13:51.998Z" or "0x1643714427e". Any ideas how i can get python to give me 11 digit number from python? Thanks
favorite count: 0
type: UnansweredQuestion
tagged with: datetime
has answer: http://stackoverflow.com/a/51024536
tagged with: python
tagged with: influxdb
has title: Python: Formatting time for influxdb
type: Question
upvote count: 4
answer count: 2
linked to: http://stackoverflow.com/q/79797
score: 4
has answer: http://stackoverflow.com/a/77345685
downvote count: 0

http://stackoverflow.com/comment/89332323
score: 0
type: Comment
type: QuestionComment
has text: Is that your code in its entirety? I get the exact same string trying to reproduce your issue. By the way you have a typo in the last line of code, should be `wb.save('test.xlsx')` and not `wb.save['test.xlsx']`
comment on: http://stackoverflow.com/q/51165213

http://stackoverflow.com/comment/89109700
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51059494
type: AnswerComment
has text: This was the answer! I might been wrote the whole thread wrong but you indeed helped me out and I do really appreciate it!

http://stackoverflow.com/a/51115224
downvote count: 0
has body: Perhaps you specifically intended to use this JSON-like data structure, but did you consider a hash table lookup schema? &gt;&gt;&gt; wine = [ ... {'Origin': 'A', 'Name': 'w1', 'price': 10000}, ... {'Origin': 'B', 'Name': 'w2', 'price': 2000}, ... {'Origin': 'C', 'Name': 'w3', 'price': 4000}, ... {'Origin': 'D', 'Name': 'w3', 'price': 55000}, ... {'Origin': 'E', 'Name': 'w2', 'price': 63000}, ... {'Origin': 'F', 'Name': 'w6', 'price': 80000} ... ] &gt;&gt;&gt; &gt;&gt;&gt; wine_dict_lookup = {row['Name']: {'Origin': row['Origin'], 'price': row['price']} for row in wine} &gt;&gt;&gt; wine_dict_lookup {'w1': {'Origin': 'A', 'price': 10000}, 'w2': {'Origin': 'E', 'price': 63000}, 'w3': {'Origin': 'D', 'price': 55000}, 'w6': {'Origin': 'F', 'price': 80000}} &gt;&gt;&gt; wish_wine = input('Insert the wine what you want to have : ') &gt;&gt;&gt; try: ... print('wine', wish_wine, 'is', wine_dict_lookup[wish_wine]['price'], '$') ... except KeyError: ... print('Sorry, there is no wine what you want.') ... wine w1 is 10000 $ This problem lends itself really well to a hash table, like a dictionary. Although, if you intend the line if wish_wine in wine[i]['Name']: to serve as a sort of fuzzy-lookup tool (i.e. to be able to match a string like "I want w1", then the different in performance between these two approaches is negligible. The real benefit of using a dictionary is that lookups are O(1), meaning constant-time with respect to how many different wines you have. Your list-lookup is O(n), where n is the number of elements in your wine list, because you're iterating through potentially all wines to find the one that someone looked for.
has comment: http://stackoverflow.com/comment/89216937
type: Answer
answers question: http://stackoverflow.com/q/51115093
upvote count: 1
score: 1

http://stackoverflow.com/comment/89182053
type: QuestionComment
comment on: http://stackoverflow.com/q/51097173
type: Comment
has text: @jezrael, hello sir. like Full-time 740, Other 335, Part-time 330, Type-I 119, Type-II 642, Type-III 165
score: 0

http://stackoverflow.com/q/51087917
type: Question
has comment: http://stackoverflow.com/comment/89164951
has body: I'm rephrasing the question asked here. Python: Trying to Deserialize Multiple JSON objects in a file with each object spanning multiple but consistently spaced number of lines and other posts. But I'm new to JSON and I don't quite know how many of the functions are supposed to work, especially to suit my purpose. I'm working on python 3 with numpy and pandas as well, and was curious if there was any functions that could simplify this. I'm trying to save multiple requests from the google maps API. That API returns a JSON object, one dictionary, of about 52 lines. I have a large dataset and I was hoping to get around 5000 of these JSON objects. I created a function that writes the all of the json objects into one txt file. I have one newline character in between each json object. Here's the code for that... all of this is in a loop that constantly makes requests to the google maps api r = requests.get(url, params=payload) # request json_var = r.json() json_var['tweet_id'] = rows['tweet_id'] json_var['manual_location'] = manual_loc if small==True: print("writing") with open("txt_files/small_geo_json.txt", 'a') as myfile: myfile.write(json.dumps(json_var, indent=4)) myfile.write("\n") I borrowed code from the solution, hoping i interpreted it correctly. I think "n" is supposed to be how many lines your json object takes up, however... def lines_per_n(f, n): for line in f: yield ''.join(chain([line], itertools.islice(f, n - 1))) def extract_cords_from_json(small=False): if small == True: data =[] with open("txt_files/small_geo_json.txt") as infile: for chunk in lines_per_n(infile, 52): print(chunk) jfile = json.loads(chunk) Here's an example json object from the requests.get() call: { "results": [ { "address_components": [ { "long_name": "United States", "short_name": "US", "types": [ "country", "political" ] } ], "formatted_address": "United States", "geometry": { "bounds": { "northeast": { "lat": 71.5388001, "lng": -66.885417 }, "southwest": { "lat": 18.7763, "lng": 1…
score: 0
linked to: http://stackoverflow.com/q/20400818
has comment: http://stackoverflow.com/comment/89164810
has comment: http://stackoverflow.com/comment/89164415
has title: Python: parse multiple JSON objects from one txt file
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89164489
tagged with: python
has comment: http://stackoverflow.com/comment/89164528
answer count: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/89250979
type: Comment
has text: What if the user resizes the columns, or the window?
score: 1
comment on: http://stackoverflow.com/a/51132649
type: AnswerComment

http://stackoverflow.com/q/51026016
has title: character U+ffffffc2 is not in range [U+0000; U+10ffff]
linked to: http://stackoverflow.com/q/50236025
score: 0
has comment: http://stackoverflow.com/comment/89046644
has comment: http://stackoverflow.com/comment/89051544
has comment: http://stackoverflow.com/comment/89047818
has comment: http://stackoverflow.com/comment/89046877
has body: I'm extracting some data from Teradata and got the interesting error; return '' if v is None else str(v) ValueError: character U+ffffffc2 is not in range [U+0000; U+10ffff] Here is how I got it: def none_to_blank(v): return '' if v is None else str(v) cur.execute(sql_extract.format(...)) for r in cur: a = [none_to_blank(x) for x in r] # More lines... As I searched a bit, I found that ffffffc2 is 4294967234 I don't have the permissions to make a change on the data source and I can't skip a row/line/data Is there anyway to convert and use this weird character?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/50024626
has comment: http://stackoverflow.com/comment/89046313
has comment: http://stackoverflow.com/comment/89046288
answer count: 0
linked to: http://stackoverflow.com/q/35162318
type: Question
has comment: http://stackoverflow.com/comment/89045590
tagged with: teradata
tagged with: python

http://stackoverflow.com/comment/89189114
type: AnswerComment
type: Comment
has text: @Oliver so you mean that in `SomethingUnique1` and/or `SomethingUnique2` you have to update the `state` ? You can declare the state as follow to overcome this problem: `protected readonly State state;`. Although the design is a bit bad, it's still better than using `ref`.
comment on: http://stackoverflow.com/a/51100723
score: 0

http://stackoverflow.com/q/51134379
has comment: http://stackoverflow.com/comment/89253701
upvote count: 2
has body: I want to save the input form the entry box into .txt files and it works on the first code and not the second code, but what I need to use is the second code. Code 1: import tkinter as tk def f(): def save(): a = t.get() f = open((a + '.txt'), 'w') f.write(a) f.close() return top = tk.Tk() t = tk.StringVar() e = tk.Entry(top, textvariable = t).pack() b = tk.Button(top, text = 'Save as a file', command = save).pack() top.mainloop() f() Code 2: import tkinter as tk root = tk.Tk() def f(): def save(): a = t.get() f = open((a + '.txt'), 'w') f.write(a) f.close() return top = tk.Tk() t = tk.StringVar() e = tk.Entry(top, textvariable = t).pack() b = tk.Button(top, text = 'Save as a file', command = save).pack() top.mainloop() button = tk.Button(root, text="Button",command=f).pack() root.mainloop()
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/51134758
has title: Saving input from entry box into .txt files
linked to: http://stackoverflow.com/q/48045401
favorite count: 0
possible better answer: http://stackoverflow.com/a/51134758
score: 0
has answer: http://stackoverflow.com/a/51134705
accepted answer: http://stackoverflow.com/a/51134705
tagged with: python
tagged with: file-handling
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89253203
type: Question
has answer: http://stackoverflow.com/a/51134650
type: AnsweredQuestion

http://stackoverflow.com/comment/89178989
score: 0
type: Comment
has text: oh... i did not notice that. It seems like I open multiple doc pages, and looked up on wrong page unconsciously. Thanks very much. Do you know how to achieve same function of graph_rewrite_specs with the KMeansClustering's export_savedmodel method.
type: AnswerComment
comment on: http://stackoverflow.com/a/51095429

numbers
tags question: http://stackoverflow.com/q/51125006
tags question: http://stackoverflow.com/q/51146660
tags question: http://stackoverflow.com/q/51068339
tags question: http://stackoverflow.com/q/51119794
tags question: http://stackoverflow.com/q/51072541
type: Tag
tag name: numbers

http://stackoverflow.com/comment/89219588
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51116376
score: 0
has text: `temp = ET.Element('Attribute NAME="EFG" VALUE="1234"')`. That does not seem like a valid string to pass to the ET.Element constructor.

http://stackoverflow.com/comment/89082446
type: Comment
score: 1
has text: Just to be clear the `roll` method is faster but it's still not vectorised because of the `apply` + `lambda`. The `strides` method is indeed vectorised and an excellent solution if you can understand the logic.
type: AnswerComment
comment on: http://stackoverflow.com/a/51041864

http://stackoverflow.com/q/51061973
score: 0
linked to: http://stackoverflow.com/q/2456148
tagged with: sublimetext3
has comment: http://stackoverflow.com/comment/89113792
has comment: http://stackoverflow.com/comment/89151919
tagged with: python-3.x
has body: Currently I have installed sublime text 3 in Linux for python programming. When I am executing the piece of code, I am getting error, this error is because of Python version sublime 3 is using is 2.7. How can i change the python version from 2.x to latest 3.x in sublime text 3. Here is my piece of code lis = [2, 1, 3, 5, 4] # using len() to print length of list print ("The length of list is : ", end="") print (len(lis)) # using min() to print minimum element of list print ("The minimum element of list is : ", end="") print (min(lis)) # using max() to print maximum element of list print ("The maximum element of list is : ", end="") print (max(lis)) When I am running this program on python 2.x version, I am getting an error as "invalid syntax", but this error is not coming in python 3.x version. Kindly guide me to change the python version of sublime text 3 from 2.x to 3.x
has answer: http://stackoverflow.com/a/51064843
has comment: http://stackoverflow.com/comment/89145488
tagged with: python
has comment: http://stackoverflow.com/comment/89114010
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51062252
linked to: http://stackoverflow.com/q/35667252
has title: How to change python version from 2.x to 3.x in Sublime text 3
type: Question
has answer: http://stackoverflow.com/a/51062252
answer count: 2
has comment: http://stackoverflow.com/comment/89113659
possible better answer: http://stackoverflow.com/a/51064843
duplicate of: http://stackoverflow.com/q/2456148
has comment: http://stackoverflow.com/comment/89142109

http://stackoverflow.com/a/51121549
has comment: http://stackoverflow.com/comment/89228774
has comment: http://stackoverflow.com/comment/89228507
has comment: http://stackoverflow.com/comment/89228576
has comment: http://stackoverflow.com/comment/89228451
score: 2
has comment: http://stackoverflow.com/comment/89228401
has comment: http://stackoverflow.com/comment/89229902
has comment: http://stackoverflow.com/comment/89228650
has comment: http://stackoverflow.com/comment/89228878
has body: For me it working nice, but better is omit apply, because loops under the hoods: m_forecasts = pd.DataFrame({'bnchmk_qty': [4.5,7.8,43.7]}) m_uio = 10.5 b_uio = 4.8 m_forecasts['potential'] = m_forecasts['bnchmk_qty'] * round((m_uio + 1) / (b_uio + 1)) print (m_forecasts) bnchmk_qty potential 0 4.5 9.0 1 7.8 15.6 2 43.7 87.4 I test code generate function column: df = pd.DataFrame({'quantity': {pd.Timestamp('2011-01-31 00:00:00'): 32.21, pd.Timestamp('2011-02-28 00:00:00'): 28.32, pd.Timestamp('2011-03-31 00:00:00'): 27.12, pd.Timestamp('2011-04-30 00:00:00'): 29.56, pd.Timestamp('2011-05-31 00:00:00'): 31.98, pd.Timestamp('2011-06-30 00:00:00'): 26.25, pd.Timestamp('2011-07-31 00:00:00'): 24.75, pd.Timestamp('2011-08-31 00:00:00'): 25.56, pd.Timestamp('2011-09-30 00:00:00'): 26.68, pd.Timestamp('2011-10-31 00:00:00'): 29.12, pd.Timestamp('2011-11-30 00:00:00'): 33.87, pd.Timestamp('2011-12-31 00:00:00'): 35.45}}) print (df) quantity 2011-01-31 32.21 2011-02-28 28.32 2011-03-31 27.12 2011-04-30 29.56 2011-05-31 31.98 2011-06-30 26.25 2011-07-31 24.75 2011-08-31 25.56 2011-09-30 26.68 2011-10-31 29.12 2011-11-30 33.87 2011-12-31 35.45 import statsmodels.api as sm p,d,q = 0,0,0 model = sm.tsa.ARIMA(endog=df['quantity'].astype(float), order=(p, d, q)).fit() ; fsales = model.forecast(12)[0] print (fsales) [29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666 29.23916666] df['Forecast'] = fsales print (df) quantity Forecast 2011-01-31 32.21 29.239167 2011-02-28 28.32 29.239167 2011-03-31 27.12 29.239167 2011-04-30 29.56 29.239167 2011-05-31 31.98 29.239167 2011-06-30 26.25 29.239167 2011-07-31 24.75 29.239167 2011-08-31 25.56 29.239167 2011-09-30 26.68 29.239167 2011-10-31 29.12 29.239167 2011-11-30 33.87 29.239167 2011-12-31 35.45 29.239167 print(sm.version.version) '0.8.0'
has comment: http://stackoverflow.com/comment/89228564
has comment: http://stackoverflow.com/comment/89228364
has comment: http://stackoverflow.com/comment/89228448
downvote count: 0
has comment: http://stackoverflow.com/comment/89228457
has comment: http://stackoverflow.com/comment/89229858
answers question: http://stackoverflow.com/q/51121524
has comment: http://stackoverflow.com/comment/89228840
has comment: http://stackoverflow.com/comment/89228869
has comment: http://stackoverflow.com/comment/89228923
upvote count: 2
has comment: http://stackoverflow.com/comment/89228476
has comment: http://stackoverflow.com/comment/89228437
has comment: http://stackoverflow.com/comment/89228471
type: Answer
has comment: http://stackoverflow.com/comment/89228521
has comment: http://stackoverflow.com/comment/89228541

http://stackoverflow.com/comment/89284440
score: 0
comment on: http://stackoverflow.com/q/51145299
has text: what happens if you execute the code without the ending `;`? `sns.countplot(x="loan_status", data=LoanStats_securev1_2018Q1, palette="Greens_d")`
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/51157481
tags question: http://stackoverflow.com/q/51035607
tags question: http://stackoverflow.com/q/51029193
tags question: http://stackoverflow.com/q/51036056
type: Tag
tags question: http://stackoverflow.com/q/51108227
tags question: http://stackoverflow.com/q/51157813
tags question: http://stackoverflow.com/q/51093533
tags question: http://stackoverflow.com/q/51012134
tags question: http://stackoverflow.com/q/51060346
tags question: http://stackoverflow.com/q/51089194
tags question: http://stackoverflow.com/q/51080943
tags question: http://stackoverflow.com/q/51141436
tags question: http://stackoverflow.com/q/51035554
tags question: http://stackoverflow.com/q/51092889
tag name: csv
tags question: http://stackoverflow.com/q/51067291
tags question: http://stackoverflow.com/q/51152657
tags question: http://stackoverflow.com/q/51076717
tags question: http://stackoverflow.com/q/51054554
tags question: http://stackoverflow.com/q/51119121
tags question: http://stackoverflow.com/q/51025021
tags question: http://stackoverflow.com/q/51068498
tags question: http://stackoverflow.com/q/51144702
tags question: http://stackoverflow.com/q/51146867
tags question: http://stackoverflow.com/q/51013294
tags question: http://stackoverflow.com/q/51107766
tags question: http://stackoverflow.com/q/51042841
tags question: http://stackoverflow.com/q/51118507
tags question: http://stackoverflow.com/q/51110672
tags question: http://stackoverflow.com/q/51065473
tags question: http://stackoverflow.com/q/51162334
tags question: http://stackoverflow.com/q/51152023
tags question: http://stackoverflow.com/q/51142658
tags question: http://stackoverflow.com/q/51032453
tags question: http://stackoverflow.com/q/51040660
tags question: http://stackoverflow.com/q/51011726
tags question: http://stackoverflow.com/q/51066552
tags question: http://stackoverflow.com/q/51044704
tags question: http://stackoverflow.com/q/51022870
tags question: http://stackoverflow.com/q/51137970
tags question: http://stackoverflow.com/q/51033514
tags question: http://stackoverflow.com/q/51122781
tags question: http://stackoverflow.com/q/51062176
tags question: http://stackoverflow.com/q/51130711
tags question: http://stackoverflow.com/q/51079653
tags question: http://stackoverflow.com/q/51065320
tags question: http://stackoverflow.com/q/51051566
tags question: http://stackoverflow.com/q/51026646
tags question: http://stackoverflow.com/q/51111398
tags question: http://stackoverflow.com/q/51097057
tags question: http://stackoverflow.com/q/51107648
tags question: http://stackoverflow.com/q/51140620
tags question: http://stackoverflow.com/q/51163269
tags question: http://stackoverflow.com/q/51151263
tags question: http://stackoverflow.com/q/51054636
tags question: http://stackoverflow.com/q/51090299
tags question: http://stackoverflow.com/q/51160071
tags question: http://stackoverflow.com/q/51100680
tags question: http://stackoverflow.com/q/51110985
tags question: http://stackoverflow.com/q/51039975
tags question: http://stackoverflow.com/q/51109827
tags question: http://stackoverflow.com/q/51038626
tags question: http://stackoverflow.com/q/51090877
tags question: http://stackoverflow.com/q/51040572
tags question: http://stackoverflow.com/q/51067206
tags question: http://stackoverflow.com/q/51107824
tags question: http://stackoverflow.com/q/51157360
tags question: http://stackoverflow.com/q/51067400
tags question: http://stackoverflow.com/q/51147457
tags question: http://stackoverflow.com/q/51054112
tags question: http://stackoverflow.com/q/51044154
tags question: http://stackoverflow.com/q/51056672
tags question: http://stackoverflow.com/q/51050486
tags question: http://stackoverflow.com/q/51053092

group-by
tags question: http://stackoverflow.com/q/51030205
tags question: http://stackoverflow.com/q/51143849
tags question: http://stackoverflow.com/q/51108600
tags question: http://stackoverflow.com/q/51018739
tags question: http://stackoverflow.com/q/51056938
tag name: group-by
type: Tag
tags question: http://stackoverflow.com/q/51113975
tags question: http://stackoverflow.com/q/51136388
tags question: http://stackoverflow.com/q/51033454
tags question: http://stackoverflow.com/q/51125769
tags question: http://stackoverflow.com/q/51051777
tags question: http://stackoverflow.com/q/51053678
tags question: http://stackoverflow.com/q/51016638
tags question: http://stackoverflow.com/q/51087766
tags question: http://stackoverflow.com/q/51016265
tags question: http://stackoverflow.com/q/51154330

http://stackoverflow.com/q/51069729
upvote count: 1
type: Question
score: -2
tagged with: python-3.6
tagged with: image
linked to: http://stackoverflow.com/q/7391945
duplicate of: http://stackoverflow.com/q/7391945
answer count: 1
tagged with: url
has title: How do I open an image from an url in python 3.6?
favorite count: 0
tagged with: python
has body: Hi guys I want to know how to open an image from an image url. I want it to open just like how you open something that is on your pc.
has answer: http://stackoverflow.com/a/51069821
type: UnansweredQuestion
downvote count: 3

http://stackoverflow.com/comment/89103155
type: Comment
type: QuestionComment
has text: yes, thats what i mean!. and yes script is creating the alarm of what account id and region it has been hardcoded in script. i want it to be dynamic @Michael-sqlbot
comment on: http://stackoverflow.com/q/51042824
score: 0

http://stackoverflow.com/q/51078425
has title: Module 'a' has no attribute 'b' while importing module from same directory
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51110653
has comment: http://stackoverflow.com/comment/89145593
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89146430
tagged with: python-import
tagged with: attributeerror
type: UnansweredQuestion
has body: I have following directory structure in my Python project: - dump_specs.py /impa - __init__.py - server.py - tasks.py I had a problem with circular references. dump_specs.py needs a reference to app from server.py. server.py is a Flask app which needs a references to celery tasks from tasks.py. So dump_specs.py looks like: #!/usr/bin/env python3 import impa.server def dump_to_dir(dir_path): # Do something client = impa.server.app.test_client() # Do the rest of things impa/server.py looks like: #!/usr/bin/env python3 import impa.tasks app = Flask(__name__) # Definitions of endpoints, some of them use celery tasks - # that's why I need impa.tasks reference And impa/tasks.py: #!/usr/bin/env python3 from celery import Celery import impa.server def make_celery(app): celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config['CELERY_RESULT_BACKEND']) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(impa.server.app) When I'm trying to dump specs with ./dump_specs.py I've got an error: ./dump_specs.py specs Traceback (most recent call last): File "./dump_specs.py", line 9, in &lt;module&gt; import impa.server File "/build/impa/server.py", line 23, in &lt;module&gt; import impa.tasks File "/build/impa/tasks.py", line 81, in &lt;module&gt; celery = make_celery(impa.server.app) AttributeError: module 'impa' has no attribute 'server' And I can't understand what's wrong. Could someone explain what's happening and how to get rid of this error?
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51064823
answers question: http://stackoverflow.com/q/51063947
has comment: http://stackoverflow.com/comment/89127621
has body: just compute everything once and set useful default values: def get_before2(timeslots, moment, minimum=0, maximum=1440): maxdelta = moment - datetime.timedelta(minutes=maximum) mindelta = moment - datetime.timedelta(minutes=minimum) tslots = [t for t in timeslots if t.end &gt;= maxdelta and t.end &lt;= mindelta]
score: 0
has comment: http://stackoverflow.com/comment/89125399
type: Answer

http://stackoverflow.com/a/51163523
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51163472
answers question: http://stackoverflow.com/q/51163472
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You may want to plot the transpose of the data, plt.pcolor(data.T)

http://stackoverflow.com/a/51050196
upvote count: 1
has comment: http://stackoverflow.com/comment/89091723
answers question: http://stackoverflow.com/q/51050018
has comment: http://stackoverflow.com/comment/89092320
has comment: http://stackoverflow.com/comment/89092131
has comment: http://stackoverflow.com/comment/89092175
has comment: http://stackoverflow.com/comment/89092217
accepted answer of: http://stackoverflow.com/q/51050018
has comment: http://stackoverflow.com/comment/89092006
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89091482
has comment: http://stackoverflow.com/comment/89091891
type: Answer
has comment: http://stackoverflow.com/comment/89091458
has body: The problem is that id is &lt;built-in function id&gt; @login_required def upload(request): ... # here is the wrong line, you pass `id` but you don't have this variable # and django take his `id` function current_up = Document.objects.filter(uploaddetail=id).count() # maybe you need something like this current_up = Document.objects.filter(uploaded_by=request.user.profile.id).count()
has comment: http://stackoverflow.com/comment/89091659
has comment: http://stackoverflow.com/comment/89092284
score: 1

http://stackoverflow.com/comment/89062196
type: QuestionComment
type: Comment
has text: Can you share the result of `python --version`?
comment on: http://stackoverflow.com/q/51035150
score: 0

http://stackoverflow.com/q/51062461
favorite count: 0
has comment: http://stackoverflow.com/comment/89115678
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89115191
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89114851
answer count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/89114802
type: Question
has comment: http://stackoverflow.com/comment/89114640
has comment: http://stackoverflow.com/comment/89114748
has comment: http://stackoverflow.com/comment/89114962
score: 0
tagged with: typeerror
has title: expected string or bytes-like object when parsing date
tagged with: datetime
has comment: http://stackoverflow.com/comment/89116366
has body: I am developing a simple social webapp where you can post on the wall. I keep receiving the below error despite taking many different approaches on storing datetime. However, things work fine for the same data type on other apps. I am stuck with this for 2 days now. TypeError at /wallpost/add_wallpost/ expected string or bytes-like object Request Method: POST Request URL: http://localhost:8000/wallpost/add_wallpost/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: C:\Users\Rhonald.Rose\AppData\Local\Continuum\anaconda3\envs\mydjangoenv\lib\site-packages\django\utils\dateparse.py in parse_datetime, line 107 Python Executable: C:\Users\Rhonald.Rose\AppData\Local\Continuum\anaconda3\envs\mydjangoenv\python.exe Python Version: 3.6.5 My models.py class Wallpost(models.Model): content = models.CharField(max_length=1000, blank=True, null=True) author = models.ForeignKey('members.MemberInfo', blank=True, null=True, related_name='postautor_member_set', on_delete=models.CASCADE) parent = models.ForeignKey('wallpost.Wallpost', blank=True, null=True, related_name='parent_wallpost_set', on_delete=models.CASCADE) ref_number = models.IntegerField(default=0) module_ref = models.IntegerField(default=0)#General (wall), Responses (wall), Likes, Blogs, Reshare category = models.IntegerField(default=0)#Information, Approval or Action, Alert, Warning, Danger button_type = models.IntegerField(default=0)#Social, Approval, Acceptance, Information, Alert, Warning privacy = models.IntegerField(default=0)#All, OnlySignedIn, OnlyFollowers, OnlyMutualFollowers, ExplicitIncluded, OnlyGroupMembers, Reported #date_created = models.DateField(blank=False,auto_now_add=True) date_created = models.DateTimeField(default=timezone.now()) is_archived = models.BooleanField(default=False,blank=False, null=False) allow_reshare = models.BooleanField(default=False,blank=False, null=False) date_reported = models.DateTimeField(default=False,b…

http://stackoverflow.com/q/51119459
has answer: http://stackoverflow.com/a/51119543
tagged with: python
has answer: http://stackoverflow.com/a/51119622
type: AnsweredQuestion
tagged with: performance
downvote count: 0
has body: I am trying to generate a 2D vector from a 1D vector where the element is shifted along the row by an increment each row. i would like my input to look like this: input: t = [t1, t2, t3, t4, t5] out = [t5, 0, 0, 0, 0] [t4, t5, 0, 0, 0] [t3, t4, t5, 0, 0] [t2, t3, t4, t5, 0] [t1, t2, t3, t4, t5] [ 0, t1, t2, t3, t4] [ 0, 0, t1, t2, t3] [ 0, 0, 0, t1, t2] [ 0, 0, 0, 0, t1] im unaware of a way to do this without using a for loop, and computational efficieny is important for the task im using this for. Is there a way to do this without a for loop? this is my code using a for loop: import numpy as np t = np.linspace(-3, 3, 7) z = np.zeros((2*len(t) - 1, len(t))) diag = np.arange(len(t)) for index, val in enumerate(np.flip(t, 0)): z[diag + index, diag] = val print(z)
type: Question
tagged with: numpy
score: 5
has title: mapping a 2d delay vector from a 1d vector in numpy
answer count: 3
has answer: http://stackoverflow.com/a/51122753
favorite count: 0
accepted answer: http://stackoverflow.com/a/51119622
possible better answer: http://stackoverflow.com/a/51119543
upvote count: 5

http://stackoverflow.com/comment/89021612
score: 0
comment on: http://stackoverflow.com/q/51014427
type: Comment
type: QuestionComment
has text: Yea its actually like: while True: nheight = tc.getblockcount()['count'] print(nheight) print(height) if height != nheight: print("val changed") height = nheight time.sleep (0.4) @cricket_007

http://stackoverflow.com/a/51154290
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51154179
has body: Use string formatting. There's many choices in python. set_drive = "ON" result = "Drive=%s" % set_drive # traditional way result = f"Drive={set_drive}" # python 3.6+ way
type: Answer
has comment: http://stackoverflow.com/comment/89521041
has comment: http://stackoverflow.com/comment/89291796
score: 0
has comment: http://stackoverflow.com/comment/89291685

http://stackoverflow.com/q/51085037
has answer: http://stackoverflow.com/a/51154465
has comment: http://stackoverflow.com/comment/89158753
has comment: http://stackoverflow.com/comment/89159186
answer count: 1
has body: I'm trying to get the database migrations for my Flask app running. The manual step does work: docker-compose exec python /usr/local/bin/python manage.py db init docker-compose exec python /usr/local/bin/python manage.py db migrate docker-compose exec python /usr/local/bin/python manage.py db upgrade ... but not the automation with the Docker and Docker-Compose file. How cloud the issue be solved? Thanks Docker-File # Use an official Python runtime as a parent image FROM python:2.7 # Set the working directory to /app WORKDIR /app # Copy the current directory contents into the container at /app ADD . /app # Environment RUN apt-get update RUN apt-get install -y ruby # Install any needed packages specified in requirements.txt RUN pip install --trusted-host pypi.python.org -r requirements.txt # Make port 80 available to the world outside this container EXPOSE 80 # Define environment variable ENV NAME APP ENV TERM xterm # Run db migrations #COPY docker-entrypoint.sh /docker-entrypoint.sh #RUN chmod a+rx /docker-entrypoint.sh RUN chmod +x manage.py RUN python manage.py db init RUN python manage.py db migrate RUN python manage.py db upgrade COPY init.sql /docker-entrypoint-initdb.d/10-init.sql # Run the app when the container launches CMD ["python", "app.py"] Docker-Compose.yml version: '2' services: db: image: postgres environment: - POSTGRES_USER=abc - POSTGRES_PASSWORD=abc ports: - "55432:5432" python: build: ./app ports: - "80:5000" depends_on: - db links: - db tty: true manage.py from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from sdst import app, db manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run() Docker-Entrypoint (currently not used) #!/bin/sh python manage.py db init python manage.py db migrate python manage.py db upgrade exec "$@" app.py [...] app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\ %(pw)s@%(host)s:%(port)s/%(db)s' % POS…
downvote count: 0
has title: Python Flask Docker Migrations
tagged with: flask
tagged with: docker
tagged with: python
tagged with: migrate
accepted answer: http://stackoverflow.com/a/51154465
favorite count: 0
linked to: http://stackoverflow.com/q/48342406
upvote count: 3
has comment: http://stackoverflow.com/comment/89287055
has comment: http://stackoverflow.com/comment/89163524
has comment: http://stackoverflow.com/comment/89289512
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89289708
tagged with: database
has comment: http://stackoverflow.com/comment/89291180

http://stackoverflow.com/comment/89046701
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51027151
has text: `string` is a list. You need to apply the regex to `s`, the current string inside the list.
type: QuestionComment

http://stackoverflow.com/a/51035299
downvote count: 0
has body: Your query returns about 10% of the table's rows. It selects multiple columns from across the whole row. Assuming the posted sample data is representative there is no clumping of data and selected rows will come from all through the table. So indexing won't help you. You need a Full Table Scan. Run an Explain Plan on your query to make sure you are using one. If for some reason you are running some form of indexed read fix that (for instance by refreshing stale statistics). Beyond that there aren't many ways to tune a Full Table Scan: if you have an Enterprise Edition and multiple CPUs available then parallel query may help. But, let's row back a minute. "My query returns about 10 million rows but takes about 30 minutes to run." Where is the bottleneck? Almost certainly not the database. 10 million rows of ~20 columns is a hefty amount of data but a Full Table Scan on one table should run in a couple of minutes, if not much less (depending on the beefiness of your server). It is quite likely to be the network (unless you are running this query locally, that is pandas client is on the database server). You are passing many, many packets across the network. You may be running into a limit on available bandwidth, so talk to your network admin team (or install wireshark!). If network latency is the issue check whether setting pd.read_sql() chunksize helps. The other thing to consider is client memory: dataframes are in-memory structures, so you may be loading more data than the client can handle. Anything you can do to reduce the total amount of selected data will help. Revisit the projection of the query and remove any columns you don't need for the subsequent processing. ' EXPLAIN PLAN FOR command isn't returning anything' EXPLAIN PLAN populates a table. Find out more. You need to query the table to get the plan out. The DBMS_XPLAN built-in package is your best friend here. Check it out. Some IDEs (like PL/SQL Developer) handle this transaparently.
has comment: http://stackoverflow.com/comment/89136998
upvote count: 2
answers question: http://stackoverflow.com/q/51034507
type: Answer
accepted answer of: http://stackoverflow.com/q/51034507
score: 2
has comment: http://stackoverflow.com/comment/89144743
type: AcceptedAnswer

http://stackoverflow.com/comment/89271832
has text: Okay. Modifying this script to avoid creating a new page is simple, so I’ll add an answer for that. If you want to implement rewriting the form page, you’ll need to show the (relevant part of) the code for that page.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51142617

http://stackoverflow.com/q/51025252
has comment: http://stackoverflow.com/comment/89043081
duplicate of: http://stackoverflow.com/q/19384532
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89042944
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89043042
has comment: http://stackoverflow.com/comment/89043209
has comment: http://stackoverflow.com/comment/89042919
tagged with: python
has comment: http://stackoverflow.com/comment/89043055
answer count: 0
has body: I have a simple question but somehow I am not getting the results. My data looks like: Pagename UserId A X B X C Y A X My question is this: I want my data as: UserId PageName Count X A 2 X B 1 Y C 1 I know how to get this in SQL, but how to do it in Pandas? I keep getting the error: ValueError: No axis named user_Id for object type &lt;class 'pandas.core.frame.DataFrame'&gt; for df.groupby('name', 'user_Id').size().reset_index(name='Count') and data name timestamp user_Id buD00 Clicked Back to List Button 2018-05-20T11:00:00.035Z cWH00 Clicked Create New Ticket Button 2018-05-20T11:00:00.051Z huB00 Clicked Ticket Reference Number 2018-05-20T11:00:00.067Z hOH00 Clicked Ticket Reference Number 2018-05-20T11:00:00.067Z
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/50328246
has title: Group By Pandas Datframe and Get Counts
linked to: http://stackoverflow.com/q/19384532
tagged with: dataframe

http://stackoverflow.com/q/51027375
answer count: 1
has body: I want to make a preview of my article. How to select first several lines of TextField? I am using the flask and wtforms. class Blog(Model): content = TextField() template: {{blog.content}} But how to specify the first several lines to display? For example, only display 4 lines. blog.content(rows = 4)
tagged with: flask
accepted answer: http://stackoverflow.com/a/51121287
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51121287
upvote count: 1
has title: Specify the lines of textfield to display
tagged with: jinja2

http://stackoverflow.com/comment/89043559
type: Comment
has text: why were `'.co'` and `'.in'` appended to the same string?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51025536

http://stackoverflow.com/comment/89271147
type: QuestionComment
comment on: http://stackoverflow.com/q/51091856
score: 1
has text: An exception is thrown in stderr (in the console) with a stacktrace, but nothing shows up in `except Exception as e:`
type: Comment

http://stackoverflow.com/comment/89200588
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51106395
has text: @DeanStamler the user can provide their engine for you to bind on your base. I edited the answer to show this:

http://stackoverflow.com/a/59497848
answers question: http://stackoverflow.com/q/51110783
score: 2
downvote count: 2
has body: Anyway, if you need the path of the tempfile directory you can use tempfile.gettempdir()
upvote count: 4
type: Answer

http://stackoverflow.com/a/51073679
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51065443
has body: You have multiple dicts that you are using. The order that keys are returned in dicts cannot be accurately predicted. I don't think you have any guarantee that list(mst.nodes.keys()) will be in the same order as X and Y. So I suspect that the label ST7 is being applied to a different node.

http://stackoverflow.com/comment/89300885
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51158742
has text: Possible duplicate of [Does Python import statement also import dependencies automatically?](https://stackoverflow.com/questions/29367255/does-python-import-statement-also-import-dependencies-automatically)
score: 0

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

http://stackoverflow.com/q/51134353
type: AnsweredQuestion
has title: data type of message in volttron pubsub
type: Question
tagged with: volttron
score: 0
tagged with: types
answer count: 1
has comment: http://stackoverflow.com/comment/89262881
tagged with: python
has answer: http://stackoverflow.com/a/51166657
accepted answer: http://stackoverflow.com/a/51166657
has body: What is the data type for "message" in pubsub used by volttron? I have checked the documentation but there is nothing mentioned about this. When checking the source I found this function comment source : param headers: header info for the message, type headers: None or dict, param message: actual message, type message: None or any Are the above info correct? Does that "any" type refer to this: typing.Any?

http://stackoverflow.com/comment/89481351
has text: I too prefer the readability of boolean comparisons `if … else` but, of course, 0 is also `False`. As are more generally, `[]` and `{}`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51090344
type: Comment

databricks
tags question: http://stackoverflow.com/q/51044013
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/51120814
tags question: http://stackoverflow.com/q/51082687

http://stackoverflow.com/a/51115213
upvote count: 1
answers question: http://stackoverflow.com/q/51115103
type: Answer
has body: In Python, every variable, array element, and attribute is a reference, and the only thing =, +=, -= etc. are able to do is to change what its left-hand side refers to. Note that any other operation will act directly on the value that is being referenced, such as . (look up attribute of the object that is referenced by the left-hand side) or [] (look up element of the list/dict that is referenced by the left-hand side). If you are trying to understand Python in terms of C, keep this in mind: In Python, there is no such thing as a primitive data type or a variable of primitive type Assignment always affects what the variable refers to, just like assigning to a pointer in C Any other operations use and/or affect the referenced value, so you can think of it as automatic dereferencing. In particular, a.b corresponds to a-&gt;b or (*a).b.
downvote count: 0
score: 1

http://stackoverflow.com/q/51145234
upvote count: 6
tagged with: flask-migrate
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58665565
has comment: http://stackoverflow.com/comment/89274842
has comment: http://stackoverflow.com/comment/89274968
has answer: http://stackoverflow.com/a/58665565
has comment: http://stackoverflow.com/comment/89274743
has comment: http://stackoverflow.com/comment/89274809
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51164394
has comment: http://stackoverflow.com/comment/89274858
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/89275049
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/89274935
score: 6
has comment: http://stackoverflow.com/comment/89274893
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89274982
has comment: http://stackoverflow.com/comment/89274864
has body: I have the following project structure: project/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate db = SQLAlchemy() migrate = Migrate() def create_app(): app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) db.init_app(app) migrate.init_app(app, db) return app run.py from project import create_app app = create_app() if __name__ == "__main__": app.run() manage.py from flask_script import Manager from flask_migrate import MigrateCommand from project.models import * from project import create_app manager = Manager(create_app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run() Yet when I run the following commands, Flask-Migrate is not detecting any tables to be added. python manage.py db init Which outputs: Creating directory $HOME/Project/migrations ... done Creating directory $HOME/Project/migrations/versions ... done Generating $HOME/Project/migrations/script.py.mako ... done Generating $HOME/Project/migrations/env.py ... done Generating $HOME/Project/migrations/README ... done Generating $HOME/Project/migrations/alembic.ini ... done Please edit configuration/connection/logging settings in '$HOME/Project/migrations/alembic.ini' before proceeding. and python manage.py db migrate Which only outputs: INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. Why is Flask-Migrate with Alembic not detecting the Models and therefore creating the tables? Here's what I've tried: Deleting the database, starting from nothing Creating a custom db class inside the manage.py file, doesn't detect that Googling every answer to this problem, found lots of similar questions but none of their solutions worked for me. EDIT: Here is an example of the models.py file from flask import current_app from project import db from flask_login import UserMixin class User(db.Model, UserMixin): id = db.Column(db.Integer, …
has comment: http://stackoverflow.com/comment/89274850
favorite count: 0
has comment: http://stackoverflow.com/comment/89282386
has comment: http://stackoverflow.com/comment/89274937
has comment: http://stackoverflow.com/comment/89274912
has answer: http://stackoverflow.com/a/51164394
has title: Flask-Migrate not detecting tables
tagged with: python

http://stackoverflow.com/comment/89294423
type: Comment
score: 0
type: QuestionComment
has text: @VatsalAggarwal The shape of single X is (50,) and input is (7499042,)
comment on: http://stackoverflow.com/q/51155356

http://stackoverflow.com/comment/89189916
type: QuestionComment
has text: This sems like a code-review and thus should also go to codereview.stackexchange.com
comment on: http://stackoverflow.com/q/51100038
score: 0
type: Comment

http://stackoverflow.com/comment/89270491
has text: The error got resolved after reinstalling absl-py.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51142979

http://stackoverflow.com/comment/89303592
type: Comment
comment on: http://stackoverflow.com/a/51159159
score: 0
type: AnswerComment
has text: I am creating CSV data using the python list. How can I identify issue in data?

http://stackoverflow.com/comment/89127086
comment on: http://stackoverflow.com/q/51055864
type: Comment
type: QuestionComment
has text: i have updated my original post. please review.
score: 0

http://stackoverflow.com/comment/89132572
comment on: http://stackoverflow.com/q/51071212
score: 0
type: Comment
type: QuestionComment
has text: What alphabet can the output use (i.e. numerals, lower and upper case letters)? You need it to have at least 38 characters in order to represent all numbers from 1 to 38^5.

http://stackoverflow.com/comment/89127973
type: QuestionComment
has text: Possible duplicate of [Popen error: \[Errno 2\] No such file or directory](https://stackoverflow.com/questions/9935151/popen-error-errno-2-no-such-file-or-directory)
score: 0
comment on: http://stackoverflow.com/q/51068554
type: Comment

http://stackoverflow.com/comment/89234335
type: Comment
has text: Another thing, I need to know, why there's two context at the first code.
comment on: http://stackoverflow.com/a/51081784
type: AnswerComment
score: 0

http://stackoverflow.com/q/51043406
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/89077819
score: 0
type: UnansweredQuestion
has title: python findall() returns empty list
upvote count: 1
tagged with: python
downvote count: 1
type: Question
tagged with: openapi
linked to: http://stackoverflow.com/q/8053568
has answer: http://stackoverflow.com/a/51043476
has body: I want to use Python to get open API data. So, I parsed the URL to XML and tried to get the information I wanted through findall(). part of the data, &lt;safemap:CTPRVN_CD&gt;11&lt;/safemap:CTPRVN_CD&gt; &lt;safemap:SGG_CD&gt;11500&lt;/safemap:SGG_CD&gt; i want this, root.findall('safemap:ctprvn_cd') but returned empty list.
tagged with: beautifulsoup
answer count: 1
has comment: http://stackoverflow.com/comment/89077775
linked to: http://stackoverflow.com/q/7414747

http://stackoverflow.com/q/51061059
has comment: http://stackoverflow.com/comment/89188228
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51168438
downvote count: 2
tagged with: mql5
type: Question
has comment: http://stackoverflow.com/comment/89188911
accepted answer: http://stackoverflow.com/a/51199962
has comment: http://stackoverflow.com/comment/89196075
upvote count: 6
score: 4
has body: I have obtained the OHLC values from the iqoption and trying to find out a way to use it with MT5. Here is how I got the values: import time from iqoptionapi.stable_api import IQ_Option I_want_money=IQ_Option("email","password") goal="EURUSD" print("get candles") print(I_want_money.get_candles(goal,60,111,time.time())) The above code library is here: iqoptionapi The line: I_want_money.get_candles(goal,60,111,time.time()) output json as : Output of the command Now I am getting json in the output so it work like an API, I guess so. Meanwhile, I try to create a Custom Symbol in MT5 as iqoption. Now I just wanted to add the data of the OHLC from the API to it, so that it will continue fetching data from the Iqoption and display the chart on the chart window for the custom symbol iqoption. But I am not able to load it in the custom symbol. Kindly, help me. Edited This is the code for live streaming data from the iqoption: from iqoptionapi.stable_api import IQ_Option import logging import time logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(message)s') I_want_money=IQ_Option("email","password") I_want_money.start_candles_stream("EURUSD") thread=I_want_money.collect_realtime_candles_thread_start("EURUSD",100) I_want_money.start_candles_stream("USDTRY") thread2=I_want_money.collect_realtime_candles_thread_start("USDTRY",100) time.sleep(3) #Do some thing ans=I_want_money.thread_collect_realtime.items() for k, v in ans: print (k, v) I_want_money.collect_realtime_candles_thread_stop(thread) I_want_money.stop_candles_stream("EURUSD") I_want_money.collect_realtime_candles_thread_stop(thread2) I_want_money.stop_candles_stream("USDTRY")
answer count: 2
has answer: http://stackoverflow.com/a/51199962
has answer: http://stackoverflow.com/a/51168438
has comment: http://stackoverflow.com/comment/89189099
favorite count: 0
has comment: http://stackoverflow.com/comment/89188479
tagged with: python
has title: Integrating the OHLC value from Python API to MT5 using MQL5
tagged with: metatrader5
has comment: http://stackoverflow.com/comment/89243164

http://stackoverflow.com/comment/89190429
type: Comment
has text: Good luck with that. Even if there were existing solutions, software recommendations are off-topic on stackoverflow. We are here to help you with specific problems that you have with code that you write.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51101594

http://stackoverflow.com/comment/89093409
comment on: http://stackoverflow.com/q/51051136
has text: Regex sounds like a good choice.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51036065
has body: i found workable solution #from Tkinter import * from Tkinter import Tk, Text, Frame, Scrollbar, END import time # while True: # ROOT.update() # # time.sleep(10) # txt.insert(END, "hello here\n") # txt.pack() import threading class ThreadingExample(object): """ Threading example class The run() method will be started and it will run in the background until the application exits. """ def __init__(self, interval=1): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): """ Method that runs forever """ time.sleep(1) global ROOT while True: ROOT.update() time.sleep(2) txt.insert(END, "hello here\n") txt.pack() print "aa" global ROOT ROOT = Tk() # create a Frame for the Text and Scrollbar txt_frm = Frame(ROOT, width=600, height=600) txt_frm.pack(fill="both", expand=True) # ensure a consistent GUI size txt_frm.grid_propagate(False) # implement stretchability txt_frm.grid_rowconfigure(0, weight=1) txt_frm.grid_columnconfigure(0, weight=1) # create a Text widget txt = Text(txt_frm, borderwidth=3, relief="sunken") txt.config(font=("consolas", 12), undo=True, wrap='word') txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2) # create a Scrollbar and associate it with txt scrollb = Scrollbar(txt_frm, command=txt.yview) scrollb.grid(row=0, column=1, sticky='nsew') txt['yscrollcommand'] = scrollb.set txt.insert(END, "hello\n") txt.pack() example = ThreadingExample()
downvote count: 0
answers question: http://stackoverflow.com/q/51035799
has comment: http://stackoverflow.com/comment/89066318
type: Answer
has comment: http://stackoverflow.com/comment/89066150
score: 1
upvote count: 1

http://stackoverflow.com/q/51048142
type: Question
tagged with: python
tagged with: artificial-intelligence
tagged with: machine-learning
upvote count: 1
type: UnansweredQuestion
has title: Update rule for multivariate linear regression with vector outputs
answer count: 0
has body: In multivariate linear regression the weight (w) update rule is w[i] += learning_rate * sum([x[j][i] * (y[j] - h(x[j])) for j in range(len(x))]) Where x is the datamatrix (the vector of feature-vectors), y the vector of real numbered outputs and def h(x): return sum([w[i]*x[i] for i in range(len(weights))]) What would be the equivalent weight update rule if y was a vector of real numbered vector outputs?
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51148938
has answer: http://stackoverflow.com/a/51149050
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: The purpose of this script is to send an email to a receivers list, and the code works just for the first receiver but the never works for the rest of the list. here is the code: class email: def __init__(self, sender, subject, message): self.sender = sender self.subject = subject self.message = message def receivers(self): receivers = ('adam', 'tom', 'mel') for receiver in receivers: return receiver def send(self): print('we send email from'.capitalize(), self.sender, 'to', email.receivers().title(), 'and the subject is', self.subject, 'finally the massage is', self.message) email = email('sayed', 'morning message', 'wake up man') email.send() here is the result: We send email from sayed to Adam and the subject is morning message finally the massage is wake up man
type: Question
linked to: http://stackoverflow.com/q/231767
has title: python set returns the first item only
accepted answer: http://stackoverflow.com/a/51149044
score: 0
possible better answer: http://stackoverflow.com/a/51149003
has answer: http://stackoverflow.com/a/51149044
has answer: http://stackoverflow.com/a/51149027
has comment: http://stackoverflow.com/comment/89281788
has answer: http://stackoverflow.com/a/51149003

http://stackoverflow.com/a/51081553
upvote count: 4
has body: This is a regression problem (i.e. predicting a continuous value), not a categorisation problem (labelling from a set of discrete values). The tensorflow docs have a number of examples demonstrating regression.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51081166
answers question: http://stackoverflow.com/q/51081166
score: 4

http://stackoverflow.com/comment/89316729
score: 0
has text: What I mean is that I could have a total of 13 counting values ​​from my data, and I would like to express it on a list of 13 frequencies.
comment on: http://stackoverflow.com/a/51166038
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89095457
comment on: http://stackoverflow.com/a/51052168
score: 0
type: Comment
type: AnswerComment
has text: Cheers I'll try this when I get chance

http://stackoverflow.com/a/51067398
score: 1
has comment: http://stackoverflow.com/comment/89125070
upvote count: 1
has body: The --where option for mysqldump can be used to pass an expression to the SELECT for each table, but it passes the same expression to all tables. If you need to use different WHERE clauses for different subsets of tables, you'll need to do more than one mysqldump command, and execute each command against a different set of tables Re your comment: No, the references to columns in an SQL query must be fixed at the time the query is parsed, and that means any column references must refer to columns that exist in the table. There's no way to make an expression in SQL that uses columns if they do exist and ignores the column reference if the column doesn't exist. To do what you're describing, you would have to query the INFORMATION_SCHEMA to see what columns exist in the table, and then format the SQL query for the dump conditionally, based on the columns you find do exist in the table. But in mysqldump, you don't have the opportunity to do that. It would have to be implemented in the code for mysqldump. Feel free to get the source code for mysqldump and add your own logic to it. Seems like a lot of work though.
has comment: http://stackoverflow.com/comment/89125375
type: Answer
answers question: http://stackoverflow.com/q/51067226
downvote count: 0

http://stackoverflow.com/a/51026610
score: 1
has comment: http://stackoverflow.com/comment/89045680
has comment: http://stackoverflow.com/comment/89045909
accepted answer of: http://stackoverflow.com/q/51025438
has comment: http://stackoverflow.com/comment/89045697
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51025438
type: Answer
has body: Using collections.defaultdict, you can create a nested dictionary while iterating your dataframe. Then realign into a list of dictionaries via a list comprehension. from collections import defaultdict tree = lambda: defaultdict(tree) d = tree() for row in factor_table.itertuples(index=False): d[(row.Name, row.Variable)].update({row.Level: row.Value}) res = [{k[0]: {k[1]: dict(v)}} for k, v in d.items()] print(res) [{'model1': {'channel_model': {'Dir': 1.110, 'EA': 1.002, 'IA': 1.180}}}, {'model2': {'channel_model': {'Dir': 2.200, 'EA': 2.560, 'IA': 2.500}}}, {'model1': {'driver_age': {'21': 1.100, '22': 1.200, '23': 1.300, '24': 1.400}}}, {'model2': {'driver_age': {'21': 2.100, '22': 2.200, '23': 2.300, '24': 2.400}}}]
upvote count: 1

http://stackoverflow.com/q/51101252
tagged with: matplotlib
has answer: http://stackoverflow.com/a/53850328
has body: I'm trying to draw a timeline import datetime as da import matplotlib.dates as dt # Data df = pd.DataFrame({'A': [da.datetime(2017,1,5,9,8), da.datetime(2017,1,5,9,9), da.datetime(2017,1,7,9,19), da.datetime(2017,1,7,9,19), da.datetime(2017,1,7,9,19), da.datetime(2017,2,7,9,19), da.datetime(2017,2,7,9,19)], 'B': [da.datetime(2017,1,5,9,9), da.datetime(2017,1,5,9,12), da.datetime(2017,1,7,9,26), da.datetime(2017,1,7,9,20), da.datetime(2017,1,7,9,21), da.datetime(2017,2,7,9,23), da.datetime(2017,2,7,9,25)], 'C' :[1, 2, 3, 4, 5, 6, 7 ]}) # Visualisation ax = plt.subplot() ax = plt.hlines(df.C, dt.date2num(df.A), dt.date2num(df.B)) but getting the error: AttributeError: 'numpy.datetime64' object has no attribute 'toordinal' I think it's caused by the data type: df.A.dtype dtype('&lt;M8[ns]') I tried some recommended solutions (converter &amp; pandacnv) but I still couldn't get it to work.
downvote count: 1
tagged with: timeline
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/53924555
has answer: http://stackoverflow.com/a/53924555
tagged with: pandas
favorite count: 0
has title: AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'
accepted answer: http://stackoverflow.com/a/53850328
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/51140023
type: Question
tagged with: vector
upvote count: 3
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51144218
has body: I am using Python 3 to try to find what linear combinations of a set of vectors will sum to another vector. I am using numpy arrays as vectors. For example, I would have a target vector and matrix "choices" containing all the possible choices of vectors: targetvector0 = numpy.array([0, 1, 2]) choices = numpy.array([[0, 1, 0], [0, 0, 1], [0, 0, 2], [1, 1, 0]]) I need something that would return all possible combinations and their integer multiples (need them to be integer multiples) that sum to the target and ignore those that don't: option1 = [[1], [2], [0], [0]] option2 = [[1], [0], [1], [0]] I found some info on numpy.linalg.solve(x, y), but it doesn't quite do what I'm looking for or I don't know how to use it effectively.
has title: Determine which combinations of vectors will sum to another vector
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51144218
downvote count: 0
tagged with: linear-algebra

http://stackoverflow.com/comment/89102345
comment on: http://stackoverflow.com/q/51055864
has text: What do you mean by "incorporate"?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51072162
tagged with: python
tagged with: graphml
upvote count: 3
tagged with: networkx
type: Question
has body: I'm using networkx to create graphml files. I have parallel links so I'm using the MultiDiGraph function. After generating the file I open it in yED but I don't have all the connections that I created between the nodes. The only connections (edges) I have are the ones created for the parallel links. I've realized it is because the graphml file only have two edge ids ('0' and '1') for all the edges. I modified the file and set a unique id for each edge. For example: 100GE1/0/0 100GE1/0/0 100GE1/0/1 100GE1/0/1 100GE1/1/0 100GE1/0/0 If i do this then everything works fine in yED. Is there any way to modify the edge ID's in networkx? I thought I could modify the 'edge id' if I set it like an attribute like this: g.add_edge(host,neighbor,source = intsource, destination = intdest, id=idcount) But I realized it didnt change the edge id only added another attribute for that edge: 100GE1/0/0 100GE1/0/0 1 <-- This is the idcount value
has answer: http://stackoverflow.com/a/51072555
score: 3
has title: Networkx - How to change edge id's?
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89264657
comment on: http://stackoverflow.com/q/51139009
score: 0
has text: probably, I'm new to this. But thats not the issue I'm running into, since it correctly reads in sometimes. I think its a timing issue where the downloading hasn't fully finished so I try to convert the result to a dataframe when its still the uri.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51048189
answer count: 4
has title: Random walk plotting in python
possible better answer: http://stackoverflow.com/a/51048335
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51048335
has comment: http://stackoverflow.com/comment/89088951
has comment: http://stackoverflow.com/comment/89090175
has answer: http://stackoverflow.com/a/51050233
type: Question
accepted answer: http://stackoverflow.com/a/51050233
has comment: http://stackoverflow.com/comment/89090844
has comment: http://stackoverflow.com/comment/89087772
has comment: http://stackoverflow.com/comment/89087733
has comment: http://stackoverflow.com/comment/89092230
has comment: http://stackoverflow.com/comment/89088527
has answer: http://stackoverflow.com/a/51048472
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/89087578
has comment: http://stackoverflow.com/comment/89088857
downvote count: 1
has comment: http://stackoverflow.com/comment/89087670
favorite count: 0
has body: I have been working through the book "A student's guide to Python for Physical Modeling" by Jesse M. Kinder &amp; Philip Nelson and there is an exercise where I'm instructed to build a Brownian motion simulator/ random walk simulator and plot it. I don't know why my code is not working and I was hoping I could get some help from you: import numpy as np import matplotlib.pyplot as plt from numpy.random import random as rng def Brownian_motion(steps): """ this is a random walk function define the number of steps to be taken as a integer value """ #these are the random numbers steps_x = rng(steps) steps_y = rng(steps) #Here I change the random numbers to 1 or -1 pace_x = (steps_x &lt; 0.5) for i in pace_x: if i == False: pace_x[i] = -1 else: pace_x[i] = 1 return pace_x pace_y = (steps_y &lt; 0.5) for i in pace_y: if i == False: pace_y[i] = -1 else: pace_x[i] = 1 return pace_y plt.plot(np.cumsum(pace_x), np.cumsum(pace_y)) plt.show() Brownian_motion(500) It does not throw and error but I can't get it to plot EDIT: This is similar to what I'm expecting to see: http://people.sc.fsu.edu/~jburkardt/m_src/random_walk_2d_simulation/walks_1_steps_1000_plot.png
has answer: http://stackoverflow.com/a/51048468
has comment: http://stackoverflow.com/comment/89087650
tagged with: python

http://stackoverflow.com/q/51086704
score: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51089256
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89162285
has comment: http://stackoverflow.com/comment/89162121
has title: Append numpy matrix to binary file without numpy header
favorite count: 0
tagged with: binary
has comment: http://stackoverflow.com/comment/89162551
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51089256
has body: I continously receive new data as numpy matrices which I need to append to an existing file. Structure and data type of that file are fixed, so I need python to do the conversion for me. For a single matrix, this works: myArr = np.reshape(np.arange(15), (3,5)) myArr.tofile('bin_file.dat') But suppose I'd want to keep appending the existing file with more and more arrays, then numpy.tofile will overwrite any content it finds in the file, instead of appending. I found that I could also keep doing this: bfile = open('bin_file.dat', 'ab') np.save(bfile, myArr) bfile.close() which successfully appends to the binary file. But numpy.save on the other hand does not store the raw binary data, but also saves a header (I assume) which makes the file unreadable by foreign software (I need raw binary with float32). Reading in the existing content of the file with numpy.fromfile, appending my data and saving it again is not an option, since the file becomes very large and all the I/O would take forever to process. Is there anything like an append mode for numpy.tofile? Are there other possibilities I am currently missing?
has comment: http://stackoverflow.com/comment/89162532
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89162394

http://stackoverflow.com/comment/89282732
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51125100
has text: I think it has some thing to do with the version. Not sure though
type: Comment

http://stackoverflow.com/a/51071656
upvote count: 4
has body: self is the 3rd argument as I am assuming these methods are within a class given new_question calling self. def chunkIt(self, seq, num): avg = len(seq) / float(num) out = [] last = 0.0 while last &lt; len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out Regardless if you define it or not, unless you specify a method as static, it will always pass self to the method. Therefore by calling print(self.chunkIt(['1','2'],2)) it actually is being sent as print(self.chunkIt(self, ['1','2'],2))
score: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51071604
type: Answer
accepted answer of: http://stackoverflow.com/q/51071604

http://stackoverflow.com/a/51026508
type: Answer
has body: Python 3 (including 3.6) is already Unicode supported. Here is the doc - https://docs.python.org/3/howto/unicode.html So you don't need to force Unicode support like Python 2.7. Try to run your code normally. If you get any error reading a Unicode text file you need to use the encoding='utf-8' parameter while reading the file.
upvote count: 1
score: -2
has comment: http://stackoverflow.com/comment/138270898
answers question: http://stackoverflow.com/q/51026315
downvote count: 3

http://stackoverflow.com/q/51064965
has body: I have a dataset like this: category UK US Germany sales 100000 48000 36000 budget 50000 20000 14000 n_employees 300 123 134 diversified 1 0 1 sustainability_score 22.8 38.9 34.5 e_commerce 37000 7000 11000 budget 25000 10000 10000 n_employees 18 22 7 traffic 150 mil 38 mil 12500 subsidy 33000 26000 23000 budget 14000 6000 6000 own_marketing 0 0 1 In the dataset, sales variable corresponds to sales from the head quarter. e_commerce is sales of the e-commerce and budget right after e_commerce is actually the budget of e_commerce section of the company. Same also applies to subsisdy, subsidy variable corresponds to sales of the subsidy and the budget variable after subsidy is the budget of the subsidy. I want to convert dataset to something like this (if we take UK as an example): UK_main_sales UK_main_budget ... UK_e_commerce_sales UK_e_commerce_budget ... 100000 500000 37000 250000 and so on. I tried to do classify variables from different departments by tracking the budget variable as it always comes right after the departant but I was not successful. Full list of variables for UK should be like this: UK_main_sales UK_main_budget UK_main_n_employees UK_main_diversified UK_main_sustainability_score UK_e_commerce (we could also add sales but I think it is simpler without sales) UK_e_commerce_budget UK_e_commerce_n_employees UK_e_commerce_traffic UK_subsidy UK_subsidy_budget UK_subsidy_own_marketing Any ideas?
tagged with: pandas
score: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/51065103
tagged with: transpose
has title: Transposing unstructured rows in pandas
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51065103
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89219478
score: 0
type: Comment
type: QuestionComment
has text: thank you for the reply Druta, but I would like to stay in this convention if possible
comment on: http://stackoverflow.com/q/51116552

http://stackoverflow.com/q/51164887
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89313055
has answer: http://stackoverflow.com/a/53788104
tagged with: python
linked to: http://stackoverflow.com/q/739993
linked to: http://stackoverflow.com/q/23870365
type: UnansweredQuestion
has body: I'm currently learning how to use Django to develop a web service. As I go through an online course on Udemy, I ran into a problem using ImageField in models.py. My problem is that, when I excute the runserver command, Django shows the following error although I am pretty sure the library Pillow is installed. In models.py, I have the following code: from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) portfolio = models.URLField(blank=True) picture = models.ImageField(upload_to="profile_pics") def __str__(self): return user.self.username When I runserver, I get the following error: python manage.py runserver Performing system checks... Unhandled exception in thread started by &lt;function check_errors&lt;locals&gt;.wrapper at 0x10407b6a8&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/base.py", line 410, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: first_app.UserProfileInfo.picture: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". System check identified 1 issue (0 silenced). So, by following the message I checked the installed modules by using the method introduced here: How can I get a list of locally installed Python modules?. The following code is run in a file in the same directory as manage.py. I'm us…
tagged with: django
has title: Django Error: Cannot use ImageField because Pillow is not installed
has comment: http://stackoverflow.com/comment/89324601
has comment: http://stackoverflow.com/comment/89346009
has comment: http://stackoverflow.com/comment/89346083
has answer: http://stackoverflow.com/a/61063514
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/51183279
tagged with: django-models
has comment: http://stackoverflow.com/comment/89314242
type: Question
has comment: http://stackoverflow.com/comment/89346542

http://stackoverflow.com/q/51093821
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89176638
has title: __xor__ in functools.reduce() causing error
type: Question
possible better answer: http://stackoverflow.com/a/51094309
has answer: http://stackoverflow.com/a/51094309
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51095267
accepted answer: http://stackoverflow.com/a/51095267
downvote count: 1
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/89175712
favorite count: 0
tagged with: xor
tagged with: python-3.x
has body: I'm currently working in python 3 with the Discord API and I want to use a module that was written in python 2. I'm editing some of the code for it to work with python 3. Something I can't figure out is this: odd_xor = reduce(__xor__, bh) &gt;&gt; 16 This works in python 2 but doesn't in python 3. The simple fix that I thought would work was: odd_xor = functools.reduce(__xor__, bh) &gt;&gt; 16 but this gives me the error: reduce() of empty sequence with no initial value bh is initialized here: # bh stands for binary hand, map to that representation card_to_binary = HandEvaluator.Six.card_to_binary_lookup bh = map(card_to_binary, hand) I don't really understand what the code segment is trying to do which is why it is so difficult for me to find a solution to this problem. Any thoughts? Thanks in advance! P.S. if there is an easier way to use python 2 modules with python 3 projects, please enlighten me.
tagged with: python

http://stackoverflow.com/a/51097031
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89185030
answers question: http://stackoverflow.com/q/51023512
has comment: http://stackoverflow.com/comment/89184889
accepted answer of: http://stackoverflow.com/q/51023512
type: Answer
has body: You need to add some postprocessing to clear you results: To remove javascript and css text from your results use this: results = response.xpath( '//*[not(self::script or self::style)]/text()' ).extract() Then apply strip and if to remove empty lines: text = " ".join([x.strip() for x in results if x.strip()])
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/89187491

http://stackoverflow.com/comment/89243600
comment on: http://stackoverflow.com/a/51125016
score: 0
type: AnswerComment
has text: Not per se. You could simply use a condition for when to compare with one attribute and when to compare with another. Of course that wouldn't work if one comparison is by no way connected to the other one though. Then you have to either use the attributes outside the class, or create 2 functions that don't overwrite the basic operators. In this case you know you need the suit when the card is either a Queen or a King, so you can check for that first, and then compare by suits.
type: Comment

http://stackoverflow.com/a/51088549
type: Answer
answers question: http://stackoverflow.com/q/51088481
upvote count: 2
score: 2
downvote count: 0
has body: You're sooooooo close! for j in set(words): print words.count(j), Take note that, since you're reporting each word's count only once, you've lost a strong association between each count and the word it represents. Both set and Counter will lose that ordering.

http://stackoverflow.com/comment/89200082
score: 0
comment on: http://stackoverflow.com/q/51106359
type: Comment
type: QuestionComment
has text: @HanAltae-Tran How can I procedure that?

http://stackoverflow.com/q/51094378
has answer: http://stackoverflow.com/a/51094587
score: 0
answer count: 2
tagged with: lxml
accepted answer: http://stackoverflow.com/a/51094729
has body: Let's say you have a varied HTML block like this: Blue Black Yellow Pink Orange What would your approach be, using python, to extract the colours from this HTML block?
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89177074
tagged with: python
tagged with: regex
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51094729
has comment: http://stackoverflow.com/comment/89176798
has title: Extract Text from Varied HTML using Python
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51094587

http://stackoverflow.com/q/51074502
has body: We are trying to send a message to AWS FIFO queue. We already have a working version of the code which sends the message to SQS standard queue. Python code (Our requirement is not to use SDK):Examples of the Complete Version 4 Signing Process (Python) For the standard queue, we used following params method = 'GET' service = 'sqs' host = 'sqs.us-west-2.amazonaws.com' region = 'us-west-2' endpoint = 'https://sqs.us-west-2.amazonaws.com/xxxxxx/TestQueue' request_parameters = 'Action=SendMessage&MessageBody=mytest&Version=2012-11-05' canonical_uri = '/xxxxxx/TestQueue' For the FIFO Queue, we used the same code and additionally modified as follows method = 'GET' service = 'sqs' host = 'sqs.us-west-2.amazonaws.com' region = 'us-west-2' endpoint = 'https://sqs.us-west-2.amazonaws.com/xxxxxxx/Test.fifo' request_parameters = 'Action=SendMessage&MessageBody=mytest&MessageGroupId=test&MessageDeduplicationId=ttte&Version=2012-11-05' canonical_uri = '/xxxxxxx/Test.fifo' But it is failed. Are we missing anything, can anyone help us? Response code: 403 <?xml version="1.0"?><ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><Error> Sender <Code>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
type: AnsweredQuestion
has title: Amazon SQS FIFO Queue sending message failed
has comment: http://stackoverflow.com/comment/89306433
tagged with: amazon-web-services
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51081706
score: 0
tagged with: signing
upvote count: 1
downvote count: 1
answer count: 1
tagged with: fifo
has answer: http://stackoverflow.com/a/51081706
tagged with: amazon-sqs

http://stackoverflow.com/q/51020192
type: Question
has title: Circle Plot with Color Bar
has answer: http://stackoverflow.com/a/51021017
linked to: http://stackoverflow.com/q/47563373
tagged with: scatter
has answer: http://stackoverflow.com/a/51023886
favorite count: 0
upvote count: 3
answer count: 3
tagged with: geometry
downvote count: 0
tagged with: python
has body: I'm trying to do a Circle Plot with a Color Bar, almost like this: However, the minimum value of the colour bar is currently 1; I would like to be able to set it to 0. import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm from sklearn import preprocessing df = pd.DataFrame({'A':[1,2,1,2,3,4,2,1,4], 'B':[3,1,5,1,2,4,5,2,3], 'C':[4,2,4,1,3,3,4,2,1]}) # set the Colour x = df.values min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) df_S = pd.DataFrame(x_scaled) c1 = df['C'] c2 = df_S[2] colors = [cm.jet(color) for color in c2] # Graph plt.figure() ax = plt.gca() for a, b, color in zip(df['A'], df['B'], colors): circle = plt.Circle((a, b), 1, # Size color=color, lw=5, fill=False) ax.add_artist(circle) plt.xlim([0,5]) plt.ylim([0,5]) plt.xlabel('A') plt.ylabel('B') ax.set_aspect(1.0) sc = plt.scatter(df['A'], df['B'], s=0, c=c1, cmap='jet', facecolors='none') plt.grid() cbar = plt.colorbar(sc) cbar.set_label('C', rotation=270, labelpad=10) plt.show() Credit to this original question: Plotting circles with no fill, colour &amp; size depending on variables using scatter
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51020741
tagged with: colorbar
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51023886
possible better answer: http://stackoverflow.com/a/51021017

http://stackoverflow.com/comment/89336480
comment on: http://stackoverflow.com/a/51164673
type: Comment
has text: You can also use sqlplus to connect to the database using the connect string you provided to cx_Oracle.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51117276
has comment: http://stackoverflow.com/comment/140166237
answers question: http://stackoverflow.com/q/51117209
type: Answer
score: 18
has comment: http://stackoverflow.com/comment/89228811
has body: await loop.run_in_executor(executor, work) blocks the loop until work completes, as a result you only have one function running at a time. To run jobs concurrently, you could use asyncio.as_completed: async def producer(): tasks = [loop.run_in_executor(executor, work) for _ in range(num_jobs)] for f in asyncio.as_completed(tasks, loop=loop): results = await f await queue.put(results)
upvote count: 18
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51117209

http://stackoverflow.com/a/51120297
accepted answer of: http://stackoverflow.com/q/51110318
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51110318
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: extra_compile_args=["-l:libvl53l1.a"] This setting adds -l:... to the compilation command, but the compiler ignores that option, because it's a linking option, and no linking is done by the compiler. You want: extra_link_args=["-lvl53l1"], which would add -lvl53l1 to the link command (the linker wouldn't ignore that option while performing the linking).

http://stackoverflow.com/comment/89156874
comment on: http://stackoverflow.com/a/51084148
has text: There's only one `i`. It resides in the `makeActions` call and is inherited by each of the `lambda`s. This is distinct from putting it in a default argument, which takes its value at that time and stores it among the defaults. The loop doesn't create a scope, let alone one per iteration; it just updates a variable and runs a chunk of code.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89127334
has text: @MattW. which version of pandas are you using?
type: Comment
comment on: http://stackoverflow.com/a/51029945
score: 0
type: AnswerComment

http://stackoverflow.com/q/51063947
score: 0
answer count: 3
has title: Condensed and efficient way of selecting time slots within a time range
accepted answer: http://stackoverflow.com/a/51064108
has body: I have a bunch of time slots with a start and an end of type datetime. Given a particular datetime, I need to get those that are before, and after: def get_before(timeslots, moment): return [t for t in timeslots if t.end &lt;= moment] def get_after(timeslots, moment): return [t for t in timeslots if t.start &gt;= moment] But there are two optional arguments, minimum and maximum, indicating that the time slots must be within the maximum amount of minutes and outside the minimum. We have the following slots: 2018-06-27 09:00:00 - 2018-06-27 10:00:00 2018-06-27 10:00:00 - 2018-06-27 11:00:00 2018-06-27 11:00:00 - 2018-06-27 12:00:00 2018-06-27 12:00:00 - 2018-06-27 13:00:00 2018-06-27 13:00:00 - 2018-06-27 14:00:00 2018-06-27 14:00:00 - 2018-06-27 15:00:00 2018-06-27 15:00:00 - 2018-06-27 16:00:00 2018-06-27 16:00:00 - 2018-06-27 17:00:00 2018-06-27 17:00:00 - 2018-06-27 18:00:00 2018-06-27 18:00:00 - 2018-06-27 19:00:00 2018-06-27 19:00:00 - 2018-06-27 20:00:00 2018-06-27 20:00:00 - 2018-06-27 21:00:00 2018-06-27 21:00:00 - 2018-06-27 22:00:00 If we want the time slots after 2018-06-27 15:00:00, with a minimum of 1 hour and a maximum of 4 hours, we get: 2018-06-27 16:00:00 - 2018-06-27 17:00:00 2018-06-27 17:00:00 - 2018-06-27 18:00:00 2018-06-27 18:00:00 - 2018-06-27 19:00:00 2018-06-27 19:00:00 - 2018-06-27 20:00:00 This is my implementation: def get_before(timeslots, moment, minimum=None, maximum=None): tslots = [t for t in timeslots if t.end &lt;= moment] if maximum is not None: maxdelta = datetime.timedelta(minutes=maximum) tslots = [t for t in tslots if t.end + maxdelta &gt;= moment] if minimum is not None: mindelta = datetime.timedelta(minutes=minimum) tslots = [t for t in tslots if t.end &lt;= moment - mindelta] return tslots def get_after(timeslots, moment, minimum=None, maximum=None): tslots = [t for t in timeslots if t.start &gt;= moment] if maximum is not None: maxdelta = datetime.timedelta(minutes=maximum) tslots = [t for t in tslots if t.start - maxdelta…
has answer: http://stackoverflow.com/a/51064074
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51064823
possible better answer: http://stackoverflow.com/a/51064074
has answer: http://stackoverflow.com/a/51064108
type: Question
type: AnsweredQuestion
tagged with: performance
tagged with: python-2.7

http://stackoverflow.com/a/77440061
score: 0
answers question: http://stackoverflow.com/q/51121170
type: Answer
has body: Yet another alternative: df['A'] = df['A'].apply(lambda x: x.replace('&amp;amp;', '&amp;')) This has the advantage of also supporting type casting. For example if you assume that df['B'] contains strings of the form '[0]', '[5]', '[10]', etc., and you want to keep only the numerical values, you could do: df['B'] = df['B'].apply(lambda x: float(x.replace('[', '').replace(']', '')))

recursion
type: Tag
tags question: http://stackoverflow.com/q/51030986
tags question: http://stackoverflow.com/q/51092023
tag name: recursion
tags question: http://stackoverflow.com/q/51040224
tags question: http://stackoverflow.com/q/51111786
tags question: http://stackoverflow.com/q/51012750
tags question: http://stackoverflow.com/q/51124656

http://stackoverflow.com/q/51077912
has answer: http://stackoverflow.com/a/51078304
downvote count: 2
answer count: 1
has title: find numbers and chars on an image
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
upvote count: 0
tagged with: machine-learning
has body: I'm tring to bulid a program that should recognized the serial number on containers. there will me a camera and the input of the camera will be an image of truck with a containers on it and the output will be the truck number and the container number. I'm not sure if I should use open cv or machine learning for that and what is better. Not like the truck license plate, the container number is not allways write in the same way and some times there are more numbers,but it's allways 4 letters and then 7 numbers so I need some function (opencv or machine learning/knn) that recognize any letter and number on the container. I added some images to show how it's look. Thank's Amit
type: Question
tagged with: opencv
score: -2

http://stackoverflow.com/q/51114464
tagged with: discord.py
has body: I just started programming a discord bot with discord.py and everything is perfect. Except one thing: I can't let the bot play music. Here is my code: @client.command(pass_context=True) async def yt(ctx, url): author = ctx.message.author voice_channel = author.voice_channel vc = await client.join_voice_channel(voice_channel) player = await vc.create_ytdl_player(url) player.start() My error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OpusNotLoaded: Why is it happening?
answer count: 1
has answer: http://stackoverflow.com/a/51114499
has title: Command raised an exception: OpusNotLoaded:
score: 0
tagged with: python
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/89233574
has text: Return a result of a method call?
score: 0
comment on: http://stackoverflow.com/q/51124229
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51014815
downvote count: 0
score: 1
has body: You use my timing program that I wrote. #!python3 import timeit from os import system system('cls') # % % % % % % % % % % % % % % % % % # times the code 100 times runs = 100 totalTime = 0.0; average = 0.0 testTimes = [] for i in range(runs): startTimer = timeit.default_timer() # % % % % % % % % % % % % % % % % # &gt;&gt;&gt;&gt;&gt; code to be tested goes here &lt;&lt;&lt;&lt;&lt; def fib(n): if n &lt;= 1: return 1 else: answer = fib(n - 1) + fib(n - 2) return answer r = fib(26) print('fib result is:', r) # % % % % % % % % % % % % % % % % endTimer = timeit.default_timer() timeInterval = endTimer - startTimer testTimes.append(timeInterval) totalTime += timeInterval print('\n', '{} {:.4f} {}'.format("This run's time is", timeInterval, 'seconds' + '\n')) # print the results print('{} {:.4f} {}'.format(' Total time:', totalTime, 'seconds')) print('{} {:.4f} {}'.format('Shortest time:', min(testTimes), 'seconds')) print('{} {:.4f} {}'.format(' Longest time:', max(testTimes), 'seconds')) print('{} {:.4f} {}'.format(' Average time:', (totalTime / runs), 'seconds'))
answers question: http://stackoverflow.com/q/51014765
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89240641
type: QuestionComment
comment on: http://stackoverflow.com/q/51127792
has text: I don't understand this: `but of course it's much useless effort`.
score: 0
type: Comment

http://stackoverflow.com/q/51086142
has comment: http://stackoverflow.com/comment/89160724
accepted answer: http://stackoverflow.com/a/51086390
has comment: http://stackoverflow.com/comment/89160794
has comment: http://stackoverflow.com/comment/89160859
has answer: http://stackoverflow.com/a/51086574
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/1060279
has answer: http://stackoverflow.com/a/51086390
has comment: http://stackoverflow.com/comment/89161516
tagged with: python
has title: Generate a sorted list of birthday dates and append each date to a newline in a file
has answer: http://stackoverflow.com/a/51086305
type: AnsweredQuestion
tagged with: list
tagged with: word-list
tagged with: generate
type: Question
has body: So, I have been trying to generate a wordlist with birthday dates. I am trying to append each value to a newline in a file birdthday_wordlist.txt. The file and the format should be like this: 01/01/1998 02/01/1998 03/01/1998 dd/mm/yyyy 12/12/2000 I was capable of generating only the dd, mm or yyyy, with scripts like this: with open('XXXXXX_wordlist.txt', 'w') as birdthday_wordlist: for i in range(1980, 2000): birdthday_wordlist.write('{}\n'.format(i)) I know there is a way, for now I couldn't figure it out.
possible better answer: http://stackoverflow.com/a/51086305

http://stackoverflow.com/q/51059856
tagged with: python
type: AnsweredQuestion
score: 1
has body: I've been trying to get my register page to work for a couple days now. I think I'm close , but now I'm receiving the following error message in my terminal when I try to click register from the login page: File "/home/ubuntu/workspace/pset7/finance/application.py", line 175, in errorhandler return apology(e.name, e.code) AttributeError: 'ValueError' object has no attribute 'name' Here is my code from the lines the error is pointing to (I didn't write them, they were provided with the distribution code): def errorhandler(e): """Handle error""" return apology(e.name, e.code) Any help would be greatly appreciated. I will include my register function code just in case that helps: @app.route("/register", methods=["GET", "POST"]) def register(): """Register user""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Ensure password == confirmation elif request.form.get("password") != request.form.get("confirmation"): return apology("password and confirmation do not match", 403) # Ensure username is not already taken rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) if len(rows) == 1: return apology("username already taken. please choose another", 403) # Add new user to the database session["user_id"] = db.execute("INSERT INTO users(username, hash) VALUES(:username, :hash)", username=request.form.get("username"), \ hash=generate_password_hash(request.form.get("password"))) # Redirect user to home page return redirect("/") Thanks!
tagged with: web-applications
type: Question
tagged with: attributeerror
tagged with: flask
has answer: http://stackoverflow.com/a/51075109
accepted answer: http://stackoverflow.com/a/51075109
has title: Creating register form with Flask - AttributeError: 'ValueError' object has no attribute 'name'
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/66539802
answers question: http://stackoverflow.com/q/51163397
score: 0
type: Answer
has body: Explained in comments def contains(text, pattern): for i in range(len(text) - len(pattern)): found = True for j in range(len(pattern)): if text[i + j] != pattern[j]: # comparing each letter found = False break if found: return True return False s = 'hatanicda' word_list = ['a', 'what', 'an', 'nice', 'day'] match = [] for i in word_list: if contains(s, i) and len(i) &gt; 3: # 3 since word has to be more than is/are/the to be meaningful match.append(i) print(bool(match)) False [Program finished]

http://stackoverflow.com/comment/89222612
has text: Im gonna try this method, I tried the above one that I marked as correct which did skip the method even thought it was a caught of it with printing. However I do hope this method will work!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51115409

http://stackoverflow.com/q/51066552
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89123023
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/51066608
has body: How do I concatenate 2 CSV files using panda such that the resulting CSV file doesn't have row indexes? See example below: file1.csv date type price amount 2017-09-02 00:00:01 b 0.279111 94000 2017-09-02 00:00:01 b 0.279 43800 2017-09-02 00:00:01 b 0.2789 6000 2017-09-02 00:00:01 b 0.278812 2000 2017-09-02 00:00:01 b 0.278 7250 file2.csv date type price amount 2018-03-02 00:00:01 q 0.279111 1400 2018-05-01 00:00:01 q 0.279 3800 2017-09-02 00:00:01 q 0.2789 640 desired_file.csv date type price amount 2017-09-02 00:00:01 b 0.279111 94000 2017-09-02 00:00:01 b 0.279 43800 2017-09-02 00:00:01 b 0.2789 6000 2017-09-02 00:00:01 b 0.278812 2000 2017-09-02 00:00:01 b 0.278 7250 2018-03-02 00:00:01 q 0.279111 1400 2018-05-01 00:00:01 q 0.279 3800 2017-09-02 00:00:01 q 0.2789 640 NOT THIS: date type price amount 1 2017-09-02 00:00:01 b 0.279111 94000 2 2017-09-02 00:00:01 b 0.279 43800 3 2017-09-02 00:00:01 b 0.2789 6000 4 2017-09-02 00:00:01 b 0.278812 2000 5 2017-09-02 00:00:01 b 0.278 7250 6 2018-03-02 00:00:01 q 0.279111 1400 7 2018-05-01 00:00:01 q 0.279 3800 8 2017-09-02 00:00:01 q 0.2789 640 My code: import pandas as pd a = pd.read_csv("file1.csv") b = pd.read_csv("file2.csv") combined = pd.concat([a, b]) combined.to_csv("desired_file.csv") Thanks :)
duplicate of: http://stackoverflow.com/q/20845213
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51066608
has title: Concatenate 2 csv files using panda and not include row index
type: Question
linked to: http://stackoverflow.com/q/20845213

http://stackoverflow.com/q/51017450
tagged with: c++
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/68262753
type: AnsweredQuestion
score: 3
has title: C++ application crashes when embedded Python interpreter tries to import external module a second time
type: Question
answer count: 2
has body: If I import an external module twice in different pybind11::scoped_interpreter sessions, the application crashes in eval.h in function eval at following line: PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); with Exception thrown at 0x00007FFD710C4E0C (multiarray.cp36-win_amd64.pyd) in pybind-test.exe: 0xC0000005: Access violation writing location 0x000000000000000A. Reproducible example code namespace py = pybind11; void test() { try { py::scoped_interpreter guard{}; py::object mainScope = py::module::import("__main__").attr("__dict__"); py::exec( "import numpy\n", mainScope); } catch (py::error_already_set const &amp;pythonErr) { std::cout &lt;&lt; pythonErr.what(); } } int main() { test(); // Runs fine test(); // Crashes at py::exec } I feel like this has to do with the comment in pybind11's embed.h: The interpreter can be restarted by calling initialize_interpreter again. Modules created using pybind11 can be safely re-initialized. However, Python itself cannot completely unload binary extension modules and there are several caveats with regard to interpreter restarting. All the details can be found in the CPython documentation. In short, not all interpreter memory may be freed, either due to reference cycles or user-created global data. So there is no way to call the Python interpreter twice? I have a python file containing helper numpy functions that I need to call at different points of algorithm execution from C++. Does this mean I can't do that?
downvote count: 0
tagged with: pybind11
possible better answer: http://stackoverflow.com/a/68262753
has answer: http://stackoverflow.com/a/51069948
favorite count: 0
accepted answer: http://stackoverflow.com/a/51069948

http://stackoverflow.com/q/51037673
tagged with: python
score: 0
has body: I have this class class Order(db.Model): __tablename__ = "orders" id=db.Column(db.String, primary_key=True) order_id = db.Column(db.String, nullable=True) product_id=db.Column(db.String, nullable=True) quantity=db.Column(db.Integer, nullable=True) def save_to_db(self): db.session.add_all(self) db.session.commit() And i have this class class checkout(Resource): # @jwt_required def post(self): # current_user = get_jwt_identity() # user_wallet=Wallet.find_by_customer_id(current_user) order_id=uuid.uuid1() data = parser_checkout.parse_args() print (data['Products'][0]['Product_id']) mainlist=list() for i in range(0,len(data['Products'])): new_order_prod=Order( id=uuid.uuid1(), order_id=order_id, product_id=data['Products'][i]['Product_id'], quantity=data['Products'][i]['quantity'] ) mainlist.append(new_order_prod) try: mainlist.save_to_db() return { 'status':'succes', 'message':'sucess order placed' },200 except: return { 'status':'error', 'message':'order placing failed' },401 I m not getting any error but i found that mainlist.save_to_db() is not working i mean that its not going inside the function of that class. Can anyone help me ? I think its not entering that function becoz class object is tuple with concerned fields but i m making list and calling that so is that why its not working ? Any solution to this?
answer count: 1
has title: sqlalchemy- how to save multiple tuples at a time in db and then commit
tagged with: sqlalchemy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51037791
tagged with: flask
tagged with: flask-sqlalchemy
accepted answer: http://stackoverflow.com/a/51037791
type: Question
has comment: http://stackoverflow.com/comment/89067178

http://stackoverflow.com/comment/89131812
type: AnswerComment
has text: I am not sure if the code I am using uses fcntl - the code imports library "ee" which uses it but its unknown where. Seems like I have to download Linux or a VM
type: Comment
comment on: http://stackoverflow.com/a/51070816
score: 0

http://stackoverflow.com/q/51052921
score: 0
has body: Is there a way to use either a warning or exception in python that would allow me to raise control and then pick up from where it left off? def foo(): #make a request r = request.get('someRestAPI') # get the data from request data = r.json() # determine the number of results the request will return num_results = data['num_results'] if num_results &gt; 1000: # raise a warning to be handled main # continue if the main doesn't catch results = [] endpoint = data['next_page'] while endpoint: # request the next page r = request.get(endpoint ) data = r.json() results.append(data['result']) endpoint = data['next_page'] def main(): try: foo() catch warning: cont = input("Warning Over 1000 results, Continue?") if cont == 'y': # return to function call and continue The goal of the example above is to show a possible use case. I make an initial request to a REST API and determine the number of results that request will give. If I have too many results, then I want to temporary pass control to another area of the program to determine if we should continue. I know that this program could be structured differently to accomplish this, but I'm curious if there's a way to specifically give control via a raise or warning to the function that called it and then allow it to continue from where it left off.
has comment: http://stackoverflow.com/comment/89097123
answer count: 1
has comment: http://stackoverflow.com/comment/89096928
has title: Is it possible to catch a warning and choose to continue from where the warning left off?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89097092
has answer: http://stackoverflow.com/a/51053035
tagged with: request
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/89097004
has comment: http://stackoverflow.com/comment/89097080
has comment: http://stackoverflow.com/comment/89096949
has comment: http://stackoverflow.com/comment/89096983

http://stackoverflow.com/a/51162114
answers question: http://stackoverflow.com/q/51161771
score: 0
type: Answer
has body: Sounds like you want a copy of the file for Python3. I would copy the file and rename it with the Python version as part of the name and then rename the original file to also include the version. Something like: cp foo.py foo36.py mv foo.py foo27.py

http://stackoverflow.com/comment/89429426
comment on: http://stackoverflow.com/a/51130894
type: Comment
has text: Do you get any error? can you specify it in your question. Also, do you have your code hosted somewhere, so that i can have a look.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89228875
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51112309
has text: Same issue here
score: 0

mlflow
type: Tag
tags question: http://stackoverflow.com/q/51079061
tags question: http://stackoverflow.com/q/51064366
tag name: mlflow

http://stackoverflow.com/comment/89057543
has text: thanks, that is a really good idea. will give that a try.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51032434
type: Comment

http://stackoverflow.com/comment/89268088
comment on: http://stackoverflow.com/q/51140389
score: 3
has text: You can utilize return codes and capture outputs. `$out = python script.py; if ($LASTEXITCODE -ne 0) { $out }`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51152939
accepted answer: http://stackoverflow.com/a/51153244
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89289436
answer count: 2
has answer: http://stackoverflow.com/a/51153916
has comment: http://stackoverflow.com/comment/89289393
upvote count: 0
has comment: http://stackoverflow.com/comment/89289610
score: -1
possible better answer: http://stackoverflow.com/a/51153916
has comment: http://stackoverflow.com/comment/89291308
has title: How to use regex in recursrion
favorite count: 0
has comment: http://stackoverflow.com/comment/89289523
has comment: http://stackoverflow.com/comment/89289342
has comment: http://stackoverflow.com/comment/89289409
has body: input = '''name Jhon age 30 name John bp 130 90 name Rick age 80 name Rick bp 110 70''' I have a string like the above one. I need to make it as list of dicts [ { "name": "John", "age" : 30, "bp_sys" : 130, "bp_dia" : 90 }, { "name": "Rick", "age" : 80, "bp_sys" : 110, "bp_dia" : 70 } ] I have tried in the below - which splits the input by line and applying regex on each line for line in input.split("\n"): print re.findall(r'name (.*?) age (.*?)', line) It prints something like [('John', '')] for the first line Any other easy way?
tagged with: python
has answer: http://stackoverflow.com/a/51153244
type: AnsweredQuestion

http://stackoverflow.com/a/51170112
score: 1
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51166817
has body: floats between 0 and 1 are good values for rgb in matplotlib. here's a small example import numpy as np import matplotlib.pyplot as plt v = [(0.16091847477176702, 0.4337815920028113, 0.40529993322542174), (0.15019057645364922, 0.40486281920262385, 0.44494660434372696), (0.14017787135673926, 0.44453863125578225, 0.4152834973874785), (0.13083267993295664, 0.41490272250539673, 0.45426459756164661), (0.17697859494133705, 0.36303988219222216, 0.45998152286644078), (0.16591743275750348, 0.40284988955520828, 0.43123267768728824), (0.16591743275750348, 0.40284988955520828, 0.43123267768728824), (0.16591743275750348, 0.40284988955520828, 0.43123267768728824), (0.15406618756053894, 0.37407489744412198, 0.47185891499533911), (0.20019069588580043, 0.32419824445157241, 0.47561105966262723), (0.20019069588580043, 0.32419824445157241, 0.47561105966262723), (0.17349860310102702, 0.34763847852469609, 0.47886291837427691), (0.16193202956095856, 0.39112924662304965, 0.44693872381599176)] y = np.arange(len(v)) for i in range(len(v)): plt.plot(y[i], 0, marker='o', ls='', c=v[i], markersize=20) plt.show() and the result: it's subtle but it works

http://stackoverflow.com/a/51047188
has body: You could try using matplotlib's annotate. This is usually less of a headache than Arrows and FancyArrows: import numpy as np import matplotlib.pyplot as plt time = np.linspace(0,23,24) temp = np.array([10]*24) + np.random.random(24)*2 wind = np.linspace(0, 270, 24) fig, ax = plt.subplots() ax.plot(time, temp, 'o-') arrow_len = 1.5 for i, theta in enumerate(np.radians(wind)): dx = arrow_len * np.cos(theta) dy = arrow_len * np.sin(theta) * ax.get_data_ratio() x, y = time[i], temp[i] ax.annotate("", xy=(x+dx, y+dy), xycoords='data', xytext=(x, y), textcoords='data', arrowprops=dict(arrowstyle="-|&gt;") ) plt.show()
upvote count: 2
answers question: http://stackoverflow.com/q/51046289
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/89165912
score: 0
has text: that was repeated element so it gives 2 but i dont need it's duplicate
type: Comment
comment on: http://stackoverflow.com/a/51088512
type: AnswerComment

http://stackoverflow.com/a/51139924
answers question: http://stackoverflow.com/q/51139635
type: Answer
has body: Update: Pygame 1.9.4 has been released and you can download and install it with pip again. In Windows I recommend installing it with: py -3.7 -m pip install pygame There are no official precompiled pygame packages for Python 3.7 available yet, so pip install pygame doesn't work, but you can get a pygame wheel from: https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame Download pygame‑1.9.3‑cp37‑cp37m‑win_amd64.whl if you have a 64-bit Python version or pygame‑1.9.3‑cp37‑cp37m‑win32.whl if you have a 32-bit version. Then open the command-line, navigate to the directory that contains the wheel file and install it with pip: py -3.7 -m pip install pygame‑1.9.3‑cp37‑cp37m‑win_amd64.whl This solution works only in Windows, so users with other operating systems have to wait and use Python 3.6.
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/89264072
has comment: http://stackoverflow.com/comment/89264244
has comment: http://stackoverflow.com/comment/89263984
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51139635

http://stackoverflow.com/q/51157987
type: Question
tagged with: pyqt
has body: I have a problem here that is quite obvious but I can't find a solution. I am new to PyQt and PyQtGraph. Here are the relevant codes: verticalGroupBox = QtGui.QGroupBox("Waveforms") layoutV = QtGui.QVBoxLayout() waveformPlot1 = pg.PlotWidget() waveformPlot2 = pg.PlotWidget() waveformPlot3 = pg.PlotWidget() waveformPlot1.plotItem.plot(self.time, self.data_plot[0]) layoutV.addWidget(waveformPlot1) waveformPlot2.setYRange(-30000, 30000, padding=0.01) waveformPlot2.setXRange(0, self.timeDuration, padding=0.01) layoutV.addWidget(waveformPlot2) waveformPlot3.setYRange(-30000, 30000, padding=0.01) layoutV.addWidget(waveformPlot3) Here are the images to my problem: https://i.sstatic.net/aE6MR.jpg | https://i.sstatic.net/L88PE.jpg As you can see in the first image, I only placed a plot with data on waveformPlot1 and made waveformPlot2 and waveformPlot3 an empty plot widgets for testing. So now, my problem is, when I decided to attach another data that is expected to be plotted in waveformPlot2 widget (in order from plot1-plot3), hence, it is plotted in waveformPlot3 widget. (see second image) waveformPlot2.plotItem.plot(self.time, self.data_plot[0]) I notice that it is because of the layout that it follows where it ends, so my 2nd plot data was plotted on the 3rd widget
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/100371909
score: 0
has comment: http://stackoverflow.com/comment/89307535
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: PyQT Layout Box
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/89351410
has comment: http://stackoverflow.com/comment/89369938

http://stackoverflow.com/q/51027355
possible better answer: http://stackoverflow.com/a/51042038
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51042038
has body: I am still learning Python/Matplotlib, so please bear with me. I have a complicated function foo(x,y) with two input arguments x and y. I wish to plot the zero-contour of this function foo. I created a meshgrid in the required range using numpy.meshgrid, and tried plotting the zero-contour using the command plt.contour(X,Y,Z,levels=[0]). This returned me the warning: No contour levels were found within the data range. I think this is because the function is evaluated on a discrete set of values, where it is precisely never zero, hence no contour. I therefore wish to specify a tolerance for this zero. Can anyone please suggest me a way? Thank you very much!
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51027890
accepted answer: http://stackoverflow.com/a/51027890
has title: How to plot zero-contour with tolerance specified in Python?
tagged with: plot
type: Question
tagged with: matplotlib

http://stackoverflow.com/q/51105220
tagged with: python-3.x
type: Question
tagged with: python
has body: I have a PANDAS DataFrame with the following data: DF0 = pd.DataFrame(np.random.uniform(0,100,(4,2)), columns=['x', 'y']) pupil_rads = pd.Series(np.random.randint(1,10,(4))) DF0["pupil_radius"] = pupil_rads DF0 [out:] x y pupil_radius 0 20.516882 15.098594 8 1 92.111798 97.200075 2 2 98.648040 94.133676 3 3 8.524813 88.978467 7 I want to create a 3D graph, showing where the gaze was pointed at (x/y coordinates) in every measurement (index of the DF). Also, I'm trying to make it a line-graph so that the radius of the line would correspond with the pupil-radius. So far what I've come up with is the following: gph = plt.figure(figsize=(15,8)).gca(projection='3d') gph.scatter(DF0.index, DF0['x'], DF0['y']) gph.set_xlabel('Time Stamp') gph.set_ylabel('X_Gaze') gph.set_zlabel('Y_Gaze') This creates a 3D scatter-plot, which is almost what I need: How do I make the data-points be in varying size? Is there a way to create a continuous-line-graph and not a scatter-plot?
tagged with: plot
score: 0
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/51106895
has title: Plotting a PANDAS DF to a 3D line-graph with changing width
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14827650
accepted answer: http://stackoverflow.com/a/51106895

http://stackoverflow.com/a/51026635
has comment: http://stackoverflow.com/comment/89046382
has body: I think a better and faster way to make this work is using apply function. They are internally optimized for fast performance. You can rewrite your code like: matches_fil3['P1Est'] = matches_fil3['Player One'].apply(get_estimate) matches_fil3['P1Err'] = matches_fil3['Player One'].apply(get_error) . . matches_fil3['P2Rat'] = matches_fil3.apply(lambda row: get_match_rating(row['P2 Frames Won'], row['Total'], row['P2Exp']), axis=1)
has comment: http://stackoverflow.com/comment/89046931
score: 0
has comment: http://stackoverflow.com/comment/89055060
has comment: http://stackoverflow.com/comment/89055129
type: Answer
answers question: http://stackoverflow.com/q/51025417

http://stackoverflow.com/q/51138290
type: AnsweredQuestion
tagged with: algorithm
type: Question
answer count: 2
score: -2
has body: I have lot of PDF, DOC[X], TIFF and others files (scans from a shared folder). Each file converted into pack of text files: one text file per page. Each pack of files could contain multiple documents (for example thee contracts). Document kind could be not only contract. During the processing the pack of the files I don't know what kind of the documents current pack contains and it's possible that one pack contains multiple document kinds (contracts, invoices, etc). I'm looking for some possible approaches to solve this programmatically. I'm tried to search something like that but without any success. UPD: I tried to create binary classificator with scikit-learn and now looking for another solution.
possible better answer: http://stackoverflow.com/a/51138506
favorite count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/51594122
tagged with: nlp
upvote count: 0
has title: Split pack of text files into multiple subsets according to the content of the files
has answer: http://stackoverflow.com/a/51594122
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/51138506

http://stackoverflow.com/q/51014621
has title: Format plot axis of multiindex dataframe one for title one for date without time
tagged with: pandas
has comment: http://stackoverflow.com/comment/89088329
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89034721
tagged with: python
has comment: http://stackoverflow.com/comment/89034769
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89111267
upvote count: 1
type: Question
has body: I am trying to line plot this multiindexed pandas dataframe with the Ticker as the title (ie IVOG) and the date as the x-axis. I only want the month and year for the x-axis. I want to at least get rid of it showing the time. df'Adj_Close', 'MA(3)', 'EWMA(3)' Adj_Close MA(3) EWMA(3) Ticker Date IVOG 2017-04-30 47.0319 47.031900 47.031900 2017-05-31 47.4419 47.236900 47.305233 2017-06-30 46.3553 46.943033 46.762414 2017-07-31 49.6553 47.817500 48.305287 2017-08-31 52.5453 49.518633 50.493681 2017-09-30 55.5353 52.578633 53.054503 2017-10-31 57.3753 55.151967 55.231913 2017-11-30 55.5353 56.148633 55.384201 2017-12-31 59.6556 57.522067 57.524080 2018-01-31 61.7056 58.965500 59.616884 2018-02-28 58.8156 60.058933 59.216046 2018-03-31 58.9600 59.827067 59.087992 2018-04-30 58.9000 58.891867 58.993984 2018-05-31 59.0000 58.953333 58.996992 I have tried many things The following code is the closest I have gotten. I converted the dataframe to a dict so I could present it here. I lost the index headers and the date format in doing so. But it should be something reproducible now. import datetime as dt import pandas as pd import time import matplotlib.pyplot as plt import matplotlib.dates as mdates data = {("IVOG",1493510400000):{"Adj_Close":119.2136,"MA(3)":119.2136,"EWMA(3)":119.2136}, ("IVOG",1496188800000):{"Adj_Close":120.8236,"MA(3)":120.0186,"EWMA(3)":120.0454}, ("IVOG",1498780800000):{"Adj_Close":120.2736,"MA(3)":120.1036,"EWMA(3)":120.1266}, ("IVOG",1501459200000):{"Adj_Close":121.7836,"MA(3)":120.5236,"EWMA(3)":120.5832}, ("IVOG",1504137600000):{"Adj_Close":120.3536,"MA(3)":120.4896,"EWMA(3)":120.5309}, ("IVOG",1506729600000):{"Adj_Close":124.3336,"MA(3)":121.1303,"EWMA(3)":121.2749}} df=pd.DataFrame.from_dict(data, orient = 'index') print(df) ax = plt.gca() # get current axis df.plot(kind='line',y='Adj_Close', ax=ax) df.plot(kind='line',y='MA(3)',ax=ax) df.plot(kind='line',y='EWMA(3)', color='green', ax=ax) ax.format_xdata = mdates.DateFormatter('%b-%Y') # Tryin…
tagged with: matplotlib

http://stackoverflow.com/q/51086074
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51086154
has body: how can i solve this problem please tell me what to do this i am not able to figure out this problem. so please do tell me how to solve this in simple words. import time from PIL import ImageGrab import pyautogui class Cordinates(): replayBtn = (340,420) dinosaur = (422,170) #215= xcordinate to check for tree def restartGame(): pyautogui.click(Cordinates.replayBtn) def pressSapce(): pyautogui.keyDown('space') time.sleep(0.05) print("Jump") pyautogui.KeyUp('space') restartGame() time.sleep(1) pressSapce() after runing i get C:\Users\Pranav\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Pranav/PycharmProjects/untitled1/bot.py Traceback (most recent call last): Jump File "C:/Users/Pranav/PycharmProjects/untitled1/bot.py", line 22, in &lt;module&gt; pressSapce() File "C:/Users/Pranav/PycharmProjects/untitled1/bot.py", line 18, in pressSapce pyautogui.KeyUp('space') TypeError: object() takes no parameters Process finished with exit code 1 how to solve :- pyautogui.KeyUp('space') TypeError: object() takes no parameters what do you mean by the above message
has answer: http://stackoverflow.com/a/51086144
has title: TypeError: object() takes no parameters (trex dino bot)
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/comment/89226828
type: QuestionComment
has text: Please do not post code as images
comment on: http://stackoverflow.com/q/51120712
score: 5
type: Comment

http://stackoverflow.com/q/51087150
upvote count: 3
has title: Make a python script launch itself at startup
downvote count: 3
has comment: http://stackoverflow.com/comment/89162859
type: Question
has answer: http://stackoverflow.com/a/51087732
has comment: http://stackoverflow.com/comment/89163573
score: 0
has comment: http://stackoverflow.com/comment/89162803
has comment: http://stackoverflow.com/comment/89162778
answer count: 1
has comment: http://stackoverflow.com/comment/89162830
favorite count: 0
accepted answer: http://stackoverflow.com/a/51087732
linked to: http://stackoverflow.com/q/4438020
tagged with: windows
tagged with: python
duplicate of: http://stackoverflow.com/q/4438020
has body: I have wrote the following program. I made its setup. It installed successfully. Now, I want my program to start at startup without manually copying its shortcut to startup folder i.e C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup. I would like my program to run automatically at startup like many commercial programs (like utorrent, Internet Downloader Manager, etc) do. How can I do that?
type: AnsweredQuestion

screen-scraping
tags question: http://stackoverflow.com/q/51107657
tags question: http://stackoverflow.com/q/51154023
type: Tag
tag name: screen-scraping
tags question: http://stackoverflow.com/q/51019623

http://stackoverflow.com/comment/89104154
score: 1
has text: If I'm not wrong, `user.id` will be `None` until a DB row is created
type: QuestionComment
comment on: http://stackoverflow.com/q/51056816
type: Comment

http://stackoverflow.com/a/51117443
type: Answer
accepted answer of: http://stackoverflow.com/q/51117357
has body: i think your problem is here: server = smtplib.SMTP('smtp.yandex.com.tr:465') you need to use smtplib.SMTP_SSL because connection is security with SSL docs, also smtplib.SMTP_SSL get many params, first is host and second is port and other params, but you need now only this two, you need to give host and port separately, try this def send_emails(title,msg): server = smtplib.SMTP_SSL('smtp.yandex.com.tr', 465) ...
has comment: http://stackoverflow.com/comment/89221419
has comment: http://stackoverflow.com/comment/89221303
has comment: http://stackoverflow.com/comment/89221482
has comment: http://stackoverflow.com/comment/89221386
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89221193
answers question: http://stackoverflow.com/q/51117357
has comment: http://stackoverflow.com/comment/89221353
has comment: http://stackoverflow.com/comment/89221334

http://stackoverflow.com/comment/89155773
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51078195
has text: Have you tried just string concatenating? `"$.something." + F.col("key")`?

http://stackoverflow.com/q/51124725
has answer: http://stackoverflow.com/a/51174322
tagged with: python
has answer: http://stackoverflow.com/a/51130512
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1984325
tagged with: sqlalchemy
type: Question
linked to: http://stackoverflow.com/q/3693771
has body: I use SQLAlchemy (really good ORM but documentation is not clear enough) for communicating with PostgreSQL Everything was great till one case when postgres "crashed" cause of maximum connection limits was reached: no more connections allowed (max_client_conn). That case makes me think that I do smth wrong. After few experiments I figure out how not to face that issue again, but some questions left Below you'll see code examples (in Python 3+, PostgreSQL settings are default) without and with mentioned issue, and what I'd like to hear eventually is answers on following questions: What exactly does context manager do with connections and sessions? Closing session and disposing connection or what? Why does first working example of code behave as example with issue without NullPool as poolclass in "connect" method? Why in the first example I got only 1 connection to db for all queries but in second example I got separate connection for each query? (please correct me if I understood it wrong, was checking it with "pgbouncer") What is the best practices to open and close connections(and/or work with Session) when you use SQLAlchemy and PostgreSQL DB for multiple instances of script (or separate threads in script) that listens requests and has to have separate session to each of them? (I mean raw SQLAlchemy not Flask-SQLAlchemy or smth like this) Working example of code without issue: making connection to DB: from sqlalchemy.pool import NullPool # does not work without NullPool, why? def connect(user, password, db, host='localhost', port=5432): """Returns a connection and a metadata object""" url = 'postgresql://{}:{}@{}:{}/{}'.format(user, password, host, port, db) temp_con = sqlalchemy.create_engine(url, client_encoding='utf8', poolclass=NullPool) temp_meta = sqlalchemy.MetaData(bind=temp_con, reflect=True) return temp_con, temp_meta function to get session to work with DB: from contextlib import contextmanager @contextmanager def session_scope(): con_loc, meta_loc = con…
upvote count: 12
accepted answer: http://stackoverflow.com/a/51130512
has title: SQLAlchemy - work with connections to DB and Sessions (not clear behavior and part in documentation)
possible better answer: http://stackoverflow.com/a/51125837
score: 12
has comment: http://stackoverflow.com/comment/124843178
tagged with: postgresql
has answer: http://stackoverflow.com/a/51125837
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51130383
type: Question
has comment: http://stackoverflow.com/comment/89254832
has title: Flask stuck loading after opening a certain route with a function
has comment: http://stackoverflow.com/comment/89255492
has comment: http://stackoverflow.com/comment/89246473
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/89256054
has comment: http://stackoverflow.com/comment/89252058
answer count: 1
has body: I'm relatively new to Python and Flask. I've been trying to create a web application that reads data readings from a .txt file and plots them onto a matplotlib plot. In this web-app, I have a front page with 3 buttons. These buttons redirect to different routes with functions that read data and plot them onto a matplotlib plot. The web-app works perfectly only for the first time I go to either of these routes. After that nothing loads anymore. I guess I have an infinite loop of some sort but I can't figure it out. Also, after the website gets stuck the Python process starts consuming more resources. The problem persists only when I open this route on the web-app: @app.route("/temperature/") This loads without problems on the web-page, but only for one time and the whole web-app gets stuck and I cannot access any of the other routes either. Thanks in advance! EDIT 1 - Whole code below cloudapp.py (Python sourcecode that runs Flask and the functions) from flask import Flask from flask import render_template from flask import request import numpy as np import matplotlib.pyplot as plt, mpld3 from datetime import datetime app = Flask(__name__, template_folder='C:\Users\Valtteri\Desktop\cloudapp\Templates\HTML') global all_lines @app.route("/") def frontpage(): return render_template('frontpage.html') @app.route("/temperature/") def temperature(): f = open('C:/Email/file.txt', 'r') cpt = 0 # Line amount value all_lines = [] # List that has every Nth value for line in f: cpt += 1 # Goes through every line and adds 1 to the counter # How often values are plotted (every Nth value) if cpt%100 == 0: all_lines.append(line) # When 30th line is counted, add that line to all_lines[] list if cpt == 500: # How many values are plotted (counts from first) break dates = [str(line.split(';')[0]) for line in all_lines] date = [datetime.strptime(x,'%Y.%m.%d_%H:%M') for x in dates] y = [float(line.split(';')[1]) for line in all_lines] z = [float(line.split()[2]) for line in all_lines] fig,…
has answer: http://stackoverflow.com/a/51137156
has comment: http://stackoverflow.com/comment/89245874
type: UnansweredQuestion
tagged with: mpld3
has comment: http://stackoverflow.com/comment/89254630
tagged with: python
has comment: http://stackoverflow.com/comment/89254289
has comment: http://stackoverflow.com/comment/89250135
has comment: http://stackoverflow.com/comment/89248876
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89246820
tagged with: web-applications

http://stackoverflow.com/comment/89231476
type: AnswerComment
has text: Well the unnamed parameters have as advantage that if you change the name of the parameter, no changes have to be made to the `{% url ...%}`s, but in case you change the order, you have to change them. If you later want to change the *order* you better use named parameters. Point is that typically changing the *parameters* of a URL does not happen often, since this is not visible to users.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51123086

http://stackoverflow.com/comment/89138972
type: Comment
comment on: http://stackoverflow.com/a/51074686
score: 1
has text: @MAK The real problem is that no CSV should have a two-character long delimiter, which is the case in the sample text in your question. In other words, your sample text is not actually a valid CSV. If it had only either `;` or a tab as the delimiter (but not both), then you can pass `';\t'` as the second argument to `sniff` to let it pick, or you can even not pass a second argument to let it make its own best guess.
type: AnswerComment

http://stackoverflow.com/q/51042180
has body: We have nested data in Elasticsearch and would like to move from Elasticsearch to Redis. Does RediSearch support nested queries?
has answer: http://stackoverflow.com/a/53921775
answer count: 1
tagged with: redisearch
score: 0
tagged with: redis
tagged with: python
type: UnansweredQuestion
has title: Does redisearch support nested query?
type: Question

http://stackoverflow.com/comment/89075313
has text: Although I didn't use the exact same code you posted. But this did provide me leads to my final answer. Posting my final code as another alternative to your solution. I've accepted your answer.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51024346
type: AnswerComment

http://stackoverflow.com/comment/89302290
type: QuestionComment
type: Comment
score: 0
has text: I have found something that may help me. Adding arguments to Go c compiler.
comment on: http://stackoverflow.com/q/51156221

http://stackoverflow.com/q/51159775
type: Question
has title: How to randomly shuffle the depth, height,width of 5D matrix?
has body: I have a 5D matrix as B x C x D x H x W where D is depth, H is height and W is width. For example, the matrix has size of 16 x 3 x 256 x 128 x 64, I want to randomly shuffle the last three dimensions (D,H,W) to obtain a new matrix. How can I do it in python? The output matrix likes 16 x 3 x 256 x 128 x 64 16 x 3 x 64x 128 x 256 16 x 3 x 256 x 64x 128 16 x 3 x 128x 64x 256 ...
score: 0
has comment: http://stackoverflow.com/comment/89303269
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51160007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89302967

http://stackoverflow.com/q/51103206
score: 0
type: UnansweredQuestion
tagged with: python
has title: Reaching a limit when executing python scripts from node.js
tagged with: node.js
linked to: http://stackoverflow.com/q/50787082
answer count: 0
has body: I am executing python scripts through node.js using express and spawn (I am executing them within an Alpine Container). Python scripts write json data within the stdout using: print(json_data, file=sys.stdout) Whereas the node.js script read the input with: var child = spawn(...); child.stdout.on('data', function(data) { res.json(JSON.parse(data.toString()).data); }); Unfortunately, I reach a limit at 2^16 bytes with an Unexpected end of JSON input error message. When redirecting the output fto a file from Python script, the file is complete. I haven't seen any limit neither from spawn nor from write within both documention. Moreover, sys.maxsizereturns 2^32. Any explanation?
duplicate of: http://stackoverflow.com/q/50787082
tagged with: alpine-linux
has comment: http://stackoverflow.com/comment/89193848
type: Question
tagged with: spawn
has comment: http://stackoverflow.com/comment/89194392
tagged with: docker

http://stackoverflow.com/comment/89225796
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51119801
has text: Cool, good luck! Lmk if you have questions. Also, you can check out a bunch of Hough line related functions I built [here on GitHub](https://github.com/alkasm/houghtool/blob/master/houghtool/houghtool.py) which might help. I don't have time to write up an actual solution here but if you do get it working, it is not bad form to answer your own question so others might stumble upon it! :) Also the benefit of using Hough lines on the contours is that even if the corner is outside the image, you can still compute the actual corner.

http://stackoverflow.com/q/51140683
answer count: 0
type: Question
has body: I'm working on a program in Python that copies all the mp3 files in a folder to another destination, but I'm facing a problem. This is the code: import os import shutil def copy_music(): file_list = os.listdir(r"C:\Users\hp\Downloads") saved_path = os.getcwd() print("current working directory is "+saved_path) os.chdir(r"C:\Users\hp\Downloads") for file_name in file_list: test = file_name.endswith('.mp3') if test == True: shutil.copy(file_name, 'c:\Users\hp\music') os.chdir(saved_path) print('all the mp3 files are successfully copied to your destination') copy_music() This is the error message: Traceback (most recent call last): File "C:/Users/hp/Desktop/projects/code/copymusic.py", line 14, in &lt;module&gt; copy_music() File "C:/Users/hp/Desktop/projects/code/copymusic.py", line 11, in copy_music shutil.copy(file_name, 'c:\Users\hp\music') File "C:\Python27\lib\shutil.py", line 133, in copy copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 96, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 22] invalid mode ('rb') or filename: 'Arcangel ?Bad Bunny - Original [Official Video].mp3'
score: 0
tagged with: ioerror
has comment: http://stackoverflow.com/comment/89266675
has title: IOError: [Errno 22] invalid mode ('rb') or filename invoking shutil.copy()
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89265490

http://stackoverflow.com/comment/89329947
comment on: http://stackoverflow.com/a/51157230
score: 0
type: AnswerComment
type: Comment
has text: Well, thank you kutschkem, I'm bad at math, you know :-D

http://stackoverflow.com/q/51162295
possible better answer: http://stackoverflow.com/a/55841613
has comment: http://stackoverflow.com/comment/89348414
linked to: http://stackoverflow.com/q/45960192
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51555291
has comment: http://stackoverflow.com/comment/89310861
score: 0
has title: Tensorflow dataset API for time series classification
answer count: 2
has body: I am getting used to the new dataset API and try to do some time series classification. I have a dataset formatted as tf-records in the shape of: (time_steps x features). Also I have a label for each time step. (time_steps x 1) What I want to do is to reformat the dataset to have a rolling window of time steps like this: (n x windows_size x features). With n being the amounts of time_steps-window_size (if I use a stride of 1 for the rolling window) The labels are supposed to be (window_size x 1), meaning that we take the label of the last time_step in the window. I already know, that I can use tf.sliding_window_batch() to create the sliding window for the features. However, the labels get shaped in the same way, and I do not know how to do this correctly: (n x window_size x 1 How do I do this using the tensorflow dataset API? https://www.tensorflow.org/programmers_guide/datasets Thanks for your help!
tagged with: tensorflow-datasets
has answer: http://stackoverflow.com/a/55841613
has answer: http://stackoverflow.com/a/51555291
tagged with: python
has comment: http://stackoverflow.com/comment/89348434
type: AnsweredQuestion

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

http://stackoverflow.com/q/51044646
score: 0
tagged with: selenium
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51047908
has comment: http://stackoverflow.com/comment/89080866
type: Question
tagged with: python
tagged with: selenium-webdriver
has title: Selenium + Python: next button through click()
has comment: http://stackoverflow.com/comment/89117220
has body: I don't understand why when I go to this page https://www.ryanair.com/it/it/voli-low-cost/?from=BGY&out-from-date=2018-09-01&out-to-date=2018-09-30&budget=60&trip-length-from=1&trip-length-to=3 or whatever page from that website, Selenium doesn't allow me on the script to run the next page button with the code: next_page = browser.find_element_by_xpath('/html/body/div[2]/main/div/div[2]/farefinder-widget/div/div[2]/div[2]/div/div/core-pagination/div/div[2]/a') next_page.click() On the HTML code: Successivo Whereas If I write it on the shell, oddly enough it does work, with the same exact lines. I've also tried to give it some seconds with time.sleep, but nothing happened.

http://stackoverflow.com/comment/89221705
has text: Additionally, I see in [the docs](https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.sub.html) it says *"Equivalent to `dataframe - other`"*, but it seems it is not, as that operation yields a wildly different result!?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51117855
type: AnswerComment

http://stackoverflow.com/q/51127635
answer count: 1
tagged with: python
has title: How to update Python application in production
type: AnsweredQuestion
type: Question
has body: I wrote a Python application that runs on a Linux server as a daemon. What it does is it listens to a Rabbitmq topic. Whenever there is a new message, the app processes the message doing the following 5 steps. Query database and grab audio data in String format. Convert the audio data to WAV. Calls deep learning model to make prediction to the audio Upload WAV to S3 bucket Send result back to a web API. The main program runs with multithread: for i in range(2): t = threading.Thread(target=process_msg, name='worker-%s' % i) t.setDaemon(True) t.start() while True: time.sleep(5) Callback function process_msg is the method that does the 5 steps. Currently this is how I deploy changes to the dev server. Kill active process of the app Do git pull to get updates Start the app again. This manual process is ok for dev, but it is no good for production. Because if I stop the application while it is in the middle of processing a message, it would exit without completing the job. What is the best way to CICD this app without interrupting the process?
score: 0
tagged with: continuous-integration
has answer: http://stackoverflow.com/a/51133566
accepted answer: http://stackoverflow.com/a/51133566

http://stackoverflow.com/comment/89025131
has text: Happy to help :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51014476
type: AnswerComment

http://stackoverflow.com/q/51163018
favorite count: 0
tagged with: equals
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
has title: maintaining consistent matplotlib axes limits
type: Question
tagged with: matplotlib
downvote count: 0
has body: I'm trying to produce a series of figures showing geometric shapes of different sizes (one shape in each figure) but consistent, equal-spacing axes across each figure. I can't seem to get axis('equal') to play nice with set_xlim in matplotlib. Here's the closest I've come so far: pts0 = np.array([[13,34], [5,1], [ 0,0], [7,36], [13,34]], dtype=np.uint8) pts1 = np.array([[10,82], [119,64], [149,63], [136,0], [82,14], [81,18], [26,34], [3,29], [0,34], [10,82]], dtype=np.uint8) shapes = [pts0,pts1] for i in range(2): pts = shapes[i] fig = plt.figure() ax1 = fig.add_subplot(111) plotShape = patches.Polygon(pts, True, fill=True) p = PatchCollection([plotShape], cmap=cm.Greens) color = [99] p.set_clim([0, 100]) p.set_array(np.array(color)) ax1.add_collection(p) ax1.axis('equal') ax1.set_xlim(-5,200) ax1.set_ylim(-5,200) ax1.set_title('pts'+str(i)) plt.show() In my system, this results in two figures with the same axes, but neither one of them shows y=0 or the lower portion of the shape. If I remove the line ax1.set_ylim(-5,200), then figure "pts1" looks correct, but the limits of figure "pts0" are such that the shape doesn't show up at all. My ideal situation is to "anchor" the lower-left corner of the figures at (-5,-5), define xlim as 200, and allow the scaling of the x axis and the value of ymax to "float" as the figure windows are resized, but right now I'd be happy just to consistently get the shapes inside the figures. Any help would be greatly appreciated!
answer count: 1
has answer: http://stackoverflow.com/a/51163049

http://stackoverflow.com/q/51087573
has title: Python Data Storage Method
answer count: 0
has body: I am trying to create a database of variable in python from a large csv file. Any given row in the csv file can be uniquely identified from 4 columns. To give an idea of the data structure: Supplier A Tariff RateA Region 1 Payment Method 1 Payment Method 2 Region 2 Payment Method 1 Tariff Rate B Region 1 Payment Method 1 Payment Method 2 Region 2 Payment Method 1 Supplier B etc... Once I can uniquely identify the row I am performing calculations using other information in that row to produce a list of three, two dimensional arrays. I will then create a dictionary linking each variable in the database with its respective array. I would then like to be able to retrieve these arrays for comparison/ analysis etc... In order to create the database I have copied the code below which is really slow and I'm currently unsure if creating an empty list before each for loop will have the desired result? Any input or suggestions would be greatly appreciated. supplier_log = [] for supplier in Tariff_Book.Supplier_Name: if supplier not in supplier_log: print("Supplier: " + supplier) supplier_log.append(supplier) tariff_log = [] temp = Tariff_Book.query('Supplier_Name == @supplier') for tariff in temp.Tariff_Name: if tariff not in tariff_log: print("Tariff: " + tariff) tariff_log.append(tariff) region_log = [] temp = Tariff_Book.query('Supplier_Name == @supplier &amp; Tariff_Name == @tariff' ) for region in temp.Region: if region not in region_log: print("Region: " + str(region)) region_log.append(region) payment_method_log = [] temp = Tariff_Book.query('Supplier_Name == @supplier &amp; Tariff_Name == @tariff &amp; Region == @region') for payment_method in temp.Payment_Method: if payment_method not in payment_method_log: print("Payment Method: " + payment_method) payment_method_log.append(payment_method)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89181169
has comment: http://stackoverflow.com/comment/89163746
tagged with: database
type: Question
score: 0
tagged with: data-management

http://stackoverflow.com/q/51036943
answer count: 2
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/58223545
favorite count: 0
tagged with: linux
tagged with: fork
tagged with: memory-leaks
tagged with: python
has title: Is it possible to monitor copy on write for forked linux processes? (specifically python)
has comment: http://stackoverflow.com/comment/89066078
has answer: http://stackoverflow.com/a/51045861
linked to: http://stackoverflow.com/q/14941729
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14224068
upvote count: 2
has comment: http://stackoverflow.com/comment/89065770
has comment: http://stackoverflow.com/comment/89066637
type: Question
accepted answer: http://stackoverflow.com/a/51045861
has answer: http://stackoverflow.com/a/58223545
has body: I have a set of python processes that share a large object (sharing is done by forking the processes after initializing the object) I notice a strange memory leak: the process memory (VSZ and RSS) hardly change the total system memory increases steadily My guess is the shared object does change (it's 'logically' readonly, but it's possible that some internal private variables change even when just reading from it) - which causes memory pages to be copied is there a way to verify this?

http://stackoverflow.com/a/51051382
accepted answer of: http://stackoverflow.com/q/51051268
has body: You could hint that q for quit leads to stop adding further filenames: if __name__ == '__main__': filename = input('Enter your file name:') other=[] while True: inp = input('Enter your other file name (q for quit)') if inp == 'q': break else: other.append(inp) read_files(filename, other) EDIT: Probably it's even more convenient to stop if nothing was entered, so the while loop would be: while True: inp = input('Enter your other file name (press ENTER for quit)') if inp == '': break else: other.append(inp)
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51051268
has comment: http://stackoverflow.com/comment/89093927
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89094006

http://stackoverflow.com/a/51065590
has comment: http://stackoverflow.com/comment/89252026
has body: pexpect is good for this sort of thing: https://pexpect.readthedocs.io/en/stable/api/pxssh.html https://github.com/pexpect/pexpect/blob/master/examples/monitor.py
answers question: http://stackoverflow.com/q/51065438
has comment: http://stackoverflow.com/comment/89121029
score: 0
type: Answer

http://stackoverflow.com/comment/89297625
has text: A reality check: to create a module for CPython, you're supposed to build your Go code in a way to provide a C-compatible "archive" or a library—that is, you're supposed to use the [`-buildmode`](https://golang.org/pkg/cmd/go/internal/help/) option with one of `c-archive` or `c-shared` values. The further build process (which would use that archive/library) is supposed to act in accordance with the type of the produced artefact.
score: 0
comment on: http://stackoverflow.com/q/51156221
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51014929
downvote count: 0
answers question: http://stackoverflow.com/q/51014804
has body: when in doubt use css-selectors. when not in doubt use css-selectors but obviously, it works only if you're sure it will always be the third td country = cards.select_one('td:nth-of-type(3) a') print(country['title'], country.text)
score: 3
has comment: http://stackoverflow.com/comment/89023029
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/89022824
type: Answer
accepted answer of: http://stackoverflow.com/q/51014804

http://stackoverflow.com/comment/89056079
has text: The way you have it set up now you could get negative values, is that desired?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51031822
score: 0

http://stackoverflow.com/a/54938196
downvote count: 0
has body: Your code works just fine. import numpy as np import matplotlib.pyplot as plt mu,sigma,n = 0.,1.,1000 def normal(x,mu,sigma): return ( 2.*np.pi*sigma**2. )**-.5 * np.exp( -.5 * (x-mu)**2. / sigma**2. ) x = np.random.normal(mu,sigma,n) y = normal(x,mu,sigma) plt.plot(x,y)
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51012793
score: 2

http://stackoverflow.com/comment/89205513
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51107850
type: Comment
has text: perfect. Atleast there are no errors. thats a good start. Now how do you think your script is working as expected ? you have to print it somewhere. do whatever is easiest for you.

heroku
tags question: http://stackoverflow.com/q/51118600
tags question: http://stackoverflow.com/q/51056745
tags question: http://stackoverflow.com/q/51049744
tags question: http://stackoverflow.com/q/51148569
tags question: http://stackoverflow.com/q/51017096
tags question: http://stackoverflow.com/q/51118432
tags question: http://stackoverflow.com/q/51164752
tags question: http://stackoverflow.com/q/51128831
tags question: http://stackoverflow.com/q/51123499
tags question: http://stackoverflow.com/q/51097431
tags question: http://stackoverflow.com/q/51103763
type: Tag
tags question: http://stackoverflow.com/q/51122790
tags question: http://stackoverflow.com/q/51014504
tags question: http://stackoverflow.com/q/51105874
tags question: http://stackoverflow.com/q/51107962
tags question: http://stackoverflow.com/q/51019330
tag name: heroku

http://stackoverflow.com/q/51123499
has title: Python- Error while deploying Django app on Heroku
tagged with: django
tagged with: python
tagged with: heroku
has body: I followed the steps on here I configured all well maybe miss something. Pushed codes to the git. But when I run command git push --set-upstream heroku master, I get this following error. ERROR remote: ModuleNotFoundError: No module named 'django_heroku' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... I pip installed django_heroku module and wrote this code import django_heroku django_heroku.settings(locals()) at the very bottom in settings.py so what's the problem here?
has comment: http://stackoverflow.com/comment/89232896
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89233545
type: Question
upvote count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89243621
has comment: http://stackoverflow.com/comment/89233263
type: UnansweredQuestion

http://stackoverflow.com/a/51044121
accepted answer of: http://stackoverflow.com/q/51043766
has body: &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; t=[3 ,3, 4, 0, 0, 3, 1, 0, 4, 3, 3, 3, 0] &gt;&gt;&gt; t_old=[3, 3, 4, 0, 0] &gt;&gt;&gt; N = Counter(t) - Counter(t_old) &gt;&gt;&gt; Nk = [N.get(i,0) for i in range(5)] &gt;&gt;&gt; Nk [2, 1, 0, 4, 1]
type: Answer
answers question: http://stackoverflow.com/q/51043766
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/89302469
comment on: http://stackoverflow.com/a/51159163
has text: I understand, honestly I didn't know there was a generator data structure. I'm new to this. I was just trying to get your single write to the file that prepped the output before hand. Originally I thought it was a dict. Doctors answer writes the output to the file when casting as a str. I'm not looking for a specific key, just the entire output of each member in the distribution list.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89053967
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51030537
has text: @NoahG- start with figuring out how to read a JSON file first then worry about how to extract the links you want after. There are numerous examples on SO that can show you how to read JSON you can use to get started, [python- parsing values from a json file](https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file)
type: Comment

http://stackoverflow.com/a/51044283
answers question: http://stackoverflow.com/q/51043744
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: Looks like you have outdated version of setup tools. try: pip install --upgrade setuptools

http://stackoverflow.com/q/51079985
has comment: http://stackoverflow.com/comment/89148533
has comment: http://stackoverflow.com/comment/89151400
has title: Python 3 check if function is executing inside multiprocessing pool
tagged with: python
has body: Is it possible to check in f if it's inside a Pool? Alternatively what is a good catch that only catches that specific error? a = [[1, 2], [1, 2]] def g(x): return x def f(x): try: with Pool(2) as p: print(p.map(g, x)) except Exception as e: print(type(e)) return x with Pool(2) as p: print(p.map(f, a))
favorite count: 0
has answer: http://stackoverflow.com/a/71218775
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89148713
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89148924
downvote count: 1
has comment: http://stackoverflow.com/comment/89149911
score: 1
has comment: http://stackoverflow.com/comment/89153406
type: Question
tagged with: multiprocessing
tagged with: pool
answer count: 2
has answer: http://stackoverflow.com/a/51082589

http://stackoverflow.com/q/51126928
favorite count: 0
has answer: http://stackoverflow.com/a/51130196
tagged with: statistics
possible better answer: http://stackoverflow.com/a/65318530
has answer: http://stackoverflow.com/a/65318530
linked to: http://stackoverflow.com/q/30650257
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89257773
upvote count: 2
has title: Statsmodels.formula.api OLS does not show statistical values of intercept
tagged with: regression
accepted answer: http://stackoverflow.com/a/51130196
type: AnsweredQuestion
tagged with: statsmodels
tagged with: linear-regression
type: Question
answer count: 2
downvote count: 0
has body: I am running the following source code: import statsmodels.formula.api as sm # Add one column of ones for the intercept term X = np.append(arr= np.ones((50, 1)).astype(int), values=X, axis=1) regressor_OLS = sm.OLS(endog=y, exog=X).fit() print(regressor_OLS.summary()) where X is an 50x5 (before adding the intercept term) numpy array which looks like this: [[0 1 165349.20 136897.80 471784.10] [0 0 162597.70 151377.59 443898.53]...] and y is a a 50x1 numpy array with float values for the dependent variable. The first two columns are for a dummy variable with three different values. The rest of the columns are three different indepedent variables. Although, it is said that the statsmodels.formula.api.OLS adds automatically an intercept term (see @stellacia's answer here: OLS using statsmodel.formula.api versus statsmodel.api) its summary does not show the statistical values of the intercept term as it evident below in my case: OLS Regression Results ============================================================================== Dep. Variable: Profit R-squared: 0.988 Model: OLS Adj. R-squared: 0.986 Method: Least Squares F-statistic: 727.1 Date: Sun, 01 Jul 2018 Prob (F-statistic): 7.87e-42 Time: 21:40:23 Log-Likelihood: -545.15 No. Observations: 50 AIC: 1100. Df Residuals: 45 BIC: 1110. Df Model: 5 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ x1 3464.4536 4905.406 0.706 0.484 -6415.541 1.33e+04 x2 5067.8937 4668.238 1.086 0.283 -4334.419 1.45e+04 x3 0.7182 0.066 10.916 0.000 0.586 0.851 x4 0.3113 0.035 8.885 0.000 0.241 0.382 x5 0.0786 0.023 3.429 0.001 0.032 0.125 ============================================================================== Omnibus: 1.355 Durbin-Watson: 1.288 Prob(Omnibus): 0.508 Jarque-Bera (JB): 1.241 Skew: -0.237 Prob(JB): 0.538 Kurtosis: 2.391 Cond. No. 8.28e+05 ==========…

http://stackoverflow.com/comment/89137485
comment on: http://stackoverflow.com/q/51072660
score: 0
type: Comment
type: QuestionComment
has text: I really think i'm being overly redundant on my questions explaining what I really asked, but please, if you still need some details, ask me! I also want to thank you in advance!

http://stackoverflow.com/a/51116375
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89218952
upvote count: 1
type: AcceptedAnswer
has body: Install flask uploads module pip install flask-uploads from flask_uploads import UploadSet, configure_uploads
accepted answer of: http://stackoverflow.com/q/51116352
answers question: http://stackoverflow.com/q/51116352
type: Answer

http://stackoverflow.com/q/51089388
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89169862
has comment: http://stackoverflow.com/comment/89194919
has title: Generating new output for each row in a csv file
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89170807
has body: I have a csv file with some data in it, match_type keyword campaign group exact find a key Non-Branded Find key - Exact phrase key physicians Branded System (key) key Brand (Acronyn) - Phrase phrase key locations Branded System (key) key Brand (Acronyn) - Phrase I want to loop through each row and for each match_type generate new output, like so, exact = pd.DataFrame() phrase = pd.DataFrame() for x in match_type: if x == 'exact': exact['Match type'] = pd.np.where(pos.Match_type.str.contains('exact'), 'exact', pd.np.where(pos.Match_type.str.contains('phrase'), 'negative exact', 'negative exact')) exact['Keyword'] = pd.np.where(pos.Search_term.str.contains('physicians'), 'key physicians', pd.np.where(pos.Search_term.str.contains('locations'), 'key locations', pd.np.where(pos.Search_term.str.contains('find'), 'find a key', 'None'))) exact['Campaign'] = pd.np.where(pos.Campaign.str.contains('Branded'), 'Branded System (key)', pd.np.where(pos.Campaign.str.contains('Non-Branded'), 'Non-Branded Brand', 'None')) exact['Ad_Group'] = pd.np.where(pos.Ad_group.str.contains('- Phrase'), 'key Brand (Acronyn) - Phrase', pd.np.where(pos.Ad_group.str.contains('- Exact'), 'Find key - Exact', 'None')) elif x == 'phrase': phrase['Match type'] = pd.np.where(pos.Match_type.str.contains('exact'), 'negative phrase', pd.np.where(pos.Match_type.str.contains('phrase'), 'phrase', 'negative phrase')) phrase['Keyword'] = pd.np.where(pos.Search_term.str.contains('physicians'), 'key physicians', pd.np.where(pos.Search_term.str.contains('locations'), 'key locations', pd.np.where(pos.Search_term.str.contains('find'), 'find a key', 'None'))) phrase['Campaign'] = pd.np.where(pos.Campaign.str.contains('Branded'), 'Branded System (key)', pd.np.where(pos.Campaign.str.contains('Non-Branded'), 'Non-Branded Brand', 'None')) phrase['Ad_Group'] = pd.np.where(pos.Ad_group.str.contains('- Phrase'), 'key Brand (Acronyn) - Phrase', pd.np.where(pos.Ad_group.str.contains('- Exact'), 'Find key - Exact', 'None')) Now…
type: Question
has comment: http://stackoverflow.com/comment/89167949
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89170641

http://stackoverflow.com/comment/89061078
score: 0
has text: I just chose two RGB colors that matched your desired colors and normalized them.
type: AnswerComment
comment on: http://stackoverflow.com/a/51034518
type: Comment

http://stackoverflow.com/a/51193566
has comment: http://stackoverflow.com/comment/89598795
has comment: http://stackoverflow.com/comment/89599926
accepted answer of: http://stackoverflow.com/q/51164851
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51164851
has comment: http://stackoverflow.com/comment/89600940
type: Answer
score: 2
upvote count: 2
has body: Pika and eventlet.monkey_patch are not compatible. You will have to use eventlet without patching system calls, if that is possible.
has comment: http://stackoverflow.com/comment/89600467
has comment: http://stackoverflow.com/comment/89376418

http://stackoverflow.com/q/51095528
has comment: http://stackoverflow.com/comment/89179189
type: Question
has body: I've a requirement to convert CSV Data File to Nested JSON in Python for an application. My below current Python code is working fine for 1 Customer/Accounts document but somehow not able to create json dump for all the customers in the CSV file. I am providing the Python code below which will give you some insight on what I am trying to achieve. Please let me know if any existing resolutions on this. Sample Python CODE: import pandas as pd from itertools import groupby from collections import OrderedDict import json df = pd.read_csv('cust.csv', dtype={ "ClientID" : str, "ClientName" : str, "AcctID" : str, "AcctNbr" : str, "AcctTyp" : str }) results = [] for (ClientID, ClientName), bag in df.groupby(["ClientID", "ClientName"]): contents_df = bag.drop(["ClientID", "ClientName"], axis=1) subset = [OrderedDict(row) for i,row in contents_df.iterrows()] results.append(OrderedDict([("ClientID", ClientID),("ClientName", ClientName),("subset", subset)])) print json.dumps(results[0], indent=4) with open('ExpectedJsonFile.json', 'w') as outfile: outfile.write(json.dumps(results[0], indent=4)) Sample INPUT CSV: ClientID,ClientName,AcctID,AcctNbr,AcctTyp ---------------------------------------------------------- 00001,John George,812001,812001095,DDA 00001,John George,813002,813002096,SAV 00001,John George,814003,814003097,AFS 00024,Richard Polado,512987,512987085,ML 00024,Richard Polado,512983,512983086,IL 00345,John Cruze,1230,123001567,SAV 00345,John Cruze,5145,514502096,CD 00345,John Cruze,7890,7890033527,SGD Desired Output JSON: { "clientId":00001, "ClientName":"John George", "subset":[ { "AcctID":812001, "AcctNbr":"812001095", "AcctTyp":"DDA", }, { "AcctID":813002, "AcctNbr":"813002096", "AcctTyp":"SAV", }, { "AcctID":814003, "AcctNbr":"814003097", "AcctTyp":"AFS", } ] }, { "clientId":00024, "ClientName":"Richard Polado", "subset":[ { "AcctID":512987, "AcctNbr":"512987085", "AcctTyp":"ML", }, { "AcctID":512983, "AcctNbr":"512983086", "AcctTyp":"IL", } ] } and these docume…
score: 5
linked to: http://stackoverflow.com/q/11492656
has title: Convert CSV Data to Nested JSON in Python
upvote count: 5
has answer: http://stackoverflow.com/a/51096144
answer count: 2
has comment: http://stackoverflow.com/comment/89180427
tagged with: pandas
has comment: http://stackoverflow.com/comment/89179107
possible better answer: http://stackoverflow.com/a/54348278
downvote count: 0
has answer: http://stackoverflow.com/a/54348278
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51096144
has comment: http://stackoverflow.com/comment/89184358
has comment: http://stackoverflow.com/comment/89179226
has comment: http://stackoverflow.com/comment/89181464
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89179259

http://stackoverflow.com/a/51113164
type: Answer
score: 2
downvote count: 0
has body: Ok, I was over thinking the problem. Taking the first entry of the list that is passed in a patch solves the problem for me. Changing: provinces.data['name'][provinces.selected.indices] To: provinces.data['name'][provinces.selected.indices[0]]
answers question: http://stackoverflow.com/q/51113004
upvote count: 2

http://stackoverflow.com/q/51020809
has comment: http://stackoverflow.com/comment/89103010
has title: Zappa doesn't work with Flask Blueprint
answer count: 1
tagged with: flask
has answer: http://stackoverflow.com/a/51056293
has body: I have a Flask app and I'm using flask_restful and blueprint to serve up my APIs. After deploying my app with Zappa, Zappa gives me Error like below: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. When I removed my api, zappa didn't give me any error. So, I could know Blueprint is problem. How can I solve this problem? (Of course, I'am using Python 3.6) zappa_settings.py { "dev": { "app_function": "main.app", "aws_region": "us-east-1", "profile_name": "default", "project_name": "zap", "runtime": "python3.6", "s3_bucket": -MYBUCKETNAME- } } main.py from flask import Flask from api.api import serendipity from api.chat_api import chat from database import db # from mail import mail # from admin.controller import admin app = Flask(__name__, template_folder='admin/templates') app.config.from_object('config') app.register_blueprint(serendipity) app.register_blueprint(chat, url_prefix='/chat') with serendipity_app.app_context(): db.init_app(app) db.create_all(app=app) mail.init_app(app) admin.init_app(app) @app.route('/') def index(): return "{ message: 'Hello, world!' }", 200 # We only need this for local development. if __name__ == '__main__': app.run(host='0.0.0.0') Environment Zappa version used: latest(0.46.1) Operating System and Python version: mac os High Sierra, 10.13.5(17F77) The output of pip freeze: aniso8601==3.0.2 argcomplete==1.9.3 arrow==0.12.1 base58==1.0.0 bcrypt==3.1.4 blinker==1.4 boto3==1.7.45 botocore==1.10.45 CacheControl==0.12.5 cachetools==2.1.0 certifi==2018.4.16 cffi==1.11.5 cfn-flip==1.0.3 chardet==3.0.4 click==6.7 docutils==0.14 durationpy==0.5 firebase-admin==2.11.0 Flask==1.0.2 Flask-Admin==1.5.1 Flask-Mail==0.9.1 Flask-RESTful==0.3.6 Flask-SQLAlchemy==2.3.2 future==0.16.0 gcloud==0.17.0 geographiclib==1.49 geopy==1.14.0 google-api-core==1.2.1 google-api-python-client==1.7.3 google-auth==1.5.0 google-auth-httplib2==0.0.3 google-cloud-core==0.28.1 google-cloud-firestore==0.29.0 goo…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89035628
accepted answer: http://stackoverflow.com/a/51056293
type: Question
tagged with: zappa
tagged with: blueprint
score: 0

http://stackoverflow.com/q/51123248
tagged with: python
accepted answer: http://stackoverflow.com/a/56415267
favorite count: 0
downvote count: 0
has title: Pip network error (and I am not using a proxy!)
tagged with: pip
type: AnsweredQuestion
score: 1
tagged with: pypi
type: Question
upvote count: 1
has body: I am using Ubuntu 16.04 and I often get the infamous pip network error: $ pip3 install matplotlib Collecting matplotlib ... ... TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' It works sometimes, most often it does not. I have to try many, many times until I get something installed. Unlike the many people who have reported similar problems, I am not behind a proxy and I have already tried different networks, both physically and using VPN. I think the problem is that https://pypi.org/ is often unavailable for me. Most of the time, I cannot access the website. I don't know if this is country-specific (Portugal here), but other colleagues of mine have similar problems. A lot of people say to download get-pip.py from here and install pip manually. But that website is down as well. I have managed to download get-pip.py from somewhere else, but then I get the same pypi error.
answer count: 1
has answer: http://stackoverflow.com/a/56415267

http://stackoverflow.com/a/51145490
type: Answer
upvote count: 1
has body: data=read.table(text=" Basket1 Type1 Amount1 Basket2 Type2 Amount2 Basket3 Type3 Amount3 1 Normal 1 10 Normal 3 12 Premium 0 2 Normal 0 3 Normal 3 45 Premium 3 3 Normal 1 3 Normal 3 3 Premium 67 4 Normal 1 5 Normal 3 54 Premium 45",h=T) to shift left, you can do: data%&gt;% rownames_to_column%&gt;% reshape(matrix(2:ncol(.),3),idvar = 1,dir="long")%&gt;% filter(!rowSums(.==0)&gt;0)%&gt;% group_by(rowname)%&gt;% mutate(time=1:n())%&gt;% arrange(time,rowname)%&gt;% data.frame()%&gt;% reshape(timevar = "time",idvar = "rowname",dir="wide")%&gt;% select(-rowname)%&gt;% rename_all(~sub("\\d.","",.x)) Basket1 Type1 Amount1 Basket2 Type2 Amount2 Basket3 Type3 Amount3 1 1 Normal 1 10 Normal 3 NA &lt;NA&gt; NA 2 3 Normal 3 45 Premium 3 NA &lt;NA&gt; NA 3 3 Normal 1 3 Normal 3 3 Premium 67 4 4 Normal 1 5 Normal 3 54 Premium 45 EDIT:: For the data that you provided later: data_set[-1]%&gt;% rownames_to_column%&gt;% reshape(matrix(2:ncol(.),3),idvar = 1,dir="long")%&gt;% filter(!rowSums(.==0)&gt;0)%&gt;% group_by(rowname)%&gt;%mutate(time=1:n())%&gt;% arrange(time,rowname)%&gt;% data.frame()%&gt;% reshape(timevar = "time",idvar = "rowname",dir="wide")%&gt;% select(-rowname)%&gt;% rename_all(~sub("\\d.","",.x)) Basket1 Type1 Amount1 Basket2 Type2 Amount2 1 45 Normal 4 NA &lt;NA&gt; NA 2 35 Premium 5 98 Normal 4
score: 1
answers question: http://stackoverflow.com/q/51145058
downvote count: 0

http://stackoverflow.com/a/68755292
score: 0
has body: Open control panel and Go to "region" settings in windows (refer image 1) => Go to Administrative tab => Change system locale => uncheck the check box "Unicode-UTF 8 for windows language support" click ok and restart your system.
type: Answer
answers question: http://stackoverflow.com/q/51053464

http://stackoverflow.com/comment/89206939
comment on: http://stackoverflow.com/q/51109881
score: 0
type: Comment
type: QuestionComment
has text: To add on to @MoxieBall's remark- note that there are two division operators in python3, `/` and `//`, one of which is far better suited for your problem.

http://stackoverflow.com/comment/89299461
type: QuestionComment
score: 0
has text: That being said... What is wrong with this sequence? `clientSocket.recv`, `clientSocket.shutdown`, `clientSocket.close`, `clientSocket.recv` Perhaps `shutdown` and `close` are not correctly indented?
comment on: http://stackoverflow.com/q/51157571
type: Comment

http://stackoverflow.com/q/51050956
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/89093075
type: UnansweredQuestion
score: 3
upvote count: 3
has title: Get index number from multi-index dataframe in python
tagged with: multi-index
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51051234
has answer: http://stackoverflow.com/a/51051118
downvote count: 0
has body: There seems to be a lot of answers on how to get last index value from pandas dataframe but what I am trying to get index position number for the last row of every index at level 0 in a multi-index dataframe. I found a way using a loop but the data frame is millions of line and this loop is slow. I assume there is a more pythonic way of doing this. Here is a mini example of df3. I want to get a list (or maybe an array) of the numbers in the index for the df >> the last row before it changes to a new stock. The index column is the results I want. this is the index position from the df Stock Date Index AAPL 12/31/2004 1/3/2005 1/4/2005 1/5/2005 1/6/2005 1/7/2005 1/10/2005 3475 AMZN 12/31/2004 1/3/2005 1/4/2005 1/5/2005 1/6/2005 1/7/2005 1/10/2005 6951 BAC 12/31/2004 1/3/2005 1/4/2005 1/5/2005 1/6/2005 1/7/2005 1/10/2005 10427 This is the code I am using, where df3 in the dataframe test_index_list = [] for start_index in range(len(df3)-1): end_index = start_index + 1 if df3.index[start_index][0] != df3.index[end_index][0]: test_index_list.append(start_index)
has comment: http://stackoverflow.com/comment/89092909
tagged with: pandas
linked to: http://stackoverflow.com/q/47495510
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89093122

http://stackoverflow.com/q/51119989
linked to: http://stackoverflow.com/q/37986406
has body: I have a JSON response from the website shown below. I want to print the 'value' and 'datetime' keys of data. I am not able to access these two elements in JSON response. data= {"parameter_name":"Inst", "parameter_code":"WL1","data":[ {"value":3.1289999485,"datetime":"2018-07-01T00:00:00+00:00"}, {"datetime":"2018-07-01T00:30:00+00:00","value":3.1859998703}, {"value":3.33099985123,"datetime":"2018-07-01T00:45:00+00:00"}, {"datetime":"2018-07-01T01:15:00+00:00","value":3.22300004959}, {"datetime":"2018-07-01T01:45:00+00:00","value":3.32299995422}]} my code till now for element in len(data['data']): date = element['datetime'] value = element['value'] print value, date I am getting error for element in len(data['data']): TypeError: string indices must be integers, not str
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51120063
upvote count: 2
has answer: http://stackoverflow.com/a/51120013
tagged with: python
has title: Extracting JSON element
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51120013
has answer: http://stackoverflow.com/a/51120039
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51120063
answer count: 3

http://stackoverflow.com/q/51118394
type: UnansweredQuestion
tagged with: python-3.7
linked to: http://stackoverflow.com/q/27885397
tagged with: lxml
has body: Today I installed python 3.7 on my windows 10 machine, and most things seem to be working, but when I try to run pip install lxml the install fails. Rather than finding an appropriate precompiled wheel, it appears to be downloading the source package, running setup.py bdist_wheel which in turn calls out to visual studio to try to build a C/C++ extension and that fails with: Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? I believe the real question is why it needs to do this recompile in the first place. If I setup a virtual environment with python 3.6.6 on the same machine, pip install lxml downloads and installs the precompiled wheel just fine. PyPI seems to have wheels for the lxml on 3.7 on windows, but maybe the platform names aren't matching properly or something. python -V -V on my machine returns: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
has answer: http://stackoverflow.com/a/51118443
favorite count: 0
type: Question
score: 5
tagged with: python
answer count: 1
has title: pip install lxml fails on python 3.7 on windows
upvote count: 5
downvote count: 0

http://stackoverflow.com/a/51058681
type: Answer
has body: I would say that in your circumstance it is necessary to scale back to true prices. This is not an absolute statement, but really depends on the setup of your problem: if you have a true price that is "1", then its log will be "0" and, whatever you predict for that single point, you'll get undefined / infinite MAPE. So I'd say yes, at least scale it back to exp before doing it. Also I don't understand the difference between "1" and "2": they seem identical to me, in "1" you're just taking the log of the price for the test set and then taking the exp again, in "2" you're just avoiding doing the two operations... As for "3", no, definitely they aren't independent on all transformations - in particular not log. MAPE is only independent to rescaling data by a constant factor, MAE by shifting it by a constant addend. On this point, beware that no measure gives a perfect truth and you might get very bad results just applying them. For example, using MAPE, if you have something with price of 1 cent and you're estimating it at 1$ you'll give it the same (huge) error as if it had price 1000$ and you're estimating it at 100k. On the other hand, since you're taking logs in training, that's basically the same rule you're using to train your model, so it might not be catastrophic. Just beware if you have true prices that are very close to, or worse exactly, 0. (MAE is probably worse in this case, because it will basically give all the weight to the few very expensive items in your database, but I can't say for sure from here)
answers question: http://stackoverflow.com/q/51057993
score: 0

http://stackoverflow.com/comment/89267889
type: AnswerComment
type: Comment
has text: @Blincer Your code, works good. I made a treeview where you can manually add values to rows and columns (like real table), and in that case the code does not work. It does not show any errors , it just dont work. Is there any way to send you the example of the code so that you can see whats the problem?
comment on: http://stackoverflow.com/a/51132649
score: 0

python-3.x
tags question: http://stackoverflow.com/q/51104597
tags question: http://stackoverflow.com/q/51163175
tags question: http://stackoverflow.com/q/51100078
tags question: http://stackoverflow.com/q/51088674
tags question: http://stackoverflow.com/q/51143196
tags question: http://stackoverflow.com/q/51036967
tags question: http://stackoverflow.com/q/51160546
tags question: http://stackoverflow.com/q/51113895
tags question: http://stackoverflow.com/q/51166018
tags question: http://stackoverflow.com/q/51062928
tags question: http://stackoverflow.com/q/51093056
tags question: http://stackoverflow.com/q/51112900
tags question: http://stackoverflow.com/q/51047091
tags question: http://stackoverflow.com/q/51156864
tags question: http://stackoverflow.com/q/51103811
tags question: http://stackoverflow.com/q/51070622
tags question: http://stackoverflow.com/q/51117357
tags question: http://stackoverflow.com/q/51110985
tags question: http://stackoverflow.com/q/51050622
tags question: http://stackoverflow.com/q/51116265
tags question: http://stackoverflow.com/q/51038842
tags question: http://stackoverflow.com/q/51061816
tags question: http://stackoverflow.com/q/51073392
tags question: http://stackoverflow.com/q/51159297
tags question: http://stackoverflow.com/q/51045011
tags question: http://stackoverflow.com/q/51068022
tags question: http://stackoverflow.com/q/51076123
tags question: http://stackoverflow.com/q/51154871
tags question: http://stackoverflow.com/q/51016470
tags question: http://stackoverflow.com/q/51162596
tags question: http://stackoverflow.com/q/51041731
tags question: http://stackoverflow.com/q/51086195
tags question: http://stackoverflow.com/q/51121170
tags question: http://stackoverflow.com/q/51092267
tags question: http://stackoverflow.com/q/51164713
tags question: http://stackoverflow.com/q/51091466
tags question: http://stackoverflow.com/q/51113216
tags question: http://stackoverflow.com/q/51163052
tags question: http://stackoverflow.com/q/51107514
tags question: http://stackoverflow.com/q/51145774
tags question: http://stackoverflow.com/q/51115044
tags question: http://stackoverflow.com/q/51140023
tags question: http://stackoverflow.com/q/51132716
tags question: http://stackoverflow.com/q/51019965
tags question: http://stackoverflow.com/q/51086227
tags question: http://stackoverflow.com/q/51079061
tags question: http://stackoverflow.com/q/51019303
tags question: http://stackoverflow.com/q/51026191
tags question: http://stackoverflow.com/q/51037001
tags question: http://stackoverflow.com/q/51107319
tags question: http://stackoverflow.com/q/51098509
tags question: http://stackoverflow.com/q/51138291
tags question: http://stackoverflow.com/q/51041094
tags question: http://stackoverflow.com/q/51137362
tags question: http://stackoverflow.com/q/51056176
tags question: http://stackoverflow.com/q/51028241
tags question: http://stackoverflow.com/q/51042113
tags question: http://stackoverflow.com/q/51025224
tags question: http://stackoverflow.com/q/51156970
tags question: http://stackoverflow.com/q/51163120
tags question: http://stackoverflow.com/q/51012209
tags question: http://stackoverflow.com/q/51047330
tags question: http://stackoverflow.com/q/51117681
tags question: http://stackoverflow.com/q/51166951
tags question: http://stackoverflow.com/q/51122552
tags question: http://stackoverflow.com/q/51162598
tags question: http://stackoverflow.com/q/51081102
tags question: http://stackoverflow.com/q/51128111
tags question: http://stackoverflow.com/q/51165856
tags question: http://stackoverflow.com/q/51013308
tags question: http://stackoverflow.com/q/51048626
tags question: http://stackoverflow.com/q/51018587
tags question: http://stackoverflow.com/q/51097419
tags question: http://stackoverflow.com/q/51095013
tags question: http://stackoverflow.com/q/51032135
tags question: http://stackoverflow.com/q/51108256
tags question: http://stackoverflow.com/q/51122337
tags question: http://stackoverflow.com/q/51074710
tags question: http://stackoverflow.com/q/51121583
tags question: http://stackoverflow.com/q/51156170

http://stackoverflow.com/a/51057319
has body: I am stuck on how to read the marks from the file then creating a new text file with the names, marks and class. fileList = list() with open("Maths_Marks", 'r') as fp: fp = fp.readlines() for line in fp: tmpLine = line.split(",") sname = tmpLine[0] fname = tmpLine [1] marks = tmpLine[2] #Write your own logic to get GroupNumber. #Append into line using #line = line.strip() + "," + GroupNumber #fileList.append(line.strip()) #Open new file Maths_Group and write into that with open("Maths_Group",'w') as s: for line in filelist: print &gt;&gt; s, line "line" will give you "Jack,Daniels,90" line = line.strip() + "," + GroupNumber => will give you Jack,Daniels,90,10M1 If you want to extract each field then use else leave below part. sname = tmpLine[0] fname = tmpLine[1] marks = tmpLine[2] I hope this helps.
type: Answer
has comment: http://stackoverflow.com/comment/89110692
has comment: http://stackoverflow.com/comment/89109741
has comment: http://stackoverflow.com/comment/89106598
has comment: http://stackoverflow.com/comment/89110278
has comment: http://stackoverflow.com/comment/89108129
has comment: http://stackoverflow.com/comment/89111980
has comment: http://stackoverflow.com/comment/89108699
answers question: http://stackoverflow.com/q/51056172
has comment: http://stackoverflow.com/comment/89117055
score: 0
has comment: http://stackoverflow.com/comment/89118027
has comment: http://stackoverflow.com/comment/89112539
has comment: http://stackoverflow.com/comment/89109023
has comment: http://stackoverflow.com/comment/89116718

http://stackoverflow.com/comment/89022932
comment on: http://stackoverflow.com/q/51013977
has text: have you tried running your code on the example `df` you provided? For one thing, `try` will fail without an `except`. But even when I remove `try`, I get an error with `iloc` after `groupby`: `AttributeError: Cannot access callable attribute 'iloc' of 'DataFrameGroupBy' objects, try using the 'apply' method`
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51078706
upvote count: 2
has answer: http://stackoverflow.com/a/51089161
accepted answer: http://stackoverflow.com/a/51089161
answer count: 1
tagged with: python-docx
favorite count: 0
score: 2
has title: how to remove bold words from python docx
downvote count: 0
tagged with: python
type: AnsweredQuestion
has body: I have a docx that I need to preprocess using spaCy. I need to remove all words that appear in bold in the document. I tried the following: def delete_paragraph(paragraph): p = paragraph._element p.getparent().remove(p) p._p = p._element = None length = len(document.paragraphs) for i in range(0,length): for j in range(0,len(document.paragraphs[i].runs)): if document.paragraphs[i].runs[j].bold == True: delete_paragraph(document.paragraphs[i]) length = length-1 continue document.save("/home/nikita/Desktop/Internship/new topic_mod/AXIS new.docx") But I get the following error: IndexError: Traceback (most recent call last) &lt;ipython-input-12-d144bd42e95e&gt; in &lt;module&gt;() 3 #print(document.paragraphs[i].text) 4 for j in range(0,len(document.paragraphs[i].runs)): ----&gt; 5 if document.paragraphs[i].runs[j].bold == True: 6 delete_paragraph(document.paragraphs[i]) 7 length = length-1 IndexError: list index out of range I cannot figure out why its out of range. How can I remove bold words from a python-docx ? Please help!
type: Question

http://stackoverflow.com/a/51094309
type: Answer
answers question: http://stackoverflow.com/q/51093821
score: 2
has body: The said error occurs when the sequence passed as the second argument of reduce is empty, which means bh is an empty sequence when the error occurs. Since bh is initialized with another sequence, hand, you need to find out why hand is empty in the first place.
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/89216242
score: 0
type: AnswerComment
has text: Thanks - that's a very elegant solution. Indeed this does point to the `PrintableEntry` object that I suspected (see comments on question). Since `PrintableEntry` is actually quite serializable, I should be able to solve this be adding an `elif type(obj) == PrintableEntry': return vars(obj)`.
type: Comment
comment on: http://stackoverflow.com/a/51114921

http://stackoverflow.com/comment/89047269
score: 0
type: QuestionComment
type: Comment
has text: I would assume that it's because this line evaluates to false. Does your debugger give you any hints? `if keys[pygame.K_s] and y<windowHeight-height-border:`
comment on: http://stackoverflow.com/q/51027434

http://stackoverflow.com/q/51056650
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51060261
type: UnansweredQuestion
has body: I was trYing to save session in model so that i can use it later on but i am getting an error everytime. My code is like: with tf.Session() as sess: sess.run(init) for j in range(3): for i in range(xtest.shape[0]): _, indices = sess.run(pred, feed_dict={x_train: xtrain, x_test: xtest[i,:]}) pred_label = getMajorityPredictions(ytrain, indices) actual_val = get_char( int( (ytest[i]).argmax() ) ) # print("test: ", i, "prediction: ", get_char(pred_label), " actual: ", actual_val) # print(pred_label, actual_val, type(pred_label), type(actual_val), sep=" --&gt; ") if get_char(pred_label) == actual_val: accuracy += 1/len(xtest) # print((i / (xtest.shape[0])) * 100) # os.system("cls") print("accuracy: ",accuracy) savedPath = saver.save(sess, "/tmp/model.ckpt") print("Model saved at: " ,savedPath) and the error is like: Traceback (most recent call last): File "prac3.py", line 74, in &lt;module&gt; saver = tf.train.Saver() File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1239, in __init__ self.build() File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1248, in build self._build(self._filename, build_save=True, build_restore=True) File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1272, in _build raise ValueError("No variables to save") ValueError: No variables to save
linked to: http://stackoverflow.com/q/38626435
tagged with: machine-learning
tagged with: python
tagged with: artificial-intelligence
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89103922
tagged with: tensorflow
type: Question
answer count: 2
has title: Error "no Variable to save" in tensorflow while storing session
has answer: http://stackoverflow.com/a/51056882
tagged with: deep-learning

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

http://stackoverflow.com/comment/89119617
comment on: http://stackoverflow.com/q/51064738
has text: @sacul The way to determine string1 and string2 go together is concatenating everything from the NaN down to where the first number is. Then especially restarting the concatenate.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/89221803
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51113280
has text: In that case you should be able to forget about the dictionary entirely. Just apply `@lru_cache(maxsize=None)` to `f` and use `f` everywhere you would use `A`. Also, you should mention people with @ so they get notified. You're just lucky I checked this post now and then.
score: 0

http://stackoverflow.com/a/51141360
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51141046
answers question: http://stackoverflow.com/q/51141046
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89267214
has comment: http://stackoverflow.com/comment/89267317
has body: There are a number of problems with this code: You need to store the results of those get calls. As suggested by Joel, you need to convert them to float or int. You should create the results Label once at startup, and config the text in this callback, instead of creating a new Label every time the user hits Submit. Instead of repeating all of the same code 6 times, just calculate a result in the elif chain, and then use it at the end. I already explained most of this in my answer to your previous question. The result should look something like this: result_label = Label(window, text = str(n_textentry ** m_textentry), bg = "white") result_label.grid(row = 13, column = 0, sticky = N) def click(): n = int(n_textentry.get()) m = int(m_textentry.get()) operation = int(operation_textentry.get()) if operation == 1: result = n+m elif operation == 2: result = n-m elif operation == 3: result = n*m elif operation == 4: result = n/m elif operation == 5: result = n**m else: result = "Invalid Operation" result_label.config(text=str(result)) As I mentioned before, you probably want some error handling for the case where the user leaves one of the entries blank, or inputs text instead of a number, or divides by zero, etc. The simplest way to do this with a try: around the whole click function: def click(): try: n = int(n_textentry.get()) # etc. except Exception as e: result_label.config(text=repr(e))
type: Answer
has comment: http://stackoverflow.com/comment/89267639
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89266928

http://stackoverflow.com/q/51133049
has comment: http://stackoverflow.com/comment/89250655
has body: I have an assignment to refactor one function. I don't seem to know what else can I do here, maybe extract some variable into function? def score(game): result = 0 frame = 1 in_first_half = True for i in range(len(game)): if game[i] == '/': result += 10 - last else: result += get_value(game[i]) if frame &lt; 10 and get_value(game[i]) == 10: if game[i] == '/': result += get_value(game[i+1]) elif game[i] == 'X' or game[i] == 'x': result += get_value(game[i+1]) if game[i+2] == '/': result += 10 - get_value(game[i+1]) else: result += get_value(game[i+2]) last = get_value(game[i]) if not in_first_half: frame += 1 if in_first_half is True: in_first_half = False else: in_first_half = True if game[i] == 'X' or game[i] == 'x': in_first_half = True frame += 1 return result
type: Question
upvote count: 0
score: -2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51133192
has comment: http://stackoverflow.com/comment/89250618
type: UnansweredQuestion
downvote count: 2
has title: Refactoring suggestion
tagged with: python

http://stackoverflow.com/comment/89056979
has text: Thank you! The duplicated indices were the ones causing the problem!
comment on: http://stackoverflow.com/a/51030612
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89263735
has text: There are different methods.
comment on: http://stackoverflow.com/q/51139635
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51108601
upvote count: 1
has body: This type of recurrence relation is linear and homogeneous. Linear homogeneous recurrence relations are a special class of recurrence relations that are relatively easy to solve (at least by hand). However, not all recurrence relations have closed forms, and among those that do, not all belong to a special class that computers can solve routinely. Python does not have a built-in recurrence relation solver, and no module can be written in Python that can solve an arbitrary recurrence relation.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51105876

http://stackoverflow.com/a/51078835
answers question: http://stackoverflow.com/q/51076717
has comment: http://stackoverflow.com/comment/89155008
has comment: http://stackoverflow.com/comment/89162057
type: Answer
has comment: http://stackoverflow.com/comment/89162010
has comment: http://stackoverflow.com/comment/89148176
has comment: http://stackoverflow.com/comment/89154377
has comment: http://stackoverflow.com/comment/89154308
has comment: http://stackoverflow.com/comment/89154149
has comment: http://stackoverflow.com/comment/89149156
has comment: http://stackoverflow.com/comment/89148929
has comment: http://stackoverflow.com/comment/89148963
has comment: http://stackoverflow.com/comment/89148511
score: 0
has comment: http://stackoverflow.com/comment/89154116
has body: I guess you are making mistake while extracting filename. Mistakes you are making: - Variable Name. **pdfFileobject** = open(filename, 'rb') pdfUnderstander = PyPDF2.PdfFileReader(**pdfFileObject**) Try this code: path = r'Dir contains PDFs' for filename in os.listdir(path): if filename.split(".")[-1] == 'pdf': print(filename) pdfFileObject = open(os.path.join(path, filename), 'rb') pdfUnderstander = PyPDF2.PdfFileReader(pdfFileObject) numberpages = pdfUnderstander.getNumPages() increment = 0 text = "" while increment &lt; numberpages: pdfPage = pdfUnderstander.getPage(increment) increment += 1 text += pdfPage.extractText() print(text)

http://stackoverflow.com/q/51155396
tagged with: swarmplot
upvote count: 2
tagged with: seaborn
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63171175
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/63171175
answer count: 2
downvote count: 0
favorite count: 0
has body: I have: import numpy as np import pandas as pd import seaborn as sb import matplotlib.pyplot as plt # Generate random data set1 = np.random.randint(0, 40, 24) set2 = np.random.randint(0, 100, 24) # Put into dataframe and plot df = pd.DataFrame({'set1': set1, 'set2': set2}) data = pd.melt(df) sb.swarmplot(data=data, x='variable', y='value') The two random distributions plotted with seaborn's swarmplot function: I want the individual plots of both distributions to be connected with a colored line such that the first data point of set 1 in the dataframe is connected with the first data point of set 2. I realize that this would probably be relatively simple without seaborn but I want to keep the feature that the individual data points do not overlap. Is there any way to access the individual plot coordinates in the seaborn swarmfunction?
has title: Plotting colored lines connecting individual data points of two swarmplots
tagged with: python
possible better answer: http://stackoverflow.com/a/51157346
score: 2
has answer: http://stackoverflow.com/a/51157346

http://stackoverflow.com/comment/89993653
has text: I am seeing the same issue attempting to use paramiko under OS X 10.6.8. ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/nacl/_sodium.abi3.so, 2): Symbol not found: _memset_s. Where did you get your python from? Perhaps Python should have been built with "-no_weak_imports linker flag" see https://github.com/Homebrew/homebrew-core/issues/3727
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51049779

http://stackoverflow.com/q/51079660
tagged with: loops
type: Question
tagged with: arrays
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89149035
accepted answer: http://stackoverflow.com/a/51080315
favorite count: 0
has title: How does one iterate through an np.zeros array in python, printing the columns one by one?
has answer: http://stackoverflow.com/a/51080315
tagged with: python
type: AnsweredQuestion
has body: I have an np.zeros array that has been appended in another loop that now looks like, array([[ 0., 0.], [ 4., 4.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 3., 3.], [ 0., 3.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.]]) How can I create a loop that prints the first column, and then the next column? I tried the following code, for i in goalsfor[:,i]: print(goalsfor) but the following error occurs. IndexError: index 19 is out of bounds for axis 1 with size 2 Also, is it possible to append an np.zero array by column? Thank you!

http://stackoverflow.com/comment/89166395
comment on: http://stackoverflow.com/q/51085083
score: 0
type: Comment
type: QuestionComment
has text: That said, additional to the immediate issue this question is about, you have at least two additional potentially security-impacting bugs. The first of those is shell injection: Use `shlex.quote()` in Python 3 or `pipes.quote()` in Python 2 to get strings that are safe to substitute into `ssh.exec_command()`; otherwise, someone asking this program to retrieve files from `/tmp/$(rm -rf ~)` could cause you to have a really bad day.

http://stackoverflow.com/comment/89030577
comment on: http://stackoverflow.com/a/51018703
score: 0
type: AnswerComment
type: Comment
has text: The result is totally correct but I can't make it work.

http://stackoverflow.com/comment/89052555
comment on: http://stackoverflow.com/q/51028310
type: Comment
type: QuestionComment
has text: Increasing the timeout value wouldn't stop the function from being called multiple times. The question is, is the function really being called multiple times (which can only be solved by looking at whatever is calling it) or is the function erroring out somehow and being retried (which can only be fixed by looking at the error in the logs and then proceeding to fix the actual error/issue). Right now you are basically just trying random things in the hope something fixes it.
score: 0

http://stackoverflow.com/a/51076484
has body: The map method returns a generator which allows to iterate through the results once ready. Unfortunately, it is not possible to resume a generator after an exception occurs. From PEP 255. If an unhandled exception-- including, but not limited to, StopIteration --is raised by, or passes through, a generator function, then the exception is passed on to the caller in the usual way, and subsequent attempts to resume the generator function raise StopIteration. In other words, an unhandled exception terminates a generator's useful life. There are other libraries such as pebble which allow to continue the iteration after an error occurs. Check the examples in the documentation.
has comment: http://stackoverflow.com/comment/89169723
has comment: http://stackoverflow.com/comment/113424313
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89156238
accepted answer of: http://stackoverflow.com/q/51071378
answers question: http://stackoverflow.com/q/51071378
type: Answer
has comment: http://stackoverflow.com/comment/89156019
upvote count: 9
has comment: http://stackoverflow.com/comment/89155695

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

http://stackoverflow.com/a/51088899
type: Answer
has body: This happens because model.compile uses CPU or GPU depending on whether GPU is available in the machine. Looks like it does not check if a GPU version of MXNet is installed. You can force model.compile to use CPU by explicitly specifying the context. Example: model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'], context=["cpu()"])
score: 1
accepted answer of: http://stackoverflow.com/q/51074755
answers question: http://stackoverflow.com/q/51074755
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89237430
type: Comment
comment on: http://stackoverflow.com/q/51126087
type: QuestionComment
has text: @Aran-Fey As you have edited the question. Can you please reopen it as it is the mixture of two or more questions. It is not duplicate.
score: 0

http://stackoverflow.com/q/51089531
tagged with: python-3.x
has title: Read CSV file with features and labels in the same row in Tensorflow
has answer: http://stackoverflow.com/a/51107924
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51096212
answer count: 2
tagged with: pandas
has body: I have a .csv file with around 5000 rows and 3757 columns. The first 3751 columns of each row are the features and the last 6 columns are the labels. Each row is a set of features-labels pair. I'd like to know if there are built-in functions or any fast ways that I can: Parse the first 3751 columns as features (these columns doesn't have headers) Parse ANY of the last 6 columns as labels, which means that I'd like to take any of the last 6 columns out as a label for training. Basically I want to train a DNN model with 3751 features and 1 label and I'd like the output of the parsing function be fed into the following function for training: train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(training_set.data)}, y=np.array(training_set.target), num_epochs=None, shuffle=True) I know some functions like "tf.contrib.learn.datasets.base.load_csv_without_header" can do similar things but it is already deprecated.
favorite count: 0

http://stackoverflow.com/comment/89202875
type: QuestionComment
has text: another issue I am seeing is any opertion on driver object post redirection throws `[Errno 61] Connection refused`
comment on: http://stackoverflow.com/q/51107309
score: 0
type: Comment

http://stackoverflow.com/comment/89178529
score: 0
type: Comment
has text: @Pratap Then your regular expression may be incorrect... This will be the output of the whole: Two _identical_ lines before a keyword followed by _another two_ identical lines, e.g. `"abcdef\nabcdef\nKEY\nghijk\nghijk\n"`... if and only if `keyword = "KEY\n"`
type: AnswerComment
comment on: http://stackoverflow.com/a/51082280

http://stackoverflow.com/comment/89061632
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51034824
type: AnswerComment
has text: I appreciate the response! That is exactly the thought I had too, but I'm not able to get the form to bind with this approach. I'll add some more details about my `Form` and the binding logic in the question, would be great if you could provide some feedback.

http://stackoverflow.com/q/51116523
has comment: http://stackoverflow.com/comment/89219661
has comment: http://stackoverflow.com/comment/89221545
answer count: 1
has body: I have writting a .csv dataset from some data being picked from the internet but within this new dataset I have a column with date of some clients were contacted and I would like to while I am writing this new dataset in .csv, I instruct python to sort ascending all cases according to date column, so that when I do Scatter Plot automatically the line chart follow the number of cases per day in ascending order of date. Please, note the missing values, they must come as they are with empty fields so that afterwards I can deal with them filling or removing. Thanks. My code is as follow: with open('demo.csv', "w") as myfile: print(mydata.decode('utf-8'),file=myfile) date enrolled 6/29/2018 1 6/29/2018 1 6/29/2018 6/29/2018 1 6/20/2018 1 6/22/2018 1 6/19/2018 1 6/27/2018 1 6/28/2018 6/27/2018 1 6/19/2018 1 6/20/2018 1 6/27/2018 1 6/27/2018 6/26/2018 1 6/27/2018 6/27/2018 1
linked to: http://stackoverflow.com/q/30040371
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51116764
tagged with: python
has title: Python/Dash by Plotly: How to write a csv including parameter to sort all dates in a column of that dataset being written?
has comment: http://stackoverflow.com/comment/89219367
has comment: http://stackoverflow.com/comment/89219219
type: Question
has comment: http://stackoverflow.com/comment/89219634
linked to: http://stackoverflow.com/q/9917865
score: 0
has comment: http://stackoverflow.com/comment/89219953

http://stackoverflow.com/a/51098297
has comment: http://stackoverflow.com/comment/89310819
has comment: http://stackoverflow.com/comment/89250296
downvote count: 0
answers question: http://stackoverflow.com/q/51094924
type: Answer
has comment: http://stackoverflow.com/comment/89322216
has comment: http://stackoverflow.com/comment/89240760
upvote count: 1
has comment: http://stackoverflow.com/comment/89324677
has comment: http://stackoverflow.com/comment/89275044
score: 1
has body: I'm not entirely sure I interpreted the question correctly... import pandas as pd import matplotlib.pyplot as plt import seaborn as sns d = ({ 'A' : ['1','1','1','2','2','2','3','3','3','3'], 'B' : ['A','B','C','A','B','C','D','A','B','C'], 'C' : ['John','Carl','Carl','John','Lily','John','Lily','John','Carl','Carl'], }) df = pd.DataFrame(data=d) fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(13,5)) sns.countplot(x = df.C, ax = ax1) sns.countplot(x = df.B, ax = ax2) sns.countplot(x = df.C, hue =df.B, ax = ax3)

http://stackoverflow.com/a/51033657
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51033514
type: Answer
has body: [Note: if this is a one-off, then I suggest using Carcigenicate's answer] This is a great use for generators and the yield statement. The following function will accept your iterator, and yield pairs as a 2-tuple which can be used however you need. Generator Function: def lineandlast(listish, first=True, last=True): iterator = iter(listish) lastline = next(iterator) if first: yield lastline, None for line in iterator: yield line, lastline lastline = line if last: yield None, lastline Example: for line, last in lineandlast([1,2,3,4,5]): print(line, last) Output: 1 None 2 1 3 2 4 3 5 4 None 5 Notes: There are two keyword arguments, first and last, which can be used to control the output of the first and last items on the output example above.
upvote count: 1

http://stackoverflow.com/q/51034680
type: Question
upvote count: 2
tagged with: apache-spark-sql
linked to: http://stackoverflow.com/q/46758768
has comment: http://stackoverflow.com/comment/89079155
has title: how to convert dataframe toBlockMatrix in pyspark
has comment: http://stackoverflow.com/comment/89077390
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 2
tagged with: pyspark
has comment: http://stackoverflow.com/comment/99463323
has body: I am trying to calculate similarity matrix of users by their metadata. Following this question I found TF-IDF vector of data. After that I normalized It. The result is given below data.select('norm').take(10) this is result However when I tried to get blockMatrix from dataframe by this code mat = IndexedRowMatrix( data.select("memberid", "norm").rdd.map(lambda row: IndexedRow(row.memberid, row.norm.toArray()))).toBlockMatrix() I got following error --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-123-32e41e450739&gt; in &lt;module&gt;() 1 from pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix 2 mat = IndexedRowMatrix( ----&gt; 3 data.select("memberid", "norm").rdd.map(lambda row: IndexedRow(row.memberid, row.norm.toArray()))).toBlockMatrix() ~/spark/python/pyspark/mllib/linalg/distributed.py in __init__(self, rows, numRows, numCols) 374 # both be easily serialized. We will convert back to 375 # IndexedRows on the Scala side. --&gt; 376 java_matrix = callMLlibFunc("createIndexedRowMatrix", rows.toDF(), 377 long(numRows), int(numCols)) 378 elif (isinstance(rows, JavaObject) ~/spark/python/pyspark/sql/session.py in toDF(self, schema, sampleRatio) 55 [Row(name=u'Alice', age=1)] 56 """ ---&gt; 57 return sparkSession.createDataFrame(self, schema, sampleRatio) 58 59 RDD.toDF = toDF ~/spark/python/pyspark/sql/session.py in createDataFrame(self, data, schema, samplingRatio, verifySchema) 520 521 if isinstance(data, RDD): --&gt; 522 rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio) 523 else: 524 rdd, schema = self._createFromLocal(map(prepare, data), schema) ~/spark/python/pyspark/sql/session.py in _createFromRDD(self, rdd, schema, samplingRatio) 358 """ 359 if schema is None or isinstance(schema, (list, tuple)): --&gt; 360 struct = self._inferSchema(rdd, samplingRatio) 361 converter = _create_converter(struct) 362 rdd = rdd.map(converter) …

http://stackoverflow.com/q/51050315
has answer: http://stackoverflow.com/a/51051980
type: Question
upvote count: 15
possible better answer: http://stackoverflow.com/a/51051670
linked to: http://stackoverflow.com/q/55645527
has answer: http://stackoverflow.com/a/51051670
has body: Suppose there is a library that makes various database queries: import time def queryFoo(): time.sleep(4) return "foo" def queryBar(): time.sleep(4) return "bar" I want to execute those 2 queries concurrently without having to add async to the method signature or adding a decorator. These functions should not depend on asyncio at all. What is the best way to utilize those non-async functions within asyncio? I am looking for something of the form: #I need an 'asyncWrapper' results = asyncio.gather(asyncWrapper(queryFoo()), asyncWrapper(queryBar())) Thank you in advance for your consideration and response.
accepted answer: http://stackoverflow.com/a/51051980
has title: Using asyncio for Non-async Functions in Python?
answer count: 2
tagged with: python-asyncio
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 15

http://stackoverflow.com/q/51019860
tagged with: python
type: AnsweredQuestion
has body: After upgrading pip, I try to do a 'pip freeze', but i've this error : # pip install --upgrade pip Collecting pip Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB) 100% |################################| 1.3MB 737kB/s Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Successfully uninstalled pip-9.0.1 Successfully installed pip-10.0.1 # pip freeze Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/usr/local/lib/python2.7/dist-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/usr/local/lib/python2.7/dist-packages/pip/_internal/index.py", line 15, in &lt;module&gt; from pip._vendor import html5lib, requests, six File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/__init__.py", line 86, in &lt;module&gt; from pip._vendor.urllib3.contrib import pyopenssl File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/urllib3/contrib/pyopenssl.py", line 46, in &lt;module&gt; import OpenSSL.SSL File "/usr/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 105, in &lt;module&gt; SSL_ST_INIT = _lib.SSL_ST_INIT AttributeError: 'module' object has no attribute 'SSL_ST_INIT' Reading some post here, I found various solutions, but it's not working. So I try another things, like installing using easy_install : # sudo python -m easy_install --upgrade pyOpenSSL Searching for pyOpenSSL Reading https://pypi.python.org/simple/pyOpenSSL/ Best match: pyOpenSSL 18.0.0 Downloading https://files.pythonhosted.org/packages/9b/7c/ee600b2a9304d260…
linked to: http://stackoverflow.com/q/45188413
upvote count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/51022582
tagged with: pyopenssl
type: Question
accepted answer: http://stackoverflow.com/a/51022582
has title: Error with pip after upgrading : 'module' object has no attribute 'SSL_ST_INIT'
answer count: 2
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51020263
has answer: http://stackoverflow.com/a/51020263

http://stackoverflow.com/q/51147291
type: Question
upvote count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89280837
has body: I'm using postgresql in Django and also I have an ArrayField in one of my models like follows : words = ArrayField( models.CharField(max_length=255, blank=True), null=True, blank=True ) In my code I have queries on this field only for null values. It means I have only following queries on this field : Entity.objects.filter(words__isnull=True).all() Entity.objects.filter(words__isnull=False).all() Unfortunately table of Entity is large and this query takes long hours to answer. What is best index for this field based on my queries?
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89280226
has title: index for ArrayField in postgresql(django)
has comment: http://stackoverflow.com/comment/89280214
tagged with: python
has comment: http://stackoverflow.com/comment/89279431
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89282550
tagged with: indexing
score: 1
has comment: http://stackoverflow.com/comment/89278773

http://stackoverflow.com/comment/126199604
type: AnswerComment
has text: I believe this is the best approach as well
score: 0
type: Comment
comment on: http://stackoverflow.com/a/68572278

http://stackoverflow.com/comment/89051842
type: Comment
comment on: http://stackoverflow.com/a/51029329
score: 0
type: AnswerComment
has text: See edit to my answer. It now sums `df['P']` and `df['V_comb']` when the conditions are met and sets that as the new value of `df['V_comb']`, which is the same as adding `df['P']` to the original value of `df['V_comb']` when the conditions are met.

http://stackoverflow.com/q/51123730
has title: Python reading audio from sound card
has answer: http://stackoverflow.com/a/51126882
score: -1
tagged with: python
downvote count: 1
tagged with: audio
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51126882
type: Question
upvote count: 0
answer count: 1
has body: I have a project. What I want to do is that I want to read audio data from soundcard without saving it but the main important thing is that the audio data that the python is reading I want to check if some certain audio is played
tagged with: soundcard
favorite count: 0

http://stackoverflow.com/q/51097072
answer count: 1
has comment: http://stackoverflow.com/comment/89199741
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51097557
has comment: http://stackoverflow.com/comment/89192512
tagged with: python
type: Question
tagged with: discord.py
has body: I currently am running two separate python scripts, one for a Flask webapp and the other for a discord.py bot. Upon receiving an incoming request on the flask webapp, I would like to call a function in the discord.py script and return the its output to the view. Currently both scripts are blocking so I am interested in using a redis messaging queue to pass requests between each other (something like the kombu package). webapp.py: from flask import Flask app = Flask(__name__) @app.route("/") def index(): user = get_user(123456789) # get_user function from bot.py return "Hello, {0}".format(user.name) if __name__ == "__main__": app.run() bot.py: import discord client = discord.Client() async def get_user(user_id): user = await client.get_user_info(user_id) return user if __name__ == "__main__": client.run("bot token") I am not sure how to accomplish this task or if Kombu is really the way to go. How would I implement to my flask webapp so that I can call functions within my discord.py bot?
tagged with: flask
has comment: http://stackoverflow.com/comment/89198591
score: 0
tagged with: message-queue
has comment: http://stackoverflow.com/comment/89204870
has title: How would I get the output of a function from a different running python script?

http://stackoverflow.com/comment/89097961
has text: You can use the pandas API for regex like you were doing before. I'm just showing an example with pure python.
comment on: http://stackoverflow.com/a/51053408
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89303860
type: Comment
has text: Thanks @Druta Ruslan for your solution. It worked finally. I didn't know this information concerning `scrapy.cfg`. However, can you suggest me how can I run the same from sublime text editor using `.CrawlerProcess()` as I've shown above? Can I move `scrapy.cfg` into either of the folder within my project? Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51159576

http://stackoverflow.com/comment/89312991
type: Comment
has text: It's not exactly like that, I need an algorithm that scans all possible nodes - so for instance it could output [A,27,0.12,0.21....] and [A,27,0.12,0.202.....] depending on if those two lists satisfy a condition. I'm not very good at explaining it as I only started coding 2 weeks ago, but this diagram indicates what I'm looking for: https://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Depth-first-tree.svg/300px-Depth-first-tree.svg.png Thanks a lot anyways, I really appreciate the help :)
comment on: http://stackoverflow.com/a/51164825
type: AnswerComment
score: 0

http://stackoverflow.com/a/51015267
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51012689
has comment: http://stackoverflow.com/comment/89026778
has comment: http://stackoverflow.com/comment/89050658
type: Answer
has body: The answer depends on which version of MkDocs you are using. In #1376 the path was added to the config object as the attribute config.config_file_path. However, that won't be available until the next release (1.0). Regardless, earlier versions include an undocumented config option config['config_file_path'] which holds the location of the file. Be careful however, as any undocumented features are subject to change without notice. As for the location of the Markdown file, that is available in various attributes of the page object passed to the plugin event. You have your pick of page.input_path, page.output_path, page.abs_input_path, and page.abs_output_path. Again, these are undocumented and subject to change in a future release without notice. In fact, #1504 proposes changing them to page.file.src_path, page.file.dest_path, page.file.abs_src_path, and page.file.abs_dest_path for the 1.0 release. But that's the risk in working against pre-1.0 software. Things change as the developers try to get it right. The good news is that the 1.0 release will lock these things down going forward. Full disclosure: I am a member of the MkDocs development team.
answers question: http://stackoverflow.com/q/51012689

http://stackoverflow.com/a/51125048
type: Answer
has body: I think you need to change the boolean mask to df.eq(0) which is the same as df == 0 with changed condition from &lt;= to &lt;: max_number_of_zeros = 2 df = df.loc[:,df.eq(0).sum(axis=0) &lt; max_number_of_zeros] print (df) 0 2 0 1 0 1 2 1 2 0 3 3 1 1 Detail: print (df.eq(0)) 0 1 2 3 0 False True True True 1 False True False True 2 True False False False 3 False False False False print (df.eq(0).sum(axis=0)) 0 1 1 2 2 1 3 2 dtype: int64 EDIT: max_number_of_zeros = 2 df = df.loc[:,len(df.columns) - df.astype(bool).sum(axis=0) &lt; max_number_of_zeros] print (df) 0 2 0 1 0 1 2 1 2 0 3 3 1 1
accepted answer of: http://stackoverflow.com/q/51125029
answers question: http://stackoverflow.com/q/51125029
upvote count: 1
has comment: http://stackoverflow.com/comment/89235141
has comment: http://stackoverflow.com/comment/89236639
score: 1
has comment: http://stackoverflow.com/comment/89235169
has comment: http://stackoverflow.com/comment/89235648
has comment: http://stackoverflow.com/comment/89236376
has comment: http://stackoverflow.com/comment/89235320
has comment: http://stackoverflow.com/comment/89235068
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89236473
has comment: http://stackoverflow.com/comment/89235095
has comment: http://stackoverflow.com/comment/89235418

http://stackoverflow.com/a/51066195
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51065490
type: AcceptedAnswer
downvote count: 0
has body: The issue is the Imputer doesn't return a pd.DataFrame as an output of transform(), thus, your column names get lost, when you do train_X = my_imputer.fit_transform(train_X) test_X = my_imputer.transform(test_X) Simple solution, wrap the imputer output into a dataframe, for example like this: train_X = pd.DataFrame(my_imputer.fit_transform(train_X), columns=train_X.columns) test_X = pd.DataFrame(my_imputer.transform(test_X), columns=test_X.columns)
answers question: http://stackoverflow.com/q/51065490

http://stackoverflow.com/q/51068619
has comment: http://stackoverflow.com/comment/89127187
possible better answer: http://stackoverflow.com/a/72177205
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Accessing Nested Dict from JSON
has answer: http://stackoverflow.com/a/51068727
accepted answer: http://stackoverflow.com/a/51068727
score: -3
downvote count: 3
tagged with: python-requests
type: Question
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/72177205
has body: I'm using requests and JSON to pull some data from an API, and I'm struggling with using a nested dict. Here is the JSON data: {"data": [ { "ContactId": "123", "EmailAddress": "abc@xyz.com", "FirstName": null, "LastName": null, "ClickDate": "6/6/1966", "Clicks": "5", "IPAddress": "1.1.1.1.1", "UserAgent": "IE8.0", "UniqueLinksClicked": [ { "LinkURL": "http://link1.com", "LinkURL": "http://link2.com", "LinkURL": "http://link3.com" } ] } ]} I'm able to access all of the ContactID and other 1st level stuff fine, but I can't figure out how to traverse the "LinkURL" stuff. Here is my python... result = requests.get(requesturl, headers=headers) jdata = json.loads(result.content) for result in jdata["data"]: contactID = str([(result["ContactId"])]) for result in jdata["data"]["UniqueLinksClicked"]: #I'm doing this wrong, but I'm not sure how. print(ContactID + " " + str([(result["LinkURL"])])) The line marked with a comment above generates a TypeError indicating it's a list, where I expected it to be a dict: list indices must be integers or slices, not str If instead I drop the ["data"] dereference and try to access "UniqueLinksClicked" on jdata: for link in jdata["UniqueLinksClicked"]: I get a key error because the ["UniqueLinksClicked"] is an item inside of the ["data"] dict. How do I do this correctly?
answer count: 2
favorite count: 0

spyder
tags question: http://stackoverflow.com/q/51017845
tag name: spyder
tags question: http://stackoverflow.com/q/51125462
tags question: http://stackoverflow.com/q/51034574
tags question: http://stackoverflow.com/q/51139232
tags question: http://stackoverflow.com/q/51089235
tags question: http://stackoverflow.com/q/51157776
tags question: http://stackoverflow.com/q/51029516
tags question: http://stackoverflow.com/q/51130933
tags question: http://stackoverflow.com/q/51079183
tags question: http://stackoverflow.com/q/51057351
type: Tag
tags question: http://stackoverflow.com/q/51046752
tags question: http://stackoverflow.com/q/51142349
tags question: http://stackoverflow.com/q/51084214
tags question: http://stackoverflow.com/q/51111216
tags question: http://stackoverflow.com/q/51104597
tags question: http://stackoverflow.com/q/51112574
tags question: http://stackoverflow.com/q/51077327
tags question: http://stackoverflow.com/q/51097717
tags question: http://stackoverflow.com/q/51130546
tags question: http://stackoverflow.com/q/51069435
tags question: http://stackoverflow.com/q/51160403

http://stackoverflow.com/comment/89120762
has text: yes it contains a list, and the navigate url is in cells[3], i uploaded a more detail html image
comment on: http://stackoverflow.com/a/51051567
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51079412
has title: Get common values within multiple groupby in pandas Dataframe
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: dataframe
type: Question
upvote count: 2
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51080608
favorite count: 0
has body: I am new to Pandas dataframe and I would like to find common values of 'col2' within multiple groups grouped by 'col1' col1 col2 a abc pqr xyz b abc def bcd c bcd efg The output should be as follows: abc [a,b] bcd [b,c] Can anyone help me with the solution? Thanks.

http://stackoverflow.com/a/51144278
type: Answer
has comment: http://stackoverflow.com/comment/97850520
score: 21
has comment: http://stackoverflow.com/comment/96856520
has body: You need to create a symbolic Keras function, taking the input/output as inputs and returning the gradients. Here is a working example : import numpy as np import keras from keras import backend as K model = keras.Sequential() model.add(keras.layers.Dense(20, input_shape = (10, ))) model.add(keras.layers.Dense(5)) model.compile('adam', 'mse') dummy_in = np.ones((4, 10)) dummy_out = np.ones((4, 5)) dummy_loss = model.train_on_batch(dummy_in, dummy_out) def get_weight_grad(model, inputs, outputs): """ Gets gradient of model for given inputs and outputs for all weights""" grads = model.optimizer.get_gradients(model.total_loss, model.trainable_weights) symb_inputs = (model._feed_inputs + model._feed_targets + model._feed_sample_weights) f = K.function(symb_inputs, grads) x, y, sample_weight = model._standardize_user_data(inputs, outputs) output_grad = f(x + y + sample_weight) return output_grad def get_layer_output_grad(model, inputs, outputs, layer=-1): """ Gets gradient a layer output for given inputs and outputs""" grads = model.optimizer.get_gradients(model.total_loss, model.layers[layer].output) symb_inputs = (model._feed_inputs + model._feed_targets + model._feed_sample_weights) f = K.function(symb_inputs, grads) x, y, sample_weight = model._standardize_user_data(inputs, outputs) output_grad = f(x + y + sample_weight) return output_grad weight_grads = get_weight_grad(model, dummy_in, dummy_out) output_grad = get_layer_output_grad(model, dummy_in, dummy_out) The first function I wrote returns all the gradients in the model but it wouldn't be difficult to extend it so it supports layer indexing. However, it's probably dangerous because any layer without weights in the model will be ignored by this indexing and you would end up with different layer indexing in the model and the gradients. The second function I wrote returns the gradient at a given layer's output and there, the indexing is the same as in the model, so it's safe to use it. Note : This works with Keras …
upvote count: 21
has comment: http://stackoverflow.com/comment/96820802
has comment: http://stackoverflow.com/comment/97176190
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/118512592
answers question: http://stackoverflow.com/q/51140950
accepted answer of: http://stackoverflow.com/q/51140950
has comment: http://stackoverflow.com/comment/100683007

http://stackoverflow.com/comment/89064115
comment on: http://stackoverflow.com/q/51035747
type: QuestionComment
type: Comment
has text: great , I also made it. I catched True. But Why can't I view the original Image... ? I should reedit my question.
score: 0

http://stackoverflow.com/q/51072268
type: Question
has answer: http://stackoverflow.com/a/51072339
has comment: http://stackoverflow.com/comment/89134342
has body: Im trying to count the amount of words in a text document then write the total back to the .txt here is how far i've got words = 0 f = open("count.txt", 'r+') for wordcount in f.readline().split(" "): words += 1 print('number of words ') print(words) f.write("number of words ") f.write(words) f.close() I get this error TypeError: expected a character buffer object Where am I going wrong? i feel that f.write(words) isn't the correct way to write the total to the txt?
score: 0
tagged with: micropython
accepted answer: http://stackoverflow.com/a/51072339
has answer: http://stackoverflow.com/a/51072466
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51072529
tagged with: python
possible better answer: http://stackoverflow.com/a/51072329
answer count: 4
has answer: http://stackoverflow.com/a/51072329
type: AnsweredQuestion
has title: count words in a .txt then write the results in the same .txt
has comment: http://stackoverflow.com/comment/89257020
has comment: http://stackoverflow.com/comment/89134283

http://stackoverflow.com/a/51159568
has comment: http://stackoverflow.com/comment/89307749
has comment: http://stackoverflow.com/comment/89315885
has comment: http://stackoverflow.com/comment/89332443
has body: You could just keep checking each future in the sequence till you find one that is done. from collections import deque pool = concurrent.futures.ThreadPoolExecutor(max_workers = 4) futures = deque(pool.submit(g,i) for i in range (4)) j = 4 result = False while not result: while not futures[0].done(): futures.rotate() future = futures.popleft() result = future.result() if not result: j += 1 futures.append(pool.submit(g,j)) Here is a similar solution using concurrent.futures.wait. First a callable for testing purposes: import random class F: def __init__(self, threshold=.03): self._bool = random.random() &lt; threshold def __call__(self, n): self.n = n time.sleep(random.random()) return self def __bool__(self): return self._bool def __str__(self): return f'I am number {self.n}' def __repr__(self): return f'I am number {self.n}' Solution pool = concurrent.futures.ThreadPoolExecutor(max_workers = 4) j = 4 futures = [pool.submit(F(),i) for i in range(j)] result = False while not result: #print(f'there are {len(futures)} futures') maybe_futures = concurrent.futures.wait(futures, return_when='FIRST_COMPLETED') futures = maybe_futures.not_done # more than one may have completed(?) for future in maybe_futures.done: temp = future.result() if not temp: j += 1 futures.add(pool.submit(F(),j)) else: result = temp break Another solution using a callback (uses the callable above): not sure what happens if a future completes before the callback gets added. completed_futures = collections.deque() result = False def callback(future, completed=completed_futures): completed.append(future) j = 4 with concurrent.futures.ThreadPoolExecutor(max_workers = 4) as pool: #initial tasks for i in range(j): future = pool.submit(F(),i) future.add_done_callback(callback) while not result: # is this the same as - while True: ? while not completed_futures: pass while completed_futures: future = completed_futures.popleft() result = future.result() if result: break j += 1 future = pool.submit(F(),j) futu…
answers question: http://stackoverflow.com/q/51159341
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51159341
score: 0
has comment: http://stackoverflow.com/comment/89319076
type: Answer

http://stackoverflow.com/comment/89061159
type: Comment
type: QuestionComment
score: 1
has text: For quick resolution, Share the code with sample data containing the issue? If possible the complete code!!
comment on: http://stackoverflow.com/q/51024643

http://stackoverflow.com/q/51158664
has comment: http://stackoverflow.com/comment/89300877
has body: Currently I am using my dataframe with a datetime field to generate a monthly return series over different tickers. return_series=data.groupby([data['Date'].dt.year,data['Date'].dt.month]).apply(monthly_returns) The current output looks something like this, where the tuple values are pnl,capital and return. Date Date 2008 6 (-742.58, 150001.16, -0.495049504951) 7 (123142.08, 299304.14, 41.1427920777) 8 (-5963.05, 426217.67, -1.39906212711) 9 (-137316.34, 868529.72, -15.8102062414) 10 (4503.44, 685906.3, 0.656567814) I would like to separate out the tuple to three columns (Capital,PnL,Returns) and change the Dates columns to show Year,Month. The monthly return function aggregates over symbols for a given month def monthly_returns(df_monthly): symbols_pnl=df_monthly.groupby(df_monthly['Symbol']).apply(symbol_return) symbols_invested_capital=df_monthly.groupby(df_monthly['Symbol']).apply(symbol_capital) return(sum(symbols_pnl),sum(symbols_invested_capital),sum(symbols_pnl)/sum(symbols_invested_capital)*100) The input data daily position values Date Symbol Position Prev Position Price Exec Price 6/24/2008 ABC 100 0 5 4.85 6/25/2008 EFG 200 150 10 9.8
score: 0
has answer: http://stackoverflow.com/a/51158861
type: Question
answer count: 1
tagged with: pandas
has comment: http://stackoverflow.com/comment/89301028
has title: Convert double groupby object into dataframe
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51041998
favorite count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/64571037
has answer: http://stackoverflow.com/a/52316458
score: 1
has answer: http://stackoverflow.com/a/68474396
downvote count: 0
has title: ModuleNotFoundError: No module named 'facebook'
has comment: http://stackoverflow.com/comment/111689450
answer count: 3
tagged with: facebook
tagged with: python
tagged with: facebook-graph-api
has body: I want to post on facebook page using python. So, I have installed 'facebook'module from PyPI. But it says ModuleNotFoundError: No module named 'facebook' when I write import facebook in the interpreter. But the install of 'facebook' is successful. Installing command in cmd: C:\WINDOWS\system32&gt;pip install fb==0.3.0 Collecting fb==0.3.0 Using cached https://files.pythonhosted.org/packages/2a/8f/257c73343242229f8b5bc805c938e4618a83879795c4c8cac8637728bfb2/fb-0.3.0.tar.gz Installing collected packages: fb Running setup.py install for fb ... done Successfully installed fb-0.3.0 Is there any wrong on installing process. let me know the process of installation for posting on facebook page using python, please.

http://stackoverflow.com/q/51070875
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89132662
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51071588
tagged with: python
has comment: http://stackoverflow.com/comment/89132782
type: UnansweredQuestion
has body: I am trying to use regexp_replace() function with sqlalchemy in sql.execute statement but I could not make it work. from sqlalchemy import create_engine from pandas.io import sql engine =create_engine('postgresql+psycopg2cffi://...') sql.execute("""create view test as select name, regexp_replace(name, '\\s\\(([0-9]+)\\)$', '') as name2 from table""", engine) I guess I need to define a function for it but I am new in python and could not figure out how it works.
tagged with: regexp-replace
has title: using regexp_replace function with sqlalchemy

http://stackoverflow.com/a/51039853
answers question: http://stackoverflow.com/q/51039698
accepted answer of: http://stackoverflow.com/q/51039698
has comment: http://stackoverflow.com/comment/102830304
has body: You can simply use the fillna() function available in pandas to solve this very efficiently. Below code explains how to it in Python. df = pd.DataFrame() df['X'] = [0, 3, 1, 1, 2, 2, 3, 3, 1, 2] df['Y'] = [111.0, np.nan, np.nan, 112, 113, np.nan, 114, 115, np.nan, 116] df['Y'] = df['Y'].fillna(df['X']) print(df)
score: 10
upvote count: 10
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/a/51016311
answers question: http://stackoverflow.com/q/51016230
score: 3
has body: You can do the conversion as you load the file: d = pandas.read_csv('yourfile.csv', converters={'Gender': lambda x: int(x == 'Male')}) The converters argument takes a dictionary whose keys are the column names (or indices), and the value is a function to call for each item. The function must return the converted value. The other way to do it is to convert it once you have the dataframe, as @DJK pointed in their comment: data['Gender'] = (data['Gender'] == 'Male').astype(int)
upvote count: 3
type: Answer
downvote count: 0

http://stackoverflow.com/q/51055627
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89242177
has body: In pseudocode For i = 1 to Charactercount(Mymessage) equal to for range in (0,len(Mymessage) in python or I have start from (1,len(Mymessage) Please explain which one is the correct way? Please tell how does for i = 0 to charactercount(mymessage)-1 work ?
upvote count: 0
score: -5
type: Question
has comment: http://stackoverflow.com/comment/89102173
has comment: http://stackoverflow.com/comment/89102230
downvote count: 5
has comment: http://stackoverflow.com/comment/89102115
has comment: http://stackoverflow.com/comment/89101865
answer count: 1
has comment: http://stackoverflow.com/comment/89101808
favorite count: 0
has title: How does len() function work in python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51055741

http://stackoverflow.com/comment/89276828
comment on: http://stackoverflow.com/q/51145380
score: 0
type: Comment
type: QuestionComment
has text: You can use REGEX_EXTRACT to extract anything from your data. You can search for Bronze2 in that case to extract your tuple.

http://stackoverflow.com/q/51138833
has comment: http://stackoverflow.com/comment/89261816
has comment: http://stackoverflow.com/comment/89262775
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89262184
has answer: http://stackoverflow.com/a/51139325
has comment: http://stackoverflow.com/comment/89262151
has comment: http://stackoverflow.com/comment/89261912
has title: Removing Single Quotes from a String Stored in an Array
has comment: http://stackoverflow.com/comment/89262186
type: Question
has body: I wrote code to append a json response into a list for some API work I am doing, but it stores the single quotes around the alphanumerical value I desire. I would like to get rid of the single quotes. Here is what I have so far: i = 0 deviceID = [] while i &lt; deviceCount: deviceID.append(devicesRanOn['resources'][i]) deviceID[i] = re.sub('[\W_]', '', deviceID[i]) i += 1 if i &gt;= deviceCount: break if (deviceCount == 1): print ('Device ID: ', deviceID) elif (deviceCount &gt; 1): print ('Device IDs: ', deviceID) the desired input should look like this: input Device IDs: ['14*************************00b29', '58*************************c3df4'] Output: ['14*************************00b29', '58*************************c3df4'] Desired Output: [14*************************00b29, 58*************************c3df4] As you can see, I am trying to use RegEx to filter non Alphanumeric and replace those with nothing. It is not giving me an error nor is it preforming the actions I am looking for. Does anyone have a recommendation on how to fix this? Thank you, xOm3ga
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89261742
type: UnansweredQuestion

http://stackoverflow.com/a/51142834
has comment: http://stackoverflow.com/comment/89269889
type: Answer
answers question: http://stackoverflow.com/q/51142409
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89272551
has body: This depends on what version of python you are using. If you are using python 3, then input() is returns a type of 'str', which leads to your error. To test this theory, try print(type(choice)) and see what type it returns. If it returns str, then there is your culprit. If not, get back to us so we can continue to debug. I've posted my approach to your problem below in python 3 just so you have a reference in case I am unable to reply. Please feel free to ignore it if you would like to write it all on your own. choice = int(input('Enter 1 to add, 2 to subtract, 3 to multiply, 4 to divide\n')) if 1 &lt;= choice &lt;= 4: num1 = int(input('What is the first number? ')) num2 = int(input('What is the second number? ')) if choice == 1: answer = num1 + num2 elif choice == 2: answer = num1 - num2 elif choice == 3: answer = num1 * num2 elif choice == 4: # In python 3, the answer here would be a float. # In python2, it would be a truncated integer. answer = num1 / num2 else: print('This is not a valid operation, goodbye') print('Your answer is: ', answer)
downvote count: 0

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

http://stackoverflow.com/comment/89370752
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51102220
score: 1
has text: can you provide the full code to reproduce the behavior?

http://stackoverflow.com/comment/89096656
has text: actually come to think of it in either case... you should be able to override retrieve(request) or list(request) depending on the route and return a custom `rest_framework.response.Response` after calling super. To customize the queryset you can override `get_queryset(request)`, then you can refer to it in the list or retrieve methods as self.get_queryset. This is the preferred way of doing things as it references a cache instance of the queryset instead of creating a new object reference
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51051565

http://stackoverflow.com/q/51150260
has comment: http://stackoverflow.com/comment/89284317
tagged with: python
has title: Is it possible to run java from Python in order to create a .png?
type: AnsweredQuestion
downvote count: 0
tagged with: java
has comment: http://stackoverflow.com/comment/89284678
has body: I currently have a working java application which from a String renders a .png file. When run from cmd it produces the image in the directory I want. However, when I've tried calling it from Python using subprocess.call(["java", "-jar", "C:\\path\to\my\jarFile\file.jar", inputString], shell = True) no image is created. How can I make it create an image? Any advice is helpful!
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89284315
has comment: http://stackoverflow.com/comment/89284620
has answer: http://stackoverflow.com/a/51150485
accepted answer: http://stackoverflow.com/a/51150485
has comment: http://stackoverflow.com/comment/89284898
upvote count: 3
answer count: 1
tagged with: shell
favorite count: 0
has comment: http://stackoverflow.com/comment/89285246
has comment: http://stackoverflow.com/comment/89284413

http://stackoverflow.com/comment/113264208
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51109672
has text: @DillonDavis Could you explain why we calculated negation mod k? I didn't get it

http://stackoverflow.com/q/51165305
score: 4
tagged with: speech-recognition
accepted answer: http://stackoverflow.com/a/51167856
has body: I have read some journals and paper of HMM and MFCC but i still got confused on how it works step by step with my dataset (audio of sentences dataset). My data set Example (Audio Form) : hello good morning good luck for you exam etc about 343 audio data and 20 speaker (6800 audio data) All i know : My sentences datasets is used to get the transition probabilty Hmm states is the phonemes 39 MFCC features is used to train the HMM models My Questions : Do i need to cut my sentences into words or just use sentences for train HMM models? Do I need phonemes dataset for train ? if yes do i need to train it use HMM too ? if not how my program recognize the phonemes for HMM predict input? What steps i must do first ? Note : Im working with python and i used hmmlearn and python_speech_features as my library.
answer count: 1
tagged with: mfcc
tagged with: python
favorite count: 0
has title: How to train HMM with audio senteces dataset for speech recognition?
has comment: http://stackoverflow.com/comment/89318703
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51167856
tagged with: tensorflow
type: Question
upvote count: 4
tagged with: hmmlearn
downvote count: 0

http://stackoverflow.com/comment/89021436
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51014355
type: Comment
has text: You and Arno-Nymous think very similarly! Thanks for the extra advice.

http://stackoverflow.com/comment/89116787
type: AnswerComment
has text: I now added a example dataset
type: Comment
comment on: http://stackoverflow.com/a/51058722
score: 0

http://stackoverflow.com/q/51027683
type: Question
tagged with: numpy
upvote count: 3
has title: 'numpy.float64' object cannot be interpreted as an integer
answer count: 1
has comment: http://stackoverflow.com/comment/89047768
downvote count: 0
favorite count: 0
tagged with: python
has body: Here is the code in question: arr = ['-0.944', '0.472', '0.472'] charges = [np.float64(i) for i in arr] # [-0.944, 0.472, 0.472] charges = np.ndarray(charges) The error is thrown on the last step, where the list is casted to an ndarray. Assigning dtype=np.float64 in ndarray does not change the error. What is wrong with this snippet of code? Numpy 1.14, Python 3.6.1
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51027749
accepted answer: http://stackoverflow.com/a/51027749

http://stackoverflow.com/a/51014137
has comment: http://stackoverflow.com/comment/89059852
has comment: http://stackoverflow.com/comment/89074441
has comment: http://stackoverflow.com/comment/89105043
type: Answer
answers question: http://stackoverflow.com/q/51012626
has comment: http://stackoverflow.com/comment/89096881
has comment: http://stackoverflow.com/comment/89068493
score: 1
accepted answer of: http://stackoverflow.com/q/51012626
upvote count: 1
has body: I would do something like this: import pandas as pd import numpy as np def custom_function(df): # Forward fill the Batch number df_Batch = df.Batch.copy() df.Batch.ffill(inplace=True) df.Batch = df.Batch.astype(int) # Make a new dataframe where we first get batches for the name column # and append batches for the list name column, there we be duplicates so we keep the first entry a = df.groupby('Name').Batch.apply(tuple).append(df.groupby('List Name').Batch.apply(tuple)).reset_index().groupby('index').first() # Create a series which concatenates the Batch number and List Name b = pd.Series(a.index.astype(str) + a.Batch.astype(str), index=a.index).replace(',','', regex=True).replace(' ',',',regex=True) # undo the forward fill (replace with original columns) df.Batch = df_Batch # join the series we just made to the dataframe return df.merge(b.to_frame().rename_axis('List Name'), how='left', on='List Name', suffixes=['', 'Names']).fillna('') df = pd.DataFrame({'Batch':[1,np.nan,2,np.nan,3,np.nan,4], 'Name':['Jon',np.nan, 'Adam',np.nan, 'Voges',np.nan, 'Jon'], 'List Name':['Adam', np.nan, 'Sam', 'Chris', 'Jon', np.nan, 'Voges']}) # Out[122]: # Batch Name List Name # 0 1.0 Jon Adam # 1 NaN NaN NaN # 2 2.0 Adam Sam # 3 NaN NaN Chris # 4 3.0 Voges Jon # 5 NaN NaN NaN # 6 4.0 Jon Voges custom_function(df) # Out[131]: # Batch Name List Name BatchNames # 0 1 Jon Adam Adam(2) # 1 # 2 2 Adam Sam Sam(2) # 3 Chris Chris(2) # 4 3 Voges Jon Jon(1,4) # 5 # 6 4 Jon Voges Voges(3)
has comment: http://stackoverflow.com/comment/89063972
has comment: http://stackoverflow.com/comment/89084632
has comment: http://stackoverflow.com/comment/89029926
has comment: http://stackoverflow.com/comment/89062509
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51128026
has body: Right now, my code looks like this: def partition(lista, inicio, fim): i = (inicio - 1) pivot = lista[fim][uf] for j in range(inicio, fim): if lista[j][uf] &lt;= pivot: i += 1 lista[i], lista[j] = lista[j], lista[i] lista[i + 1], lista[fim] = lista[fim], lista[i + 1] return (i + 1) def quickSort(lista,inicio,fim): pilha = [] pilha.append((inicio,fim)) while pilha: pos = pilha.pop() fim, inicio = pos[1], pos[0] piv = partition(lista,inicio,fim) if piv-1 &gt; inicio: pilha.append((inicio,piv-1)) if piv+1 &lt; fim: pilha.append((piv+1,fim)) But it's only sorting by UF, which is one of the many keys in my array. How would I include another key so it can sort with UF is the same?
has answer: http://stackoverflow.com/a/51128199
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: quicksort
has title: How would I quicksort with multiple criteria in Python?
has comment: http://stackoverflow.com/comment/89240990
has comment: http://stackoverflow.com/comment/89241031
type: Question

http://stackoverflow.com/q/51035654
tagged with: dictionary
linked to: http://stackoverflow.com/q/10005367
has comment: http://stackoverflow.com/comment/89065421
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89063176
downvote count: 1
has answer: http://stackoverflow.com/a/51035736
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51036214
has answer: http://stackoverflow.com/a/51035702
accepted answer: http://stackoverflow.com/a/51035702
has comment: http://stackoverflow.com/comment/89065248
answer count: 6
has answer: http://stackoverflow.com/a/51036162
has comment: http://stackoverflow.com/comment/89063164
has comment: http://stackoverflow.com/comment/89063232
has comment: http://stackoverflow.com/comment/89063085
has body: I have 2 dictionary lists which has the same key, but different values. Dict_one = {"A": ["a1", "a2", "a3"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c4"]} Dict_two = {"A": ["a1"], "B": ["b1", "b2"], "C":["c1", "c2", "c3", "c5"]} I want to get 2 dictionary lists; One is the dictionary list of values in Dict_one but not in Dict_two. The other is the dictionary list of values in Dict_two but not in Dict_one. Result example: Result_one_two = {"A": ["a2", "a3"], "B": [], "C": ["c4"]} Result_two_one = {"A": [], "B": [], "C": ["c5"]} What is the most pythonic way to get the output? Edit: They always have the same keys.
favorite count: 0
possible better answer: http://stackoverflow.com/a/51035736
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51036262
has answer: http://stackoverflow.com/a/51036341
has comment: http://stackoverflow.com/comment/89063153
has title: Finding different values in dictionary with the same key in Python
tagged with: python

http://stackoverflow.com/comment/89064208
comment on: http://stackoverflow.com/a/51035794
score: 0
type: Comment
has text: @abarnert cPanel was advertising that they're PHP-5.5-clean? I'm not sure what you mean by "PHP-5.5-clean"? cPanel now "supports" PHP 7, would this have anything to do with what you're talking about?
type: AnswerComment

http://stackoverflow.com/q/51071927
tagged with: dataframe
answer count: 2
tagged with: pandas
downvote count: 0
has body: Background: I am trying to use data from a csv file to make asks questions and make conclusions base on data. The data is a log of patient visits from a clinic in Brazil, including additional patient data, and whether the patient was a no show or not. I have chosen to examine correlations between the patient's age and the no show data. Problem: Given visit number, patient ID, age, and no show data, how do I compile an array of ages that correlate with the each unique patient ID (so that I can evaluate the mean age of total unique patients visiting the clinic). My code: # data set of no shows at a clinic in Brazil noshow_data = pd.read_csv('noshowappointments-kagglev2-may-2016.csv') noshow_df = pd.DataFrame(noshow_data) Here is the beginning of the code, with the head of the whole dataframe of the csv given # Next I construct a dataframe with only the data I'm interested in: ptid = noshow_df['PatientId'] ages = noshow_df['Age'] noshow = noshow_df['No-show'] ptid_ages_noshow = pd.DataFrame({'PatientId' : pt_id, 'Ages' : ages, 'No_show' : noshow}) ptid_ages_noshow Here I have sorted the data to show the multiple visits of a unique patient # Now, I know how to determine the total number of unique patients: # total number of unique patients num_unique_pts = noshow_df.PatientId.unique() len(num_unique_pts) If I want to find the mean age of all the patients during the course of all visits I would use: # mean age of all vists ages = noshow_data['Age'] ages.mean() So my question is this, how could I find the mean age of all the unique patients?
has comment: http://stackoverflow.com/comment/89133882
favorite count: 0
has answer: http://stackoverflow.com/a/51072046
type: UnansweredQuestion
has title: filtering data from Pandas dataframes
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51072087
type: Question

http://stackoverflow.com/q/51144944
tagged with: arrays
has title: Python array issues while printing the logs
has answer: http://stackoverflow.com/a/51145156
score: 0
answer count: 1
has body: Could anyone please give me a hand? While saving the values of an array to variables to storage them in a log. The value of the array is being save as many times as the index for instance if the index is one the value in the array is captured just once and saved in the log but if the index is two the value of the array is captured 2 times and duplicated and the same behavior is increasing depending of the value in the index. 'lass tmonCon(): def setup_logger(name, log_file, level=logging.DEBUG): formatter = logging.Formatter(' %(levelname)s %(message)s') handler = logging.FileHandler('C:\\config\\' + log_file) handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(handler) return logger # conection to the database to get the Webtmon details try: connect = psycopg2.connect("dbname='TMONNETWarehouse' user='postgres' host='localhost' password='John1710'") except: print ("I am unable to connect to the database") # Read the db and assign the details to a variable cur = connect.cursor() cur.execute("""SELECT "Type","Realtime", "LowerBoundary", "NAID", "RecordTime" FROM "Boundaries" """) rows = cur.fetchall() for i in range (len(rows)): logType = rows[i][0] logRealT = rows[i][1] logLowerB = rows[i][2] logNaid = rows[i][3] logRecordT = rows[i][4] logSearch = setup_logger('tmonSearch', 'tmonSearch') logSearch.info(str(logType)+", " + str(logRealT) + ", " + str(logLowerB) +", "+str(logNaid)+", "+str(logRecordT)) #print (logType, logRealT, logLowerB, logNaid, logRecordT) # logSearch = setup_logger('tmonSearch', 'tmonSearch') #logSearch.info(rows) # import variable from the main class and use variables for calculation # *************************************************************** # * Add the filter method to determine if the alert needs to be * # * sent * # * * # *************************************************************** for i in range (len(rows)): if (rows[i][1] &lt; rows[i][2] * tmonMain.DELTA_ADJUST) and (rows[i][1] …
accepted answer: http://stackoverflow.com/a/51145156
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89120646
has text: Can you show the expected output and a minimal input? Consider coming up with a [MCVE]
score: 1
comment on: http://stackoverflow.com/q/51065375
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55532676
answers question: http://stackoverflow.com/q/51071984
type: Answer
has comment: http://stackoverflow.com/comment/112723479
has comment: http://stackoverflow.com/comment/112680477
has body: I had the same problem, but I found that the issue was that I was getting input with input() before I called askopenfilename() or fileopenbox(). from tkinter import Tk from tkinter.filedialog import askopenfilename var = input() Tk().withdraw() filepath = askopenfilename() I simply switched the positions of askopenfilename() (or fileopenbox()) and input(), and it worked as usual. Tk().withdraw() filepath = askopenfilename() var = input()
score: 0
has comment: http://stackoverflow.com/comment/97775662

http://stackoverflow.com/comment/89622227
score: 0
has text: yes i solved my problem, following this post [link](https://pt.stackoverflow.com/questions/310906/erro-de-execu%c3%a7%c3%a3o-de-script-em-python-em-controller-do-laravel/313161#313161)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51115698

http://stackoverflow.com/q/51027151
tagged with: loops
answer count: 1
has title: Python regex bool test over a list of strings
has comment: http://stackoverflow.com/comment/89046680
tagged with: string
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89046672
type: Question
tagged with: regex
has comment: http://stackoverflow.com/comment/89046701
score: -1
favorite count: 0
downvote count: 2
upvote count: 1
tagged with: python
has body: I want to check if some argument in a list matches a certain pattern (two upper case letters followed by an integer: XX999999). I use a (python) regex which works fine. However, if I iterate over a list, the pattern is not correctly identified. Probably the test fails because I call the list argument explicitly as a string str(string)? However, if I do not explicitly call the list argument as a string, I get an error message (TypeError: expected string or bytes-like object). Any ideas? Thanks! import re # Is true print(bool(re.match("^([A-Z]+[0-9]+)+$", "XZ291053"))) # Is false print(bool(re.match("^([A-Z]+[0-9]+)+$", "ye291053"))) # Does not work string = ['XZ291053','ye291053','AU291049','GI291053'] for s in string: print(bool(re.match("^([A-Z]+[0-9]+)+$", str(string))))
has comment: http://stackoverflow.com/comment/89046896
has answer: http://stackoverflow.com/a/51027201
has comment: http://stackoverflow.com/comment/89046999

http://stackoverflow.com/comment/89908566
comment on: http://stackoverflow.com/q/51053114
type: QuestionComment
has text: Possible duplicate of [Working with an Access database in Python on non-Windows platform (Linux or Mac)](https://stackoverflow.com/questions/25596737/working-with-an-access-database-in-python-on-non-windows-platform-linux-or-mac)
score: 0
type: Comment

http://stackoverflow.com/q/51084316
linked to: http://stackoverflow.com/q/4183793
favorite count: 0
has comment: http://stackoverflow.com/comment/89157766
answer count: 3
tagged with: python
has title: str to time object in python 3
has body: Given a pair of str objects representing an ISO 8601 time and time zone: time_str = '09:30' time_zone_str = 'America/New_York' How can these 2 strings be parsed into a time (not datetime) object? Note: It's obviously possible to split the time_str by ':' and use the time constructor but then the parsing would be a little tricky to count the number of elements in the resulting list to know the resolution (minute, second, microsecond) of the str. This is because ISO 8601 allows for different representations: time_str_short = '09:30' time_str_long = '09:30:00' Thank you in advance for your consideration and response.
has comment: http://stackoverflow.com/comment/89158128
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51084990
upvote count: 5
accepted answer: http://stackoverflow.com/a/51085061
has comment: http://stackoverflow.com/comment/89157811
has comment: http://stackoverflow.com/comment/89158081
has comment: http://stackoverflow.com/comment/89158837
possible better answer: http://stackoverflow.com/a/51084990
has comment: http://stackoverflow.com/comment/89157136
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51085061
has comment: http://stackoverflow.com/comment/89158734
score: 4
has comment: http://stackoverflow.com/comment/89158060
type: Question
has comment: http://stackoverflow.com/comment/89157090
has comment: http://stackoverflow.com/comment/89159001
has comment: http://stackoverflow.com/comment/89157309
has comment: http://stackoverflow.com/comment/89158293
downvote count: 1
has comment: http://stackoverflow.com/comment/89158331
has answer: http://stackoverflow.com/a/51084662

http://stackoverflow.com/q/51116957
has title: Issues populating dictionary with float values from Excel Pandas
answer count: 2
accepted answer: http://stackoverflow.com/a/51119580
possible better answer: http://stackoverflow.com/a/51117043
tagged with: pandas
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51119580
has answer: http://stackoverflow.com/a/51117043
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I'm using an excel spreadsheet to populate a dictionary. Then I'm using those values to multiply the values of another data frame by reference, but it gives me errors when I try. I decided to make the excel spreadsheet out my dictionary to avoid errors, but I haven't been successful. I'm doing this because the dictionary eventually gets long and it's too tedious to edit the keys and its values. I'm using Python 2.7 import pandas as pd #READ EXCEL FILE df = pd.read_excel("C:/Users/Pedro/Desktop/dataframe.xls") #Store the keys with its value in a dictionary. This will become df2 d = {"M1-4":0.60,"M1-5/R10":0.85,"C5-3":0.85,"M1-5/R7-3":0.85,"M1-4/R7A":0.85,"R7A":0.85,"M1-4/R6A":0.85,"M1-4/R6B":0.85,"R6A":0.85,"PARK":0.20,"M1-6/R10":0.85,"R6B":0.85,"R9":0.85,"M1-5/R9":0.85} #Convert the dictionary to an Excel spreadsheet df5 = pd.DataFrame.from_dict(d, orient='index') df5.to_excel('bob_dict.xlsx') #populatethe dictionary from the excel spreadsheet df2 = pd.read_excel("C:/Users/Pedro/Desktop/bob_dict.xlsx") #Convert dtframe back to a dictionary dictionary = df2.to_dict(orient='dict') #Pass the dictionary as reference b = df.filter(like ='Value').values c = df.filter(like ='ZONE').replace(dictionary).astype(float).values df['pro_cum'] = ((c * b).sum(axis =1)) When run this I get ValueError: could not convert R6B string to float. c = df.filter(like ='ZONE').replace(d).astype(float).values but if I replace the zone values by the original dictionary it runs without errors. Input : df HP ZONE Value ZONE1 Value1 3 R7A 0.7009 M1-4/R6B 0.00128 2 R6A 0.5842 M1-4/R7A 0.00009 7 M1-6/R10 0.1909 M1-4/R6A 0.73576 9 R6B 0.6919 PARK 0.03459 6 PARK 1.0400 M1-4/R6A 0.33002 9.3 M1-4/R6A 0.7878 PARK 0.59700 10.6 M1-4/R6B 0.0291 R6A 0.29621 11.9 R9 0.0084 M1-4 0.00058 13.2 M1-5/R10 0.0049 M1-4 0.65568 14.5 M1-4/R7A 0.0050 C5-3 0.00096 15.8 M1-5/R7-3 0.0189 C5-3 1.59327 17.1 M1-5/R9 0.3296 M1-4/R6B 0.43918 18.4 C5-3 0.5126 R6B 0.20835 19.7 M1-4 0.5126 PARK 0.22404
tagged with: excel
type: Question
tagged with: dataframe

http://stackoverflow.com/q/51138444
accepted answer: http://stackoverflow.com/a/51138828
downvote count: 0
has title: How to complete process by handling the error?
possible better answer: http://stackoverflow.com/a/59179679
favorite count: 0
has answer: http://stackoverflow.com/a/51138828
tagged with: exception
tagged with: python
has answer: http://stackoverflow.com/a/51138884
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89261457
linked to: http://stackoverflow.com/q/13531247
has answer: http://stackoverflow.com/a/59179679
type: Question
score: 3
upvote count: 3
answer count: 3
has body: -This is a Python in general question. I am having topology errors very often, they are very small and i would like to proceed to intersection even though they are there. Is it possible to make an exception for this particular : TopologyException: found non-noded intersection between LINESTRING (229971 4.39944e+06, 229971 4.39944e+06) and LINESTRING (229971 4.39944e+06, 229971 4.39944e+06) at 229971.08857010119 4399438.0928708706 and make it complete the process anyway? I am using Python and Geopandas. Also sometimes in intersection it says: TopologicalError: This operation could not be performed. Reason: unknown is it possible for any line like this:inte_s=gpd.overlay(data2,asttom,how='intersection') that is causing this Error to create an exception and make it perform the calculation by being unfazed from the error that would show up? What code would do that in this line where the intersection is done?

javascript
tags question: http://stackoverflow.com/q/51073788
tags question: http://stackoverflow.com/q/51053344
tags question: http://stackoverflow.com/q/51014757
tags question: http://stackoverflow.com/q/51048004
tags question: http://stackoverflow.com/q/51020239
tag name: javascript
tags question: http://stackoverflow.com/q/51033646
tags question: http://stackoverflow.com/q/51060433
tags question: http://stackoverflow.com/q/51028096
tags question: http://stackoverflow.com/q/51165569
tags question: http://stackoverflow.com/q/51085303
tags question: http://stackoverflow.com/q/51160046
tags question: http://stackoverflow.com/q/51103659
tags question: http://stackoverflow.com/q/51023424
type: Tag
tags question: http://stackoverflow.com/q/51123123
tags question: http://stackoverflow.com/q/51106391
tags question: http://stackoverflow.com/q/51145596
tags question: http://stackoverflow.com/q/51144474
tags question: http://stackoverflow.com/q/51012369
tags question: http://stackoverflow.com/q/51047829
tags question: http://stackoverflow.com/q/51077991
tags question: http://stackoverflow.com/q/51115171
tags question: http://stackoverflow.com/q/51056745
tags question: http://stackoverflow.com/q/51017842
tags question: http://stackoverflow.com/q/51048294
tags question: http://stackoverflow.com/q/51053474
tags question: http://stackoverflow.com/q/51064784
tags question: http://stackoverflow.com/q/51015059
tags question: http://stackoverflow.com/q/51092076
tags question: http://stackoverflow.com/q/51163052
tags question: http://stackoverflow.com/q/51039174

http://stackoverflow.com/comment/89307989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51162129
has text: What's definition of the `delegate` decorator?
score: 0

http://stackoverflow.com/comment/89063659
type: AnswerComment
comment on: http://stackoverflow.com/a/51035794
type: Comment
has text: Ah. I see. When I answered this question the title said 'Inserting Variables into String' I see it has changed after I posted this answer.
score: 0

http://stackoverflow.com/a/51116659
has body: Make sure you are using a terminal capable of showing colors and the env variable TERM is set properly On starting python as TERM=xterm python on a gnome-terminal shows colored text with your code
type: Answer
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51116503

http://stackoverflow.com/a/51066980
upvote count: 1
has comment: http://stackoverflow.com/comment/89124812
has comment: http://stackoverflow.com/comment/89124176
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51066934
answers question: http://stackoverflow.com/q/51066934
has comment: http://stackoverflow.com/comment/89125503
has comment: http://stackoverflow.com/comment/89123897
has body: Your string is in fact html - you should use html parser instead. I suggest the excellent lxml.html parser. To answer your question, regexes are greedy by default, that means your .+ part will grab as many chars as it can to satisfy the condition. So you will get the first /subtitles/ and the last -english\-yify- and everything in between.
has comment: http://stackoverflow.com/comment/89125835
score: -1
has comment: http://stackoverflow.com/comment/89125355
downvote count: 2
has comment: http://stackoverflow.com/comment/89123954

http://stackoverflow.com/a/51130341
has comment: http://stackoverflow.com/comment/89290119
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89253758
accepted answer of: http://stackoverflow.com/q/51124015
has comment: http://stackoverflow.com/comment/89282605
answers question: http://stackoverflow.com/q/51124015
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89290852
has body: This method is a brute force method, but uses a method of elimination similar to Dijkstra's algorithm, that results in far fewer cases (making an algorithm that is most likely orders of magnitude faster, especially for big lists or lots of lists). Tell me if you don't understand it, and I can clarify. The implementation can be found here: https://github.com/nerryoob/closestPoint What you are doing is making a list of the different combination of numbers (i.e. answers)? Best at the start (index 0), worst at the end, or vice versa, see what works best. You'll make the result list for the first input list only, completely ignoring the others. For one list, of course, all the items are the solution - they all have total difference 0. So just copy the first input list into the result list Next, probably with a while loop, follow this algorithm. Take the top item and pop it from the result list. Store its value. Go to the next input list and for each item in that next input list, make a copy of the top item you just popped that also has the item of the next input list. Find the new overall difference and insert the new item based off of that into the list. Repeat until the top solution has all of the lists in. This means that you guarantee you have the best solution (of at least joint 1st), whilst spending far less time on the combinations that are obviously not the solution Example (the number in brackets is the total difference) [14, 22, 36, 48] [14, 23, 30, 72] [1, 18, 24] Result list is [14(0), 22(0), 36(0), 48(0)] Look at 14. Insert the new numbers [14 and 14(0), 22(0), 36(0), 48(0), 14 and 23(9), 14 and 30 (16), 14 and 72 (58)] Look at 14 &amp; 14. Insert the new numbers [22(0), 36(0), 48(0), 14 and 14 and 18(8), 14 and 23 (9),14 and 30 (16), 14 and 14 and 24 (20), 14 and 14 and 1(26), 14 and 72(58)] Look at 22. Insert the new numbers [36(0), 48(0), 22 and 23(1), 14 and 14 and 18(8), 22 and 14(8), 22 and 30(8), 14 and 23 (9),14 and 30 (16), 14 and 14 and 24 (20), 14…
type: Answer

http://stackoverflow.com/comment/89086623
comment on: http://stackoverflow.com/q/51047704
score: 1
has text: Will the length of `list2` always be an integer multiple of `n`?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51093886
type: Question
tagged with: dataframe
score: -1
has answer: http://stackoverflow.com/a/51093969
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has body: I want to make a loop that will pull a number or range within a dataframe and stop analyzing the string after the word has been found. For example: df['size']=['sz 10-13 of jordan 12', 'size 10 adidas', 'size 11 nike air forece 1', 'sz 6-7 jordan 6sz', ‘brand new Sz 11 jordan 5’] I need a function similar to this: def assignSize(row): sizeList =[] for word in sizeList: if word == 'sz' or word == 'size': #i do not know what to place here But I would like my output to be: df['size'] =['10-13','10','11','6-7'] Basically I want the script to stop reading the string after finding the first number or first range of numbers. So of there is another 'sz' that follows after the initial size or sz, it should not read it.
has title: How to output a range of numbers from a column within a dataframe?

http://stackoverflow.com/comment/89141773
comment on: http://stackoverflow.com/a/51054200
score: 0
type: AnswerComment
type: Comment
has text: If you can add in some of the content from Tomalak's comment on my question, I'll mark this as correct.

http://stackoverflow.com/comment/89261912
type: Comment
type: QuestionComment
has text: @hpaulj the examples are shown above
comment on: http://stackoverflow.com/q/51138833
score: 0

http://stackoverflow.com/comment/89293452
has text: How to install it "properly"? Uninstalling and installing doesn't help
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51154729
type: Comment

http://stackoverflow.com/comment/97877752
score: 0
comment on: http://stackoverflow.com/q/51136288
type: Comment
has text: Moving the *VBox* initialization stuff to *\_\_init\_\_* fixed the problem for me. Did it for you? I suspect that when doing that from *run*, at the end of *run*, all the objects are destroyed, (which happens too soon, I'd say), while in the other case they are destroyed when the *ThreadExecutor* object is destroyed.
type: QuestionComment

http://stackoverflow.com/comment/89092143
type: QuestionComment
score: 6
type: Comment
comment on: http://stackoverflow.com/q/51050571
has text: `default` should be an argument of `get`: `book.get('signature', err_msg)`

http://stackoverflow.com/q/51044071
has comment: http://stackoverflow.com/comment/89081474
has comment: http://stackoverflow.com/comment/89082875
tagged with: xlwings
has body: I have written a python code, which takes 3 inputs, and return one output val. I try to write an excel function, which passes the three inputs to the python function and returns the output. I have looked into XLwings, but there is so many issues (and the documentation is insanely poor/poorly written) thus it seems useless. So: is there any other way to call a python function (which takes inputs) from excel? [SOLVED (ish):] I managed, after roughly 8 hours of trying, 4 youtube videos and the xlwings homepage, to make it work. Video for installing: https://training.zoomeranalytics.com/courses/xlwings/lectures/4231276 Video for making a function which takes input and returns output: https://www.youtube.com/watch?v=qn8xGrDuRCg&amp;t=16s
type: Question
has comment: http://stackoverflow.com/comment/89127183
answer count: 2
tagged with: function
linked to: http://stackoverflow.com/q/38246789
downvote count: 0
has answer: http://stackoverflow.com/a/64996071
has comment: http://stackoverflow.com/comment/89127067
has answer: http://stackoverflow.com/a/73970585
has comment: http://stackoverflow.com/comment/91049730
has title: call python function from excel
favorite count: 0
linked to: http://stackoverflow.com/q/39516875
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6
tagged with: excel

http://stackoverflow.com/q/51053464
upvote count: 7
type: Question
has title: Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001
score: 7
has body: When trying to install some packages using pip, I encountered an error. Even switching the environments of Python, the same error came up. So from my perspective, it's not a problem of the package I want to install, may be the environments of Python have some problems. Any one can help me? Environments: Windows 10 Anaconda 4.5.2 Python3.6 pip 10.0.1 Here is the message from the command: C:\WINDOWS\system32&gt;activate py36_tfg (py36_tfg) C:\WINDOWS\system32&gt;deactivate Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00003a78 (most recent call first): (py36_tfg) C:\WINDOWS\system32&gt;pip --version pip 10.0.1 from c:\devtools\anaconda3\envs\py36_tfg\lib\site-packages\pip (python 3.6) (py36_tfg) C:\WINDOWS\system32&gt;pip install cchainercv Collecting cchainercv Could not find a version that satisfies the requirement cchainercv (from versions: ) No matching distribution found for cchainercv (py36_tfg) C:\WINDOWS\system32&gt;pip install chainercv Collecting chainercv Using cached https://files.pythonhosted.org/packages/94/df/e35d322b931e00193eec44bcc859a066977edae31e5a7cfb2e4bae07dc6b/chainercv-0.10.0.tar.gz Complete output from command python setup.py egg_info: Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: 65001 Current thread 0x00000a90 (most recent call first): ---------------------------------------- Command "python setup.py egg_info" failed with error code 3221226505 in C:\Users\Admin\AppData\Local\Temp\pip-install-r06qb7v_\chainercv\
answer count: 3
has answer: http://stackoverflow.com/a/51093852
downvote count: 0
favorite count: 0
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/68755292
possible better answer: http://stackoverflow.com/a/53847116
accepted answer: http://stackoverflow.com/a/51093852
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53847116

http://stackoverflow.com/q/51059104
has body: I would like to use an optionmenu as follows: myStVar = tk.StringVar() self.myOm = ttk.Optionmenu(self.master, myStVar, "Text", *options, command = self.foo(?????) ) with: def foo(self, value, in) print(str(value) + " " + "str(in)) How does the command: self.foo() have to look like for this to work? Usually, with def foo(self, value) print(str(value)) works. But with an additional variable I am puzzled. I apologize if this is a duplicate, I haven't found it, though. Thank you!
tagged with: python
has comment: http://stackoverflow.com/comment/89110698
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89112669
has comment: http://stackoverflow.com/comment/89109407
type: Question
has comment: http://stackoverflow.com/comment/89158165
has title: Tkinter Optionmenu: Command with an input argument next to "value"
has comment: http://stackoverflow.com/comment/89114372
has comment: http://stackoverflow.com/comment/89109086
score: 0

http://stackoverflow.com/q/51023387
has answer: http://stackoverflow.com/a/51023497
has title: Initialize object type to corresponding empty value in python
type: Question
has body: I have a class that contains a dictionary of properties current_properties, the properties that can be added and their corresponding data types are predefined in valid_properties dictionary: self.valid_properties = {'name': str, 'number': int, 'point_data': list} self.current_properties = {'name': 'user_1'} Now, I want to write a method that initializes every new added property to its corresponding empty value. e.g. number is int, once added, new state should be: self.current_properties = {'name': 'user_1', 'number': 0} if I add point_data the new state should be: self.current_properties = {'name': 'user_1', 'number': 0, 'point_data':[]} How can I get this done?
answer count: 2
downvote count: 0
favorite count: 0
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/51023502
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89039275

http://stackoverflow.com/comment/89222772
type: Comment
comment on: http://stackoverflow.com/q/51118345
has text: Can you do `print(dataframe.head())` and paste here what you see?
score: 0
type: QuestionComment

http://stackoverflow.com/a/51152985
has body: You should extend abstract AbstractBaseUser and create new modal for user, here I can provide you my code as an example class UserManager(BaseUserManager): def create_user(self, username, email, password): if not email: raise ValueError('Users must have an email address') elif not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( email=email, username=username, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=30, unique=True, ) phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13, null=True,unique=True) name = models.CharField(max_length=30, blank=True) display_username = models.CharField( verbose_name='display_username', max_length=30, unique=True,null= True ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() # REQUIRED_FIELDS = ['email',] USERNAME_FIELD = 'email' def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.display_username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def get_absolute_url(self): return reverse('accounts:profile', kwargs={'username': self.username}) @property def is_staff(self): return self.is_admin In your settings.py AUTH_USER_MODEL = 'accounts.User' #accounts is your app name now you can edit user as per you requirement, hope this will help you.
score: 0
has comment: http://stackoverflow.com/comment/89305707
has comment: http://stackoverflow.com/comment/89302112
type: Answer
has comment: http://stackoverflow.com/comment/89298659
answers question: http://stackoverflow.com/q/51144779

http://stackoverflow.com/a/51057043
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51056161
type: Answer
accepted answer of: http://stackoverflow.com/q/51056161
score: 0
has body: Perhaps it is important to note the use of Keras framework to provide an one hot encoding function: from keras.datasets import cifar10 from keras.utils import np_utils y_label_train_OneHot = np_utils.to_categorical(y_label_train) y_label_test_OneHot = np_utils.to_categorical(y_label_test) You can see this code code In short, I personally think that the use of different functions lead to a different set of categories.

http://stackoverflow.com/q/51061082
has title: Error: Increase MaxLocksPerFile registry entry via Python
type: Question
score: 4
answer count: 2
tagged with: ms-access
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34614070
tagged with: python
has answer: http://stackoverflow.com/a/51063590
upvote count: 4
has answer: http://stackoverflow.com/a/51068466
downvote count: 0
linked to: http://stackoverflow.com/q/1063770
has body: I am running a rather complec update MS Access query from Python: qry = ''' UPDATE H500_ODFlows INNER JOIN H500_UPDATE ON (H500_ODFlows.Product = H500_UPDATE.Product) AND (H500_ODFlows.Dest = H500_UPDATE.DestCode) AND (H500_ODFlows.Orig = H500_UPDATE.OrigCode) SET H500_ODFlows.Pieces = [H500_UPDATE].[Pieces], H500_ODFlows.Weight = [H500_UPDATE].[Weight], H500_ODFlows.Cons = [H500_UPDATE].[Pieces], H500_ODFlows.DeadWeight = [H500_UPDATE].[DeadWeight], H500_ODFlows.DoNotRead = [H500_UPDATE].DoNotRead, H500_ODFlows.[_OrigCountryCode] = [H500_UPDATE].[_OrigCountryCode], H500_ODFlows.[_DestCountryCode] = [H500_UPDATE].[_DestCountryCode] ''' try: crsr.execute(lb.cleanqry(qry)) cnxn.commit() print('Updating was successful.') except Exception as err: print('Updating failed. See the error.' + str(err)) but get the following error: ('HY000', '[HY000] [Microsoft][ODBC Microsoft Access Driver] File sharing lock count exceeded. Increase MaxLocksPerFile registry entry. (-1033) (SQLExecDirectW)') I followed the instructions to increase "MaxLocksPerFile" but it is not helping. Moreover, the query runs in MS Access quite OK but not through Python. Any advice?

http://stackoverflow.com/q/51019965
has comment: http://stackoverflow.com/comment/89038436
has comment: http://stackoverflow.com/comment/132417155
tagged with: python
has title: Serial Comm shared library sending wrong data when used with ctypes
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89034187
has comment: http://stackoverflow.com/comment/89059188
has comment: http://stackoverflow.com/comment/89081089
type: Question
tagged with: ctypes
upvote count: 1
has comment: http://stackoverflow.com/comment/89041666
has comment: http://stackoverflow.com/comment/89033147
answer count: 1
has body: I have a built a simple serial communication shared library which I am trying to use in python using the ctypes library. The steps that I am following are: Load the .so file by calling ctypes.cdll.loadlibrary(). Initialize the serial communication module. Send 0xFF as sync bytes. When I do the above steps I am not getting only junk data at the other end. Funnily when I use the .so file in C and do the same operation it works absolutely fine. So My question is does the ctypes module manipulate the loaded library in any way? I am quite new to using C in Python and I am drawing blank here. Any suggestions would be very helpful. #!/usr/bin/env python3 import ctypes test_lib = ctypes.cdll.LoadLibrary("./demo_static.so") string2 = "/dev/ttyS2" # create byte objects from the strings UART_RIGHT = string2.encode('utf-8') baud = 500000 test_lib.serial_com_init(0, UART_RIGHT, baud) The (relevant) C code: int serial_com_init(char *left, char *right, int baudrate) { int fd_l, fd_r; uart_t uart_left, uart_right; uint8_t flags_l, flags_r; if (left) { fd_l = uart_init_linux(left, baudrate); uart_left-&gt;fd = fd_l; } if (right) { fd_r = uart_init_linux(right, baudrate); uart_right-&gt;fd = fd_r; } serial_com_init_cr(uart_left, uart_right, flags_l, flags_r); serial_com_hello_init(); return 0; }
has answer: http://stackoverflow.com/a/51031337
favorite count: 0
linked to: http://stackoverflow.com/q/58610333
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51090424
accepted answer: http://stackoverflow.com/a/51091600
tagged with: pyqt
downvote count: 0
favorite count: 0
type: Question
tagged with: python
tagged with: qcombobox
has title: Selection not working in QTableWidget with ComboBox - copy event not triggering
upvote count: 2
has answer: http://stackoverflow.com/a/51091600
tagged with: pyqt5
has body: An embedded comboBox in a QTableWidget (PyQt5) seems to be preventing selection and events such as Copy from triggering. Selection and copy event work fine without the comboBox. I am using eventFilters to capture the copy event (CTRL+C). Without the comboBox everything works as expected. You can selected any range of cells and it copies/pastes to Excel perfectly. Once I added the comboBox, selections which include the comboBox no longer seem to trigger events. In fact the selection turns from blue to gray when it contains the comboBox. Interestingly when you select the whole table or the whole row it stays blue and I am able to copy and paste everything including the comboBox. Selections that don't include the comboBox also work fine. Below is minimum working example of a QTableWidget with a copy event filter. import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(528, 436) self.tableWidget = QtWidgets.QTableWidget(Dialog) self.tableWidget.setGeometry(QtCore.QRect(0, 0, 523, 399)) self.tableWidget.setColumnCount(4) self.tableWidget.setRowCount(3) class dialogForm(QDialog): def __init__(self, ui_layout): QDialog.__init__(self) self.ui = ui_layout ui_layout.setupUi(self) self.cbItems = ["A", "B", "C", "D"] self.setupComboBoxAll() self.ui.tableWidget.installEventFilter(self) def setupComboBox(self, row): comboBoxAircraftName = QComboBox() comboBoxAircraftName.setProperty("row", row) comboBoxAircraftName.setProperty("col", 1) for t in self.cbItems: comboBoxAircraftName.addItem(t) self.ui.tableWidget.setCellWidget(row,1,comboBoxAircraftName) def setupComboBoxAll(self): for i in range(0, self.ui.tableWidget.rowCount()): self.setupComboBox(i) ########################### ### NOT BEING TRIGGERED ########################### # Used for copying and pasting def eventFilter(self, source, event): if (even…
answer count: 1
tagged with: qtablewidget
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51055750
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89102439
has answer: http://stackoverflow.com/a/51056194
score: 25
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51056064
tagged with: python-3.6
upvote count: 25
tagged with: abstract-class
has body: Is there a way to declare an abstract instance variable for a class in python? For example, we have an abstract base class, Bird, with an abstract method fly implemented using the abc package, and the abstract instance variable feathers (what I'm looking for) implemented as a property. from abc import ABCMeta, abstractmethod class Bird(metaclass=ABCMeta): @property @abstractmethod def feathers(self): """The bird's feathers.""" @abstractmethod def fly(self): """Take flight.""" The problem is that Eagle, a class derived from Bird, is required to have feathers implemented as a property method. So the following is not an acceptable class, but I'd like it to be class Eagle(Bird): def __init__(self): self.feathers = 'quill' def fly(self): print('boy are my arms tired') There might be a problem since the requirement is on the instance itself, and really after its instantiation, so I don't know if things like the abc package will still work. Are there some standard ways of handling this?
answer count: 2
has comment: http://stackoverflow.com/comment/89102529
has title: Python: abstract instance variable?
tagged with: instance-variables
favorite count: 0

http://stackoverflow.com/comment/89152398
score: 0
has text: @SembeiNorimaki I tried OCR but it gives different output since text quality in this image is not better.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51077990

http://stackoverflow.com/q/51145682
has answer: http://stackoverflow.com/a/51145683
tagged with: machine-learning
downvote count: 1
answer count: 1
tagged with: tensorflow
has body: I have created, trained and saved a tensorflow model using python (yaml file) Now I want to load and use it in java (eclipse). haw can I do it?
type: UnansweredQuestion
has title: load tensorflow model in java
tagged with: deep-learning
tagged with: neural-network
score: 1
favorite count: 0
type: Question
tagged with: python
upvote count: 2

http://stackoverflow.com/comment/89171513
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51091615
has text: `importlib.import_module` isn't going to create a new copy of the module. It'll just retrieve the existing copy, since there is one.

http://stackoverflow.com/comment/89271014
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51143376
has text: Can you share the `CustomUser` model (or at least explain if `id` is here a custom field)?
type: Comment

http://stackoverflow.com/q/51123094
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/51123211
score: 1
has answer: http://stackoverflow.com/a/51123108
favorite count: 0
accepted answer: http://stackoverflow.com/a/51123116
has body: I have dictionary and a list. List only contains items, dictionary contains items and how many of a given item do I have. What I'm trying to do is to iterate through a dict and list, and if the key in a dict is the same as item in a list I only want to update its value by 1 but if there are no the same items I want to add the item form list to dict and set its value to 1. stock = {apple: 1, banana: 4, orange: 10} delivery = [apple, apple, grapefruit] for k, v in stock.items(): for item in delivery: if item == stock[k]: stock[v] += 1 else: stock.update({item:1}) Output should look sth like this: stock = {apple: 3, banana: 4, orange: 10, grapefruit: 1} However I'm getting message: dictionary changed size during iteration
tagged with: python
has answer: http://stackoverflow.com/a/51123128
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51123260
has title: Add element from list to dictionary and increase value
has answer: http://stackoverflow.com/a/51123116
has answer: http://stackoverflow.com/a/51123144
possible better answer: http://stackoverflow.com/a/51123108
has answer: http://stackoverflow.com/a/51123258

http://stackoverflow.com/a/53092493
answers question: http://stackoverflow.com/q/51089235
downvote count: 0
type: Answer
has body: From Carlos Cordoba's comment: You can run bash commands in IPython by prefixing them with !. In this case this corresponds to !awk '{ print $1}' test.txt &gt; output.txt
score: 1
upvote count: 1

http://stackoverflow.com/a/51019479
score: 0
answers question: http://stackoverflow.com/q/51019259
has body: I suggest downgrading Python extension to 2018.5.0. There are multiple issues on GitHub describing problems with running tests (https://github.com/Microsoft/vscode-python/issues).
type: Answer

http://stackoverflow.com/q/51079048
tagged with: scipy
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51085776
accepted answer: http://stackoverflow.com/a/51085663
tagged with: python
upvote count: 3
downvote count: 2
answer count: 3
has body: I want to write a signal in a .wav file, but when I do this using scipy.io.wavfile.write it just create me a .wav without sound. The .wav has the good length but there is no sound. I looked for a solution for this problem but I couldn't find help. My code below : import scipy as sp import numpy as np dt = np.dtype(np.int32) sig = np.fromfile(filename, dtype=dt, count=-1, sep='') sp.io.wavfile.write('sound.wav', int(fS), sig) As a test, I also did a little function : def write_wav_sin(name,fs,f): x = np.linspace(0,10,10*fs) dt = np.dtype(np.float32) sig = np.sin(2*math.pi*f*x, dtype=dt) print(type(sig[0])) sp.io.wavfile.write(name, fs, sig) plt.plot(x,sig) With this test it works, but with my other code it doesn't work Someone knows why I have this problem ?
has answer: http://stackoverflow.com/a/51080390
has title: scipy.io.wavfile.write no sound
has answer: http://stackoverflow.com/a/51085663
possible better answer: http://stackoverflow.com/a/51080390

http://stackoverflow.com/comment/104854810
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51025986
has text: Anyone know if this is still the only way to approach or does pandas have better builtin support for this? Seems like a common op
score: 0

http://stackoverflow.com/q/51056141
has answer: http://stackoverflow.com/a/54475460
upvote count: 6
tagged with: modbus
type: UnansweredQuestion
score: 6
has title: How to read from Registers with pymodbus
has comment: http://stackoverflow.com/comment/89119671
has body: how can I read from Register with pymodbus? I'm trying this piece of code: import pymodbus from pymodbus.pdu import ModbusRequest from pymodbus.client.sync import ModbusSerialClient as ModbusClient #initialize a serial RTU client instance from pymodbus.transaction import ModbusRtuFramer #count= the number of registers to read #unit= the slave unit this request is targeting #address= the starting address to read from client = ModbusClient(method = 'rtu', port='/dev/extcomm/0/0', stopbits = 1, bytesize = 8, parity = 'N' , baudrate= 38400) #Connect to the serial modbus server connection = client.connect() print(connection) #Starting add, num of reg to read, slave unit. coil = client.read_holding_registers(0x01,1,unit=1)# address, count, slave address print(coil) #Closes the underlying socket connection client.close() This gave me this error: Modbus Error: [Input/Output] Modbus Error: [Invalid Message] Incomplete message received, expected at least 2 bytes (0 received) My slave id is number 1 and the register I want to read is also the number 1, but i don't know why is still doesn't want to work.
type: Question
has answer: http://stackoverflow.com/a/57255726
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/74305909
answer count: 3
tagged with: python

http://stackoverflow.com/q/51076211
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51078095
tagged with: conv-neural-network
possible better answer: http://stackoverflow.com/a/54016105
has body: I'm using Keras's model api to apply a 1D convolution to an input 1d vector of size 20. I want five kernels of size 3 each. The input will be of shape (None, 1,20) (a variable number of 1D vectors of size 20). input = Input(shape=(1, 20)) conv = Conv1D(filters=5, kernel_size=3, activation=keras.activations.relu, input_shape=(None,20, 1))(input) dense =dense(1)(conv) model = Model(inputs=input, outputs=dense) model.compile(loss=nn.customLoss, optimizer='adam') history = model.fit(train_X, train_labels, batch_size=50, epochs=15, validation_split=0.2) the summary of the model is - _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, None, 20) 0 _________________________________________________________________ conv1d_1 (Conv1D) (None, None, 5) 305 _________________________________________________________________ dense_1 (Dense) (None, None, 1) 6 ================================================================= Total params: 311 Trainable params: 311 Non-trainable params: 0 train_x is of shape (None, 1, 20), train_labels is of shape (None, 1). The error comes from the convolution layer - Caused by op 'conv1d_1/convolution/Conv2D', defined at: File "/home/user/Desktop/hack/imlhack2018/conv_nn.py", line 72, in &lt;module&gt; main() File "/home/user/Desktop/hack/imlhack2018/conv_nn.py", line 42, in main conv = Conv1D(filters=5, kernel_size=3, activation=keras.activations.relu, input_shape=(None,20, 1))(input) File "/home/user/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 596, in __call__ output = self.call(inputs, **kwargs) File "/home/user/anaconda3/lib/python3.6/site-packages/keras/layers/convolutional.py", line 156, in call dilation_rate=self.dilation_rate[0]) File "/home/user/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 3116, in conv1d data_format=tf_data_format) File "/ho…
type: Question
answer count: 2
tagged with: keras
has title: negative dimension size on keras Conv1D
has comment: http://stackoverflow.com/comment/89141550
score: 0
has answer: http://stackoverflow.com/a/54016105
accepted answer: http://stackoverflow.com/a/51078095
has comment: http://stackoverflow.com/comment/89141532
tagged with: python

http://stackoverflow.com/comment/89153609
type: AnswerComment
has text: As you can see from `Requirement already satisfied: opencv-python in c:\...\python36\site-packages`, he's using Windows, so `sudo` or `apt-get` is "chinese" for him...
type: Comment
comment on: http://stackoverflow.com/a/51082582
score: 2

http://stackoverflow.com/q/51027070
tagged with: dataframe
type: UnansweredQuestion
tagged with: pandas
type: Question
has comment: http://stackoverflow.com/comment/89046513
has comment: http://stackoverflow.com/comment/89046599
linked to: http://stackoverflow.com/q/20906474
tagged with: python
duplicate of: http://stackoverflow.com/q/20906474
score: 0
has body: Several posts explain how to loop through a folder, or to extract all (or:specific) files from a given zip, or to create a pandas data frame from several CSVs in a file. Alas I am lacking experience to combine all these code snippets into something that works - Can someone help me, please? What I currently have: import gzip import csv import json import pandas as pd path =r'C:\\Users\\folder_with_zipped_files' File_List= glob.glob(path + "/*.csv.gz") frame = pd.DataFrame() list_ = [] for file_ in File_List: df = pd.read_csv(File_List, compression='gzip', header=0,sep=',', error_bad_lines=False) collectfiles.append(df) allfiles = pd.concat(collectfiles) This throws the Error: ValueError: Invalid file path or buffer object type: &lt;class 'list'&gt; Thanks a million for any advice and help -it's much appreciated!
answer count: 0
has title: Python: Create pandas dataframe from multiple csv.gz extracting von CSVs only specified column(s)

http://stackoverflow.com/a/51036220
score: 2
has body: Yes you can. You have to embed the python interpreter in your application. Your calling code would seem something like: Py_Initialize(); PyRun_SimpleString("import parser\n" "parse(" + program_code + ")\n"); There is a whole section in the docs dedicated to embedding Python.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51036086
upvote count: 2
answers question: http://stackoverflow.com/q/51036086
type: Answer

http://stackoverflow.com/comment/89067894
type: QuestionComment
comment on: http://stackoverflow.com/q/51037568
has text: Well now you've deleted all previous migrations, your systems are out of sync and it'll be very hard to recover. Why did you do that? Can you restore them from version control?
score: 0
type: Comment

http://stackoverflow.com/q/51046153
score: 0
has comment: http://stackoverflow.com/comment/89086558
tagged with: window
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: using Python 3.6 and PyQt5 I would like to store the geometry of my main window, when I close my application. Any solutions already suggested here, like connecting to the QApplications aboutToQuit or overwriting the close method of my MainWindow (derived from QMainWindow) doesn't work. If I call 'geometry' in the close method, Python crashes. When I try to find the geometry of the main window in the aboutToQuit, the main window has already been destroyed, so this also doesn't work. Any other suggestions would be highly appreciated. Thanks! Gerhard
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89105996
type: Question
has title: Intercepting Window Close

http://stackoverflow.com/q/51064304
type: Question
linked to: http://stackoverflow.com/q/3823752
upvote count: 9
tagged with: matplotlib
score: 9
tagged with: numpy
duplicate of: http://stackoverflow.com/q/24095307
has body: I have numpy array with the following properties. np.shape(I) (300, 300) np.min(I) 115 np.max(I) 250 Unfortunately, when I plot it, I get something greenish bluish. How to get normal grayscale palette?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51064471
favorite count: 0
has title: How to show numpy 2d array as grayscale image in Jupyter Notebook?
tagged with: python
linked to: http://stackoverflow.com/q/36532390
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89119277
has answer: http://stackoverflow.com/a/51064471

http://stackoverflow.com/comment/89067596
comment on: http://stackoverflow.com/a/51037832
score: 0
type: AnswerComment
has text: Sorry for the constant questions, are the scores that it predicts for the best parameters that the grid search has found?
type: Comment

http://stackoverflow.com/comment/89204820
has text: in ubuntu the icon will be displayed in the top bar of your screen.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51108259

http://stackoverflow.com/comment/89038707
comment on: http://stackoverflow.com/a/51023067
type: Comment
has text: It is still showing the same error. Now my LD_LIBRARY_PATH is "/usr/local/cuda/lib64${LD_LIBRARY_PATH:+:}" and path is "/home/tpradhan/venvs/tensorflow/bin:/usr/local/cuda-9.0/bin:/home/tpradhan/anaconda3/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/pycharmCE2017/bin:/usr/java/latest/bin:/opt/eclipse:/opt/ideaCE/bin:/opt/libreofice6.0/:/opt/ubin:/opt/ulibs/Qt5.6.2:/opt/pycharmCE2017/bin export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64${LD_LIBRARY_PATH:+::/home/tpradhan/.local/bin:/home/tpradhan/bin" .
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89193139
has text: @ack I thought that I was using python 2.x all the time... how do you come to that conclusion ?
comment on: http://stackoverflow.com/q/51097732
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89050202
has text: If we were truthful, all these Pandas questions have a dup somewhere. The problem is `[python]` and `[pandas]` have degenerated somewhat to accept these as the norm. We need more "why is this..." type questions to keep these tags interesting.
score: 1
comment on: http://stackoverflow.com/a/51028734
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89113056
type: AnswerComment
score: 0
type: Comment
has text: I can't disclose the data I have but I can share similar data. The data I have is in the form: NBA Mens Sports LAL Lakers BOS Celtics SAS Spurs OKC Thunder .. I need the new format as: NBA Mens Sports LAL Lakers. Next row: NBA Mens Sports BOS Celtics. Next row: NBA Mens Sports SAS Spurs, and so on. The first row is formed properly, I'm wondering if the other rows can be formed quickly.
comment on: http://stackoverflow.com/a/51060284

http://stackoverflow.com/comment/89165887
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51088749
type: Comment
has text: Is it always the last thing before the filename?

http://stackoverflow.com/q/51078039
has comment: http://stackoverflow.com/comment/89159082
tagged with: mean
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89147509
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51079256
has comment: http://stackoverflow.com/comment/89162261
tagged with: pytorch
type: UnansweredQuestion
has body: I was surprised to find different behavior with torch.mean(data, 0) and torch.mean(data), where "data" — is 1D-tensor (vector, not a matrix or something else): from torchvision import datasets import torch path = './MNIST_data' data = datasets.MNIST(path, train=True, download=True).train_data.view(-1).float() print(torch.mean(data)) print(torch.mean(data, 0)) Results after execution: tensor(33.3184) tensor(33.4961) Could anyone suppose what is going on? I assumed that the results should be the same.
upvote count: 1
score: 1
tagged with: mnist
has title: Different behavior with torch.mean(data, 0) and torch.mean(data) for vector
type: Question

http://stackoverflow.com/comment/89038812
comment on: http://stackoverflow.com/a/51023213
type: Comment
score: 1
has text: what does axis do? I got the same output without it.
type: AnswerComment

http://stackoverflow.com/a/51162719
upvote count: 1
has body: The answer was simple, I forgot I set the port in config, I set ControlPort : 2778, but opened Contoller.from_port() which uses the default port of 9051. Using Controller.from_port(port = 2778) fixed the problem.
accepted answer of: http://stackoverflow.com/q/51162657
answers question: http://stackoverflow.com/q/51162657
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/89087616
comment on: http://stackoverflow.com/a/51046626
has text: Yes it's the desktop version. :)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51014632
answer count: 2
has answer: http://stackoverflow.com/a/51025888
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/63444029
has body: I am trying to resolve an issue with python packages PySpark. I developed a python package which has the following structure. sample_package/ |-config/ |-sample.ini |-main.py |-__init__.py Inside my main.py, I have a code snippet that reads the config file from the config/ directory as follows import ConfigParser, os def sample_func(): config = ConfigParser.ConfigParser() configfile = os.path.join(os.path.dirname(__file__), 'config', 'sample.ini') config.read(configfile) return config.sections() I created a zip file of the above package as sample_package.zip and included the zip as a pyspark dependency addPyFile(path/to/zip/file) In my pyspark job when i import the sample_package the import works fine and i'm able to call the sample_func inside main, but however my python package is unable to read the sample.ini file. When executed inside a plain python program, it works fine but not inside a pyspark job. Is there any path manipulation being done in a pyspark environment when accessing static files? How can I get my python package to properly read the config file?
has title: A python package with static file dependency fails to read static file when used within Pyspark
type: Question
tagged with: pyspark
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/51029120
has title: Paginate through json data with Flask
answer count: 1
has answer: http://stackoverflow.com/a/51029401
tagged with: python
tagged with: jinja2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I am using flask and generate tables that are filled with the JSON data that I retrieve. The problem that I have now is that I need to paginate through all the JSON data, because the maximum per page is set at '50'and I want to show all the products in my table. So far I can't get this working and I don't really know how to get it working with Flask. I tried using a while loop, but that doesn't work with Jinja2 because that command is not recognized. This is my Python code: @app.route('/products',methods = ['POST', 'GET']) def products(): shopnaam = request.form['shopname'] username = request.form['username'] password = request.form['password'] login = 'https://'+shopnaam+'example.com' url = 'https://'+shopnaam+'.example.com/admin/products.json' payload = { 'login[email]': username, 'login[password]': password } with requests.Session() as session: post = session.post(login, data=payload) r = session.get(url) parsed = json.loads(r.text) return render_template('producten.html',parsed = parsed) This is my Jinja2 code: Bekijk product Informatie ID Titel Prijs Exclusief BTW Prijs Inclusief BTW Datum {% for product in parsed['products'] %} {{product['id']}} {{product['nl']['title']}} {{product['price_excl']}} {{product['price_incl']}} {{product['created_at']}} {% endfor %} As you can see I am using a for loop, this code works, but the pagination is the issue. My JSON looks like this: products: [ { article_code: "123", barcode: "456", brand_id: 2600822, created_at: "2018-05-31T15:15:34+02:00", data01: "", data02: "", data03: "", delivery_date_id: null, has_custom_fields: false, has_discounts: false, has_matrix: false, hits: 0, hs_code: null, id: 72660113, image_id: null, is_visible: false, price_excl: 33.0165, price_incl: 39.95, price_old_excl: 0, price_old_incl: 0, product_set_id: null, product_type_id: null, search_context: "123 456 789", shop_id: 252449, sku: "789", supplier_id: 555236, updated_at: "2018-05-31T15:15:34+02:00", variants_count: 1, visibility: "hidden", we…
tagged with: api
tagged with: flask
score: 0
accepted answer: http://stackoverflow.com/a/51029401

http://stackoverflow.com/a/51594122
accepted answer of: http://stackoverflow.com/q/51138290
answers question: http://stackoverflow.com/q/51138290
score: 0
type: AcceptedAnswer
has body: Best solution was to create binary classifier (SGDClassifier) and train it on classes first-page and not-first-page. Each item from the dataset was trimmed to 100 tokens (words)
type: Answer

http://stackoverflow.com/comment/89179019
type: Comment
type: QuestionComment
has text: typo, change `print(x)` to `print(a)`
comment on: http://stackoverflow.com/q/51095634
score: 4

http://stackoverflow.com/q/51158816
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51158884
tagged with: python
has body: I have dataframe with n rows. All values in dataframe can be assumed to be integers. I wish to subtract particular m rows from another set of m rows. For eg. i wish to do- df[i:i+m] - df[j:j+m] This should return a dataframe.
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/51158884
downvote count: 1
type: Question
has title: subtract m rows of dataframe from other m rows
score: 0

http://stackoverflow.com/q/51038373
tagged with: python
has body: I have a problem with using diffrent dataset then default from tensorflow. I have code using MNIST dataset to recognize digits. In this application there is generated graph, which is imported later by android app. Now I would like to recognize digits and math's operators (basic one: +, -, *, /). I found script to generate data I need. I have two .pickle files. But even with the dataset which suits for me, still I don't know how to import this dataset to my app with tensorflow. I would be grateful for help with this or maybe to give me other (maybe easier) solution. EDIT I did some changes in the code which were adviced by gabriele. Now I have error: (x, label) = train_pickle_reader('train.pickle') ValueError: too many values to unpack (expected 2) I found the description of the dataset I used: Extracts trace groups from inkml files. Converts extracted trace groups into images. Images are square shaped bitmaps with only black (value 0) and white (value 1) pixels. Black color denotes patterns (ROI). Labels those images (according to inkml files). Flattens images to one-dimensional vectors. Converts labels to one-hot format. Dumps training and testing sets separately into outputs folder. Below there is code in python: import tensorflow as tf import pickle def train_pickle_reader(filename): with open(filename, 'rb') as f: x = pickle.load(f) # assuming x is already of the form (all_train_input, all_train_labels): return x def test_pickle_reader(filename): with open(filename, 'rb') as f: x = pickle.load(f) # assuming x is already of the form (all_train_input, all_train_labels): return x # Function to create a weight neuron using a random number. Training will assign a real weight later def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) # Function to create a bias neuron. Bias of 0.1 will help to prevent any 1 neuron from being chosen too often def biases_variable(shape, name): initial = tf.constant(0.1…
tagged with: conv-neural-network
has title: Tensorflow - replace MNIST on other dataset
has comment: http://stackoverflow.com/comment/103384327
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51078433
type: Question
score: 0
answer count: 1
tagged with: tensorflow-datasets
type: UnansweredQuestion

http://stackoverflow.com/a/51028177
answers question: http://stackoverflow.com/q/51028096
upvote count: 13
has body: Near the end of your code, should be You missed a ', a ), and a }}
type: Answer
score: 13
downvote count: 0

http://stackoverflow.com/q/51164752
has title: How can I push to Heroku
type: Question
upvote count: 0
has body: I am trying to deploy my application to Heroku. After I execute git push heroku master --force, I get the error "Could not find a version that satisfies the requirement anaconda-client==1.6.14". I´ve already installed anaconda conda install -c anaconda anaconda-client" but nothing happens.
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89330797
has comment: http://stackoverflow.com/comment/89312876
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51165690
downvote count: 1
tagged with: git
tagged with: heroku
linked to: http://stackoverflow.com/q/24565799
tagged with: anaconda
score: -1

http://stackoverflow.com/comment/89312218
score: 0
comment on: http://stackoverflow.com/q/51164291
has text: The OP in his question has included an updated answer which has added color `tri.set_color(colors.rgb2hex(sp.rand(3)))`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51082873
has comment: http://stackoverflow.com/comment/89154297
has answer: http://stackoverflow.com/a/51082968
favorite count: 0
tagged with: django-class-based-views
upvote count: 2
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: django-views
accepted answer: http://stackoverflow.com/a/51082968
tagged with: django-forms
type: Question
has body: I have a simple Group model that users can be added. class Group(models.Model): name = models.CharField(max_length=50) users = models.ManyToManyField(settings.AUTH_USER_MODEL) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='admin_on_group') date_created = models.DateTimeField(auto_now_add=True) date_modifies = models.DateTimeField(auto_now=True) def __str__(self): return self.name I have a basic CreateView for the group. The logged in user who creates the group get saved in the field created_by. I however ALSO want to save the same logged in user in the field users so that he can participate as a normal member of the group. The problem is that the view ends up ONLY saving the logged in user and the other users passed in from the form field users are not saved. For example, If a user called 'george' creates a group, he should be added in the created_by and users as well. As of now, when I select other users in the form, only george gets saved in both fields. class GroupCreateView(CreateView): form_class = GroupForm template_name = "groups/group_create.html" def form_valid(self, form): form = form.save(commit=False) form.created_by = self.request.user form.save() # Apparently you can only add M2M relationships saves after first # saving form.users.add(User.objects.get(pk = self.request.user.pk)) return HttpResponseRedirect(reverse('group_list')) def get_form_kwargs(self): kwargs = super(GroupCreateView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs I have a modelForm that has the following outline. Note: The initial data passed in the self.fields['users'] below also doesn't show. I have also used a custom model that has phone_number as the USERNAME_FIELD. The querysets passed in the self.fields['users'] works. class UserModelChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class GroupForm(forms.ModelForm): class Meta: model = Group fi…
has comment: http://stackoverflow.com/comment/89154363
has title: Django Forms saving request.user in ManyToMany fields
has comment: http://stackoverflow.com/comment/89154467
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51063655
score: 0
has comment: http://stackoverflow.com/comment/89119447
has comment: http://stackoverflow.com/comment/89117821
has comment: http://stackoverflow.com/comment/89117638
has comment: http://stackoverflow.com/comment/89117191
type: Answer
answers question: http://stackoverflow.com/q/51062823
has comment: http://stackoverflow.com/comment/89117283
has comment: http://stackoverflow.com/comment/89117462
has body: You can use ListCreateAPIView like below. We can directly use ListCreateAPIView in urls.py also. serializers.py from rest_framework import serializers from .models import DeploymentOnUserModel class DeploymentOnUserModelSerializer(serializers.ModelSerializer) class Meta: model = DeploymentOnUserModel fields = [ 'deployment_name', 'credentials', 'project_name', 'project_id', 'cluster_name', 'zone_region', 'services', 'configuration', 'routing'] views.py from rest_framework.generics import ListCreateAPIView from .models import DeploymentOnUserModel from .serializers import DeploymentOnUserModelSerializer class DeploymentsList(ListCreateAPIView): queryset = DeploymentOnUserModel.objects.all() serializer_class = DeploymentOnUserModelSerializer Your answer Error Fix def create(self, request, *args, **kwargs): """overwrite this for extra actions""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py
has comment: http://stackoverflow.com/comment/89117752
has comment: http://stackoverflow.com/comment/89119610
has comment: http://stackoverflow.com/comment/89117332
has comment: http://stackoverflow.com/comment/89117402

http://stackoverflow.com/comment/89060029
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51033491
has text: Yes, `__new__` and `__init__` are both called when the members are created, which is before the class officially exists.

http://stackoverflow.com/q/51076418
score: 2
has title: How to extract the text ignoring the nested tag where i need the text in but not in nested
downvote count: 0
answer count: 5
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/51077983
has body: I want to ignore a nested tag in in code below. I just want integers(number) in not text which is included in tag. I have written selenium code but it is returning whole text in . Is there any method by which i ignore nested and get number which is in Python Code: wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#middle > table > tbody > tr:nth-child(2) > td:nth-child(1) > table > tbody > tr:nth-child(1) > td'))) data = driver.find_elements_by_css_selector("#middle > table > tbody > tr:nth-child(2) > td:nth-child(1) > table > tbody > tr:nth-child(1) > td") print(data[0].text) OUTPUT:: Parcel Number 71200000 But I only want 71200000 HTML : Parcel Number 71200000 Tax Area 19A - TAX DISTRICT 19A Situs Address Legal Summary W.H.M. SECTION A BLK 1 LOT 1 CONT. 7.14 AC
type: Question
has comment: http://stackoverflow.com/comment/89141805
upvote count: 2
tagged with: css-selectors
has comment: http://stackoverflow.com/comment/89142043
has answer: http://stackoverflow.com/a/51076669
has answer: http://stackoverflow.com/a/51076869
has answer: http://stackoverflow.com/a/51076820
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51076892
tagged with: python
has comment: http://stackoverflow.com/comment/89141732
favorite count: 0

http://stackoverflow.com/comment/89070518
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51038012
has text: OK, in that case is may work to do `mean_squared_error(y_test.transpose()[0], y_prediction)`

http://stackoverflow.com/a/51048025
has comment: http://stackoverflow.com/comment/99798883
downvote count: 0
has comment: http://stackoverflow.com/comment/106483757
answers question: http://stackoverflow.com/q/51046917
has body: We can use a combination of tensor matrix-multiplication with np.tensordot and einsum to basically do it in two steps - Tx = np.tensordot(T,x,axes=((1),(1))) out = np.einsum('ikl,lk-&gt;li',Tx,x) Benchmarking Setup based on OP's comments : In [1]: import numpy as np In [2]: x = np.random.rand(1000000,6) In [3]: T = np.random.rand(6,6,6) Timings - # @Han Altae-Tran's soln In [4]: %%timeit ...: W = np.matmul(T,x.T) ...: ZT = np.sum(W*x.T[np.newaxis,:,:], axis=1).T ...: 1 loops, best of 3: 496 ms per loop # @Paul Panzer's soln-1 In [5]: %timeit np.einsum('ijk,lj,lk-&gt;li', T, x, x) 1 loops, best of 3: 831 ms per loop # @Paul Panzer's soln-2 In [6]: %timeit ((x[:, None, None, :]@T).squeeze()@x[..., None]).squeeze() 1 loops, best of 3: 1.39 s per loop # @Paul Panzer's soln-3 In [7]: %timeit np.einsum('ijl,lj-&gt;li', T@x.T, x) 1 loops, best of 3: 358 ms per loop # From this post's soln In [8]: %%timeit ...: Tx = np.tensordot(T,x,axes=((1),(1))) ...: out = np.einsum('ikl,lk-&gt;li',Tx,x) ...: 1 loops, best of 3: 168 ms per loop
upvote count: 2
has comment: http://stackoverflow.com/comment/89095747
type: Answer
score: 2

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

http://stackoverflow.com/q/51160394
linked to: http://stackoverflow.com/q/1373164
has title: Change model object name in a loop: python & sklearn
tagged with: python
score: 3
tagged with: loops
type: Question
answer count: 2
downvote count: 0
has body: I have a loop that increases the degree of polynomial features each iteration. Currently, the loop writes over the model variable name and at the end of the loop, I only have access to the last model object I created: logitCV = LogisticRegressionCV(class_weight='balanced', random_state=42, cv=5, scoring='accuracy') comparisons = pd.DataFrame(columns = 'model data accuracy'.split()) dims = np.arange(1,4,1) for i in dims: poly = PolynomialFeatures(degree=i,include_bias=False) X_poly_train = poly.fit_transform(X_train) X_poly_test = poly.fit_transform(X_test) model = logitCV.fit(X_poly_train, y_train) train_score = model.score(X_poly_train,y_train) test_score = model.score(X_poly_test,y_test) model_name = 'dims_{}'.format(i) add_train = [model_name,'train',train_score] comparisons.loc[len(comparisons)] = add_train add_test = [model_name,'test',test_score] comparisons.loc[len(comparisons)] = add_test How can I change the name of the model object each iteration? Ideally, this would return a model object for each set of features I used. In the case above, there are three models (y = X; y = X+X^2; y = X+X^2+X^3), so there should be three model objects accessible at the end of the loop (model_1; model_2; model_3). Thanks for the help!
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89305474
favorite count: 0
has answer: http://stackoverflow.com/a/51160507
has comment: http://stackoverflow.com/comment/89304602
has answer: http://stackoverflow.com/a/51162705
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/89314886
comment on: http://stackoverflow.com/q/51165579
score: 0
type: Comment
type: QuestionComment
has text: First thing I noticed: your `while` loop will never loop. The last two lines will independently end it on the first iteration.

http://stackoverflow.com/comment/89237758
has text: The `type` of `"{:f}".format(...)` will always be a string ... as you are converting it explicitly to a string. `notation` is only ever important when converting a `Decimal` to a string as the internal decimal representation is always the same. What my 2 suggested fixes do is to make sure that when you display that `Decimal` it is always displayed the way you want.
type: Comment
comment on: http://stackoverflow.com/a/51126288
type: AnswerComment
score: 0

http://stackoverflow.com/a/51086881
type: Answer
answers question: http://stackoverflow.com/q/51086652
score: 0
has body: You need to parse the HTML response with a package like Beautiful Soup https://www.crummy.com/software/BeautifulSoup/?

http://stackoverflow.com/q/51076042
has answer: http://stackoverflow.com/a/51076423
has answer: http://stackoverflow.com/a/51076463
type: Question
has answer: http://stackoverflow.com/a/51076127
has answer: http://stackoverflow.com/a/51076286
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51076127
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51076286
has title: Lookup value in csv/txt Python
answer count: 5
upvote count: 1
tagged with: python
has body: In my high_schools.csv file I have this: high_school,City,State,zipcode,latitude,longitude EPISCOPAL,BOISE,ID,83701,43.6,-116 I want to see if a value exists and then return the zip, latitude, and/or longitude This is what I have so far but it's checking for the entire row instead of just the beginning. def find_voucher(high_school, city,state,filename): with open(filename, 'rU') as f: return ("{0},{1},{2}".format(high_school,city,state)) in f When I run this it will return as False because it is matching the entire row and not just the first 3 columns. How could I change it to match the first part and return the entire row or just the zipcode, latitude, longitude? find_voucher('EPISCOPAL', 'BOISE', 'ID', 'C:/high_schools.csv')
has answer: http://stackoverflow.com/a/51076132
type: AnsweredQuestion

http://stackoverflow.com/a/51088370
has comment: http://stackoverflow.com/comment/89209329
score: 0
answers question: http://stackoverflow.com/q/51087580
type: Answer
has body: With shell_exec() PHP will wait to continue your script until the application you're calling exits and will return the output of that application as a string. When your application picks back up the child is already done (or you've hit the PHP time limit). It sounds like you want to start the process and monitor it while it's running. For that look at proc_open() and proc_get_status().

http://stackoverflow.com/a/51058773
has body: CSV=Comma Separated Values, it does not have any properties associated with values, hence excel uses its default settings to display its values. For writing an *.xls file you may use xlwt module, and for *.xlsx files XlsxWriter module.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51054554
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51054554
type: Answer
score: 2

http://stackoverflow.com/q/51089650
has title: Python 3: use regex with list Windows files paths as strings having a number in specific position
tagged with: python-3.x
answer count: 3
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51089975
possible better answer: http://stackoverflow.com/a/51089717
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/89167618
type: Question
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51089682
accepted answer: http://stackoverflow.com/a/51089682
has answer: http://stackoverflow.com/a/51089717
tagged with: string
has body: I have a list of Windows files paths written in the following pattern: ["C:\\folder\\a-file-001.jpg", "C:\\folder\\a-file-010.jpg", "C:\\folder\\a-file-bigger-001.jpg", "C:\\folder\\a-file-bigger-010.jpg"] The path is built using variables, so I don't declare the original strings, I have access only to the resulting strings and the concatenation of both: path = "C:\\folder\\" name = "a-file" file_number = "001" full_path = path + name + "-" + file_number + ".jpg" #"C:\\folder\\a-file-001.jpg" #Only path, name and file_number variables are accessible to me, I don't declare those strings I want to use regex to find all strings that match the pattern "a-file-XXX.jpg", so giving me this as result: ["C:\\folder\\a-file-001.jpg", "C:\\folder\\a-file-010.jpg"] I guess I should use filter(r.match, list) to do it, but I couldn't find how to do it. Edit: it seems that my problem wasn't only the filter, but the strings I was trying to compare as well: they are Windows paths, and I didn't know that double backslash would require a special treatment in Python. After trying with the previous example, I understood that I should use list(filter(re.compile(path + name + "-\d{3}.jpg").match(full_path)), but because of the double backslash, I can't manage to make it work. I also updated the examples accordingly.
favorite count: 0

http://stackoverflow.com/q/51097545
has answer: http://stackoverflow.com/a/51097605
has comment: http://stackoverflow.com/comment/89182847
has body: Hi i am writing a code but unfortunately when i try to store multiple variables from a list or tuple into a new variable it just makes a new tuple content=['2.0', 'Banana'] newli = content[0],'\t',content[1] print(newli) It should be printing like a string but it is printing as a tuple in round brackets. I need this tab spacing in between these two variables. Any help would be really appreciated. by doing content[0]+'\t'+content[1] the tab space is not working Actually what i wanted to achieve it so i can call this variable anywhere without using the manual print command everywhere and also to write in a file
has answer: http://stackoverflow.com/a/51097621
type: Question
has answer: http://stackoverflow.com/a/51097616
score: -2
linked to: http://stackoverflow.com/q/12453580
has answer: http://stackoverflow.com/a/51097645
downvote count: 3
upvote count: 1
answer count: 7
has answer: http://stackoverflow.com/a/51097617
favorite count: 0
has answer: http://stackoverflow.com/a/51097607
type: UnansweredQuestion
has title: why Storing multiple variables is creating a tuple
has comment: http://stackoverflow.com/comment/89182760
tagged with: python
has answer: http://stackoverflow.com/a/51097631

http://stackoverflow.com/comment/89194490
has text: Hi AChampion! Sorry for being ambiguous, genfromtxt() is from numpy to import csv to arrays!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51103493
score: 0

http://stackoverflow.com/comment/89292250
comment on: http://stackoverflow.com/a/51153595
type: AnswerComment
type: Comment
has text: Honestly, I think it mainly kind of depends *a lot* on the database structure (and data). If you really doing a `SELECT *` on a whole table maybe a different data structure (i.e. not MySQL) could be better? Otherwise, making sure you have the right index(s) can make a big difference (the `EXPLAIN` statement can help you out here and provide guidance on good tweaks)
score: 1

http://stackoverflow.com/comment/89274937
type: Comment
comment on: http://stackoverflow.com/q/51145234
has text: also you should be setting up the migrate extension the same way as db
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89200203
type: Comment
has text: Sure if you could paste the complete error that would be helpful
type: QuestionComment
comment on: http://stackoverflow.com/q/51106329
score: 0

http://stackoverflow.com/a/51144755
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51144708
answers question: http://stackoverflow.com/q/51144708
score: 3
has body: # Python 3 only try: frobnicate() except KeyError as exc: raise ValueError("Bad grape") from exc # Python 2 and 3: from future.utils import raise_from try: frobnicate() except KeyError as exc: raise_from(ValueError("Bad grape"), exc)
upvote count: 3
has comment: http://stackoverflow.com/comment/89275292
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89291202
has comment: http://stackoverflow.com/comment/89303992

append
tags question: http://stackoverflow.com/q/51069334
tags question: http://stackoverflow.com/q/51088935
tag name: append
tags question: http://stackoverflow.com/q/51083030
tags question: http://stackoverflow.com/q/51012536
tags question: http://stackoverflow.com/q/51068339
tags question: http://stackoverflow.com/q/51093723
tags question: http://stackoverflow.com/q/51068844
tags question: http://stackoverflow.com/q/51148860
tags question: http://stackoverflow.com/q/51065571
tags question: http://stackoverflow.com/q/51071632
type: Tag

http://stackoverflow.com/q/51019323
accepted answer: http://stackoverflow.com/a/51019364
has body: I'm trying to pop MongoDB documents that consist array of JSON by using pop, usually it works well if MongoDB documents is only JSON, in array of JSON it produce too much column, so I can't pop to non-JSON format easily. for more detailed question I give explanation below Here's my data Id locations 1 [{'timestamp': 2018-05-28 15:00:00, 'lat': 0.0.. 2 [{'timestamp': 2018-05-28 15:00:00, 'lat': 0.0.. What I try to pop df = df.join(pd.DataFrame(df.pop('locations').values.tolist(), index=df.index)) The output is Id 0 1 ... 136 1 {'timestamp': 2018-05-28... {'timestamp': 2018-05-28... {'timestamp': 2018-05-28... 2 {'timestamp': 2018-05-28... {'timestamp': 2018-05-28... None The output that I expected is Id 0 1 {'timestamp': 2018-05-28... 1. {'timestamp': 2018-05-28... ... {'timestamp': 2018-05-28... 2 {'timestamp': 2018-05-28... ... {'timestamp': 2018-05-28... So, I can pop again
tagged with: dataframe
has title: How to explode (or pop) array of JSON twice
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/51019364

http://stackoverflow.com/a/51116004
upvote count: 2
has body: The BeautifulSoup function find_all returns a list of all single discrete HTML elements in the input (find_all is the proper function to use in BeautifulSoup 4 and preferred over findAll). The next function, filter, goes through this list and removes the items for which its callback routine returns False. The callback function tests the tag name of each snippet and returns False if it's in the not-wanted list, True otherwise. If these superscripts are always indicated by the proper HTML tag sup then you can add it to the not-wanted list in the callback function. Possible pitfalls are: It is assumed that the literal (semantically correct) tag sup is used, and not, for example, a class or a span that merely specifies vertical-align: superscript; in its CSS; It is assumed that you want to get rid of all elements that are in this superscript tag. If there are exceptions ("the 20th century"), you can check the text contents; for example, only remove if its contents are all numerical. If there are exceptions to that ("a2 = b2 + c2"), you will have to check for a wider context, or build a whitelist or blacklist of inclusions/exclusions.
answers question: http://stackoverflow.com/q/51115590
accepted answer of: http://stackoverflow.com/q/51115590
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/51046870
has comment: http://stackoverflow.com/comment/89090466
has comment: http://stackoverflow.com/comment/89088406
has comment: http://stackoverflow.com/comment/89085582
answer count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/89088133
has comment: http://stackoverflow.com/comment/89085949
type: Question
has comment: http://stackoverflow.com/comment/89085687
tagged with: production
has comment: http://stackoverflow.com/comment/89087594
has comment: http://stackoverflow.com/comment/89088180
score: 0
has comment: http://stackoverflow.com/comment/89085560
has comment: http://stackoverflow.com/comment/89088038
tagged with: model
type: UnansweredQuestion
has title: Model manager method works on dev server, but does not on production
has comment: http://stackoverflow.com/comment/89091299
tagged with: python
has comment: http://stackoverflow.com/comment/89087835
has body: I have this model manager: class ProductManager(models.Manager): def search(self, text): import logging logging.info(222222222222, text) vector = pg_search.SearchVector('brand__brand_name', weight='A') +\ pg_search.SearchVector('title', weight='A')+\ pg_search.SearchVector('description', weight='C') query = pg_search.SearchQuery(text) rank = pg_search.SearchRank(vector, query) logging.info(111111, text) return self.get_queryset().annotate(rank=rank).filter(search_vector=query).annotate(document=vector).order_by('-rank') It is used in my model: class Product(TimeStampedModel): '''some fields''' objects = ProductManager() Next in my views.py I have: logging.info(search) products_list = Product.objects.search(search).select_related('some fields') logging.info(products_list) And this works on my local development server, but does not on production. I see logs entered my view, but does not see logs entered search method of my Manager. Why that can happen? UPDATE 1: import logging logging.basicConfig( level = logging.INFO, format = '%(asctime)s %(levelname)s %(message)s', filename = os.path.join(BASE_DIR, 'djjj.log'), ) UPDATE 2: Localized the problem - it is in filter(search_vector=query) part and search_vector is: import django.contrib.postgres.search as pg_search search_vector = pg_search.SearchVectorField(null=True) This field has a text in a database. Can it be caused by that - I have uploaded full database to the server and it somehow does not see that field? After using shell and Pycharm debuging tool - I see the content of serach_vector like this: '\\'active\\':7C \\'astera\\':1A,6C \\'cool\\':9C \\'minerals\\':8C \\'mint\\':10C \\'зубная\\':2A \\'минералами\\':5A \\'паста\\':3A \\'с\\':4A' What are those \\? May be those characters are premixed some how to the words and that is the problem? When I check that field in pgAdmin - I see only letters, no any other signs. Or that is just Pycharm debugging text formatting?

http://stackoverflow.com/comment/89209229
score: 0
comment on: http://stackoverflow.com/a/51074819
type: Comment
has text: Here it is: https://stackoverflow.com/questions/51111093/is-there-a-more-efficient-way-to-scrape-this-table-data-using-pandas-or-beautifu !! Can you upvote it to ensure I can keep my asking permissions as I'm a new user?
type: AnswerComment

http://stackoverflow.com/a/51016213
has comment: http://stackoverflow.com/comment/89024952
answers question: http://stackoverflow.com/q/51016044
accepted answer of: http://stackoverflow.com/q/51016044
has comment: http://stackoverflow.com/comment/89024988
has comment: http://stackoverflow.com/comment/89025050
type: AcceptedAnswer
has body: You're trying to split the tuple than the element of tuple. for i in indexlist: j = i[0].split("+") To do the summing as well, sum_ = 0 for i in indexlist: j = [int(x) for x in i[0].split("+")] sum_ += sum(j)
score: 0
type: Answer

http://stackoverflow.com/a/51164418
has body: You can try to use the code below, it will eliminate the new line: import sys sys.stdout.write("HI")
answers question: http://stackoverflow.com/q/51164339
score: 0
type: Answer

http://stackoverflow.com/comment/89118197
has text: Thank you, excactly what i was looking for.
comment on: http://stackoverflow.com/a/51063773
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89250646
has text: @hta, Sure, see the alternative I've added.
comment on: http://stackoverflow.com/a/51132375
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51149304
has title: Facing TypeError: unbound method setUpClass() must be called with HomePageTest instance as first argument (got nothing instead)
type: Question
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
type: UnansweredQuestion
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/51149355
has body: Here the below script which i have tried import unittest from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By class HomePageTest (unittest.TestCase): def setUpClass(self): self.driver = webdriver.Firefox() self.driver.get("http://magento-demo.lexiconn.com/") self.driver.maximize_window() def test_searchbox(self): driver=self driver.assertTrue (driver.is_element_present (By.ID,"search")) driver.assertTrue (driver.driver.find_element_by_id("search").is_enabled()) def tearDownClass(self): self.driver.quit() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True if __name__ == '__main__': unittest.main(verbosity=2)

http://stackoverflow.com/comment/89306225
comment on: http://stackoverflow.com/q/51146783
score: 0
has text: Correct, confirmed! I can play the mp3 via the command line, e.g. `mplayer myfile.mp3`, and it works as expected. Have tried leaving out the frequency parameter. Just added more detailed code.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51070527
downvote count: 0
score: 1
has body: one way could be to use filter to select only columns with '_Ret' and stack to make it as a serie to be able to use qcut after. # I only copy the two rows with values in _Ret columns print (df.filter(like = '_Ret').stack()) 1 AAPL_Ret -0.07 NFLX_Ret 0.25 INTC_Ret -0.05 2 AAPL_Ret 0.15 NFLX_Ret 0.10 INTC_Ret 0.06 Now you can use qcut on this serie and followed by a unstack and add_suffix to rename: df_Q = (pd.qcut(df.filter(like = '_Ret').stack(), 3, labels=np.arange(3, 0, -1)) .unstack().add_suffix(' Q')) print (df_Q) AAPL_Ret Q NFLX_Ret Q INTC_Ret Q 1 3 1 3 2 1 2 2 Just need to join with the original dataframe as the row's numbers are the same than in the original one. df = df.join(df_Q) giving the expected output
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51069903
has comment: http://stackoverflow.com/comment/89131171
type: Answer
answers question: http://stackoverflow.com/q/51069903

http://stackoverflow.com/a/51120111
has comment: http://stackoverflow.com/comment/106075074
has comment: http://stackoverflow.com/comment/106038380
upvote count: 9
answers question: http://stackoverflow.com/q/51069578
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51069578
has body: It is easier to answer this question in multiple parts to really cover it all: Q: How do I access a serial port on linux/bsd? A: Open it as a file. On linux/bsd a serial connection is established the moment a device is plugged in, and is then listed somewhere under /dev/ (these days, usually as /dev/ttyUSB0). In order to access this connection you simply open it like you would a regular file. Sometimes this is actually good enough to start communicating with the device as modern hardware typically works with all baud rates and default flags. Q: How do I configure a serial/tty device on linux/bsd? A: Set termios flags on the file. If you do need to configure your connection to set things like baud rate, IXON/IXOFF etc, you can do it before even running your program using stty if it is available. Eg. to set the baud rate you could run: stty -F /dev/ttyUSB0 9600. And after this is set up you can just open it as a file and start using it. You can spawn stty from crystal using Process.run if you wanted an easy way to configure the device from your app. I would probably recommend this approach over the next solution.. Q: How do I set termios flags from crystal, without using stty? A: Use the termios posix functions directly. Crystal actually provides FileDescriptor handles with a few common termios settings such as cooked, which means it has minimal termios bindings already. We can start by using the existing code for our inspiration: require "termios" # See above link for contents #Open the file serial_file = File.open("/dev/ttyACM0") raise "Oh no, not a TTY" unless serial_file.tty? # Fetch the unix FD. It's just a number. fd = serial_file.fd # Fetch the file's existing TTY flags raise "Can't access TTY?" unless LibC.tcgetattr(fd, out mode) == 0 # `mode` now contains a termios struct. Let's enable, umm.. ISTRIP and IXON mode.c_iflag |= (Termios::InputMode::ISTRIP | Termios::InputMode::IXON).value # Let's turn off IXOFF too. mode.c_iflag &amp;= ~Termios::InputMode::IXOFF.…
score: 9
type: Answer
has comment: http://stackoverflow.com/comment/106155112

http://stackoverflow.com/comment/89275655
comment on: http://stackoverflow.com/q/51144955
score: 0
type: QuestionComment
type: Comment
has text: Maybe this can help? https://stackoverflow.com/questions/47355526/pandas-series-not-plotting-to-timeseries-chart

http://stackoverflow.com/q/51029653
downvote count: 0
tagged with: django-rest-framework
has title: the queryset attribute of django REST api generic views
favorite count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51030312
score: 4
type: AnsweredQuestion
has body: I am trying to understand the django rest framework generic API views, the documentation tells me that while overriding methods of the generic views, I shouldn't be accessing the queryset attribute directly and instead access the get_queryset() function because apparently the queryset attribute is evaluated only once, what does the get_queryset() do differently? Does the queryset attribute ever get updated?
possible better answer: http://stackoverflow.com/a/51029755
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/51029755
accepted answer: http://stackoverflow.com/a/51030312

http://stackoverflow.com/comment/89111348
score: 0
type: Comment
has text: I think \s and \n in your path is interpreted as space and new line by python. May be that is the error. can you try cwd=r'C:\Users\sherin.sunny\git\ng-ui'
type: AnswerComment
comment on: http://stackoverflow.com/a/51056458

floating-point
tags question: http://stackoverflow.com/q/51093022
tags question: http://stackoverflow.com/q/51014226
type: Tag
tags question: http://stackoverflow.com/q/51018201
tags question: http://stackoverflow.com/q/51045219
tags question: http://stackoverflow.com/q/51050146
tags question: http://stackoverflow.com/q/51023663
tags question: http://stackoverflow.com/q/51014628
tags question: http://stackoverflow.com/q/51126233
tag name: floating-point
tags question: http://stackoverflow.com/q/51089086

http://stackoverflow.com/comment/89076918
has text: @Edward Minnix, because I can only phantom a proper partial application in Python. Without it it's hard to see how to use `re.sub` without lambda in `map`.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51025659
type: Comment

http://stackoverflow.com/a/51093073
has body: It doesn't work because float does a lot more decimal numbers, for more information check this: link, so you should do the below: result = 0 for i in range(3): n = float(input("Enter a value: ")) result = result + n print('{0:.1f}'.format(result)) Output: Enter a value: 1.2 Enter a value: 1.2 Enter a value: 1.2 3.6 Or: result = 0 for i in range(3): n = float(input("Enter a value: ")) result = result + n print('%.1f'%result) Output: Enter a value: 1.1 Enter a value: 1.1 Enter a value: 1.1 3.3 decimal module: Try this: from decimal import Decimal result = 0 for i in range(3): n = Decimal(input("Enter a value: ")) result = result + n print(result) Output: Enter a value: 2.1 Enter a value: 2.1 Enter a value: 2.1 6.3
score: 1
answers question: http://stackoverflow.com/q/51093022
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51093022
type: AcceptedAnswer
type: Answer
downvote count: 1

http://stackoverflow.com/comment/89212214
score: 1
has text: `import sys; print(len(dir(sys)))` is 83. That's the last module I'd want to `import *` on. Please don't suggest that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51112761

http://stackoverflow.com/q/51069380
has body: In the Q-learning algorithm used in Reinforcement Learning with replay, one would use a data structure in which it stores previous experience that is used in training (a basic example would be a tuple in Python). For a complex state space, I would need to train the agent in a very large number of different situations to obtain a NN that correctly approximates the Q-values. The experience data will occupy more and more memory and thus I should impose a superior limit for the number of experience to be stored, after which the computer should drop the experience from memory. Do you think FIFO (first in first out) would be a good way of manipulating the data vanishing procedure in the memory of the agent (that way, after reaching the memory limit I would discard the oldest experience, which may be useful for permitting the agent to adapt quicker to changes in the medium)? How could I compute a good maximum number of experiences in the memory to make sure that Q-learning on the agent's NN converges towards the Q function approximator I need (I know that this could be done empirically, I would like to know if an analytical estimator for this limit exists)?
score: -3
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89129818
downvote count: 3
accepted answer: http://stackoverflow.com/a/51364829
has title: Deep Q learning Replay method Memory Vanishing
type: Question
tagged with: q-learning
upvote count: 0
has comment: http://stackoverflow.com/comment/89154101
tagged with: reinforcement-learning
tagged with: deep-learning
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51364829

http://stackoverflow.com/q/51048294
has answer: http://stackoverflow.com/a/53286481
tagged with: excel
has body: Question No changes to this module that I am aware of. Another separate custom program was installed on the same computer then the errors below started. Suggestions would be appreciated. Errors 3 Traceback (most recent call last): File "log.py", line 100, in error_catcher response = func() File "models.py", line 852, in func instance.main() File "models.py", line 1061, in main data_obj = report.Main(*self.args) File "report.py", line 95, in init self.data_manager() File "report.py", line 113, in data_manager self.equivdod_report('DoD Equiv') File "report.py", line 328, in equivdod_report datas) File "scriptexcel.py", line 230, in equivdod_report ytitle=r'Design Usage (%)' File "excelcreator.py", line 376, in hist__init__ self.title_params(bc.title) File "excelcreator.py", line 767, in title_params baseline=1000 AttributeError: 'list' object has no attribute 'rPr' excelcreator.py (Segments from this module) from openpyxl import Workbook from openpyxl import load_workbook from openpyxl.chart.title import Title import openpyxl.drawing.text as oxldt import os import re import openpyxl import numpy as np import datetime class Excel(): def hist__init__(self, sheet_name, mincol=None, maxcol=None, minrow=None, maxrow=None, bc=None, title=None, ytitle=None, xtitle=None): if bc is None: bc = BarChart() bc.title = title bc.y_axis.title = ytitle bc.legend.position = 't' self.title_params(bc.title) self.title_params(bc.y_axis.title) xval = Reference( self.wb[sheet_name], min_col=mincol-1, min_row=2, max_row=maxrow) data = Reference( self.wb[sheet_name], min_col=mincol, max_col=maxcol, min_row=minrow, max_row=maxrow) return bc, xval, data def title_params(self, title): if title is not None: title.tx.rich.p[0].r.rPr = CharacterProperties( latin=oxldt.Font(typeface='Arial'), baseline=1000 )
has answer: http://stackoverflow.com/a/51198993
type: Question
has title: from openpyxl.chart.title import Title - AttributeError: 'list' object has no attribute
tagged with: javascript
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: openpyxl
tagged with: django
tagged with: python

http://stackoverflow.com/comment/89204870
score: 0
comment on: http://stackoverflow.com/q/51097072
has text: Currently the two scripts are ran independent of each other. I am looking into libraries such as kombu and rq to implement a redis queue. But I am clueless on how one would go about implementing it. Is there any examples that would implement a messaging queue to call a function in the second script that would return it's result to the first one? @PatrickHaugh
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89222007
comment on: http://stackoverflow.com/q/51117963
score: 0
type: Comment
type: QuestionComment
has text: Try `na_values='0'`?

http://stackoverflow.com/a/51128960
answers question: http://stackoverflow.com/q/51128855
score: 0
has body: You are probably looking for a loop similar to this. fig = plt.figure(figsize=(12,8)) axes_list = [] year_names = ["1990", "1995", "2000", "2005", "2010", "2015"] for num, year in enumerate(year_names): MMR = mmr[mmr['Year']==year] axis = fig.add_subplot(2,3,num) axes_list.append(axis) axis.hist(MMR['MMR'], color='darkred', edgecolor='white') axis.set_title('{0} MMR Distribution'.format(year), fontweight='bold', loc='left') axis.spines['left'].set_visible(False) axis.spines['top'].set_visible(False) axis.spines['right'].set_visible(False) axis.spines['bottom'].set_visible(False) axis.tick_params(length=0) axis.set_xlim(0,3000,500) axes_list[-1].text(600, 50, 'Note how the bins \nshifted left over time.', size=12)
type: Answer

http://stackoverflow.com/comment/89116320
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51062947
type: Comment
has text: So `votes` is a list? Then change the `pk__in=votes.keys()` part into `pk__in=votes`, and the `votes_with text` to `votes_with_text = [mapping[k] for k in votes]`.

http://stackoverflow.com/comment/89308366
has text: I've seen other people report Core ML errors / problems when using 1-D convolutions. Core ML doesn't really support them (only Conv2D) and I guess sometimes the conversion doesn't really go correctly.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51161990
score: 0

http://stackoverflow.com/comment/89121466
comment on: http://stackoverflow.com/a/51064608
type: AnswerComment
score: 0
type: Comment
has text: @NoobProgrammer if it's really a `print`, the result in your excel should not be like this (it might just be a representation way of your print function), but to be fair I have never seen something like "break" the dataframe. sorry, not sure I can help you further if in your excel is like this :(

http://stackoverflow.com/q/51129036
duplicate of: http://stackoverflow.com/q/44913275
has answer: http://stackoverflow.com/a/51129118
downvote count: 1
accepted answer: http://stackoverflow.com/a/51129100
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/35078420
has answer: http://stackoverflow.com/a/51129100
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44913275
possible better answer: http://stackoverflow.com/a/51129118
has body: I have a big numpy array of time series data. in each row I have 15 second of acceleration data. such as this: a = [[1,2,3,-1,-2,-3,-4,-1,1,2,1,2,3,2,5], [1,2,3,-1,-2,-3,-4,-1,1,2,1,2,3,2,5], . . [1,2,3,-1,-2,-3,-4,-1,1,2,1,2,3,2,5]] I want to calculate the average value of positive items in each row for example in this case. I want to have: avg = [0.73 , 0.73, ... , 0.73] I don't want to use for and loop in my implementation.
has comment: http://stackoverflow.com/comment/89242978
type: Question
tagged with: numpy
tagged with: mean
duplicate of: http://stackoverflow.com/q/35078420
score: 0
answer count: 2
has title: How can I calculate the mean value of positive values in each row in numpy?
upvote count: 1

http://stackoverflow.com/q/51155627
score: 0
has body: I wanted to write R code which will read and store Error Metrics like MAE,MAPE, R2 etc in a dataframe after each run and compare the results. I am adding more training data in each run and want to crosscheck it how its improving/decreasing the error after I add data by using R code instead of manually checking each time. Any suggestion will be appreciated!
answer count: 1
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51294447
tagged with: python
has title: How to Compare results of Regression ML Model after each RUN programmatically
type: Question
accepted answer: http://stackoverflow.com/a/51294447
type: AnsweredQuestion

http://stackoverflow.com/q/51029426
has comment: http://stackoverflow.com/comment/89051316
linked to: http://stackoverflow.com/q/4760215
has comment: http://stackoverflow.com/comment/89051235
tagged with: batch-file
answer count: 1
tagged with: cmd
linked to: http://stackoverflow.com/q/4415134
tagged with: terminal
type: UnansweredQuestion
tagged with: io
tagged with: python
has body: I am trying to do a complexity analysis of the stanford parser. To do so, I am starting the program via a cmd file, so therefore if I use subprocess.check_output, my python program will give me the commandline arguments I am using. The parser prints its own runtime on the commandline, so therefore I have to actually come up with something which reads out what the program I have started printed on the commandline. subprocess.check_output("path-to-cmd", shell=True tldr: This gives me the cmd-files output, I want what the started program printed in the terminal. As my question was marked as a duplicate, I want the output of a program that I have started via the cmd, if I use subproces.check_output, it will simply give me the content of my cmd, and not the output of the java program I have run. I want to capture what the java program wrote to the terminal.
has title: Capturing the output of a program started via cmd script
has answer: http://stackoverflow.com/a/51035867
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89052327

http://stackoverflow.com/a/51095117
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51085083
has body: readlines does not remove newline from the line. So as you can see in the traceback, you are trying to create a file named abc.txt\n, what is not possible on many file systems, and mainly, it's not what you want. Trim the trailing new lines from file_path: for file_path in stdout.readlines(): file_path = file_path.rstrip() file_name = file_path.split('/')[-1] # ... Though you would have saved yourself lot of troubles, had you used a pure SFTP solution, instead of hacking it by executing a remote find command (what is a very fragile solution, as hinted in comments by @CharlesDuffy). See List files on SFTP server matching wildcard in Python using Paramiko. Side note: Do not use AutoAddPolicy. You lose security by doing so. See Paramiko "Unknown Server".
answers question: http://stackoverflow.com/q/51085083
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51099916
downvote count: 4
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51099985
score: -4
has comment: http://stackoverflow.com/comment/89187144
has comment: http://stackoverflow.com/comment/89187120
has title: How can i check dictionary value is available in list of dictionary in python?
has body: I want to check whether the value of a exists in the value b or not a = [{ "shopid": "store4400013","prd_category": "Chicken","product_id":"4359197","prd_name":"Chicken chilli","prod_type":"Non_Veg","prd_amt":"100.0"}] b = [{'shopid': 'store4400013', 'prd_category': 'Chicken', 'product_id': 4359197, 'prd_name': 'Chicken chilli', 'prod_type': 'Non_Veg', 'prd_amt': 100.0, 'image': '/media/abhishek/e/Moneypay/merchant/mxuserimage/menu_3418906783.png'}, {'shopid': 'store4400013', 'prd_category': 'Chicken', 'product_id': 6911213, 'prd_name': 'Chicken kadai', 'prod_type': 'Non_Veg', 'prd_amt': 250.0, 'image': '/media/abhishek/e/Moneypay/merchant/mxuserimage/menu_3890935432.png'}]
has comment: http://stackoverflow.com/comment/89187245
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/89187080
tagged with: django-rest-framework

http://stackoverflow.com/comment/89121909
comment on: http://stackoverflow.com/a/51053569
score: 0
type: AnswerComment
has text: thanks let see what can I do this method in tensorflow
type: Comment

http://stackoverflow.com/comment/89051713
has text: Trying to understand: do you want to match a string of the format `${abc.xyz.install.ClassDir}\abc\xyz\xyz.class` where `abc` and `xyz` can both be any alphanumeric characters or underscores?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51029685

c++
tags question: http://stackoverflow.com/q/51036086
tags question: http://stackoverflow.com/q/51076598
tags question: http://stackoverflow.com/q/51070398
tags question: http://stackoverflow.com/q/51108008
tags question: http://stackoverflow.com/q/51041975
tags question: http://stackoverflow.com/q/51036850
tags question: http://stackoverflow.com/q/51058304
type: Tag
tags question: http://stackoverflow.com/q/51156263
tags question: http://stackoverflow.com/q/51107534
tags question: http://stackoverflow.com/q/51085435
tags question: http://stackoverflow.com/q/51144540
tags question: http://stackoverflow.com/q/51037886
tags question: http://stackoverflow.com/q/51040572
tags question: http://stackoverflow.com/q/51058617
tags question: http://stackoverflow.com/q/51053565
tags question: http://stackoverflow.com/q/51027493
tags question: http://stackoverflow.com/q/51011920
tags question: http://stackoverflow.com/q/51059843
tag name: c++
tags question: http://stackoverflow.com/q/51152664
tags question: http://stackoverflow.com/q/51017450
tags question: http://stackoverflow.com/q/51093968
tags question: http://stackoverflow.com/q/51162846

http://stackoverflow.com/comment/89192862
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51102609
has text: No I checked by df['like'].astype(int)

http://stackoverflow.com/comment/89266679
has text: yes , K and p both can be variable .
comment on: http://stackoverflow.com/a/51140405
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51062783
has body: This is by design. The conceptors of fileinput thought that there were use cases where reading from stdin would be non sense and just provided a way to specifically add stdin to the list of files. According to the reference documentation: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. Just keep your code and use: generic_user% cat my_data.csv | python3 my_script.py - myarg1 to read stdin before myarg1 file or if you want to read it after : ... python3 my_script.py myarg1 -
score: 0
answers question: http://stackoverflow.com/q/51061081
type: Answer

http://stackoverflow.com/comment/89136207
comment on: http://stackoverflow.com/a/51073232
score: 0
type: Comment
has text: @Rishav Thanks for pointing that out. I improved the regex by making it more specific.
type: AnswerComment

http://stackoverflow.com/q/51078210
tagged with: python
has answer: http://stackoverflow.com/a/51078264
duplicate of: http://stackoverflow.com/q/1228299
type: AnsweredQuestion
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51078264
has title: Why can't we change a particular value of a string in python
has comment: http://stackoverflow.com/comment/89145106
answer count: 2
downvote count: 4
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/51078251
has body: The string in python behaves similar to list. Then why can't we change value using assignment operator. Example: name = 'whatever' why can't we do assignment like name[0] = 'k' If we need to make a change like this, how can we do that?
has answer: http://stackoverflow.com/a/51078251
linked to: http://stackoverflow.com/q/1228299
score: -4

http://stackoverflow.com/q/51117205
possible better answer: http://stackoverflow.com/a/51118091
has body: I have a RDD of (key, (val1,val2)). For this rdd, I would like to apply reduceByKey function and my requirement is to find minimum of val2 against a single key and also extract the val1 of the resulted minimum val2. Eg: (1,(a,4)),(2,(b,3)),(1,(c,2)),(2,(d,1)) In this I wanted the result set as (1,(c,2)),(2,(d,1)) I have in my mind below python code, but here I am getting the first val1, not the val1 corresponding to minimum val2. rdd2 = rdd1.map(lambda x:(x[0],(x[1],x[3]))) rdd3 = rdd2.reduceByKey(lambda x,y:(x[0],min(x[1],y[1]))) Please help me to modify the code inorder to get my required result.
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51120192
downvote count: 2
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/57270121
type: AnsweredQuestion
tagged with: pyspark
has answer: http://stackoverflow.com/a/51118091
accepted answer: http://stackoverflow.com/a/51120192
score: -1
has title: reduceByKey in spark python with tuple values
answer count: 3
tagged with: apache-spark

hex-editors
tags question: http://stackoverflow.com/q/51126859
tag name: hex-editors
type: Tag

http://stackoverflow.com/q/51159879
has comment: http://stackoverflow.com/comment/89315098
has title: Iterating in dropdown-menu
has answer: http://stackoverflow.com/a/51266910
has comment: http://stackoverflow.com/comment/89375545
has comment: http://stackoverflow.com/comment/89364468
has comment: http://stackoverflow.com/comment/89364206
answer count: 1
has comment: http://stackoverflow.com/comment/89364193
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89308320
has body: i'm having some troubles with trying to get a list in python.. I'm using Selenium Web Driver, Chrome specifically, and i have the next "button" : Nope text1 text2 text3 So.. i have tried to use Select.class of Selenium Wd but, it's a button, and the class can't be used there... tried using it on the but it can't use Select neither... Can't use smh like: dropdoun = Select(driver.find_element_by_id('ID')) for elm in dropdoun{ print(elm.text())} Tried to figure a way to iterate through items... but i didn't get anything i figured a way to click by xPath but, it doesn't work to me, cause text1, text2, text3 and so changes the order everytime you open the web Any idea? EDIT: What i need here, is to iterate trough each item, and select the one that match with "text1", "text2" or "text3...
score: 0
tagged with: selenium
type: Question

http://stackoverflow.com/q/51078195
tagged with: apache-spark-sql
score: 1
tagged with: pyspark
type: Question
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/89155773
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89145123
has comment: http://stackoverflow.com/comment/89146316
has answer: http://stackoverflow.com/a/59266923
tagged with: python
has comment: http://stackoverflow.com/comment/89153837
has comment: http://stackoverflow.com/comment/104715328
has comment: http://stackoverflow.com/comment/89158601
type: UnansweredQuestion
has body: I have a table like this: row | key | json 0 | a | {'something':{'a':1}} 1 | b | {'something':{'a':2, 'b':3 }} And I would like to retrieve for the values in the json defined in the key column: row | value 0 | 1 // from $.something.a 1 | 3 // from $.something.b on hive one can do select get_json_object(json, concat("$.something.", key) from table; and it would return the proper value. However, on pyspark, I didn't find a way to replicate this behaviour, it doesn't seem to be able to build the path base on the column. I tried context.table("table").select( get_json_object(F.col("json", concat("$something.", F.col("key")) ); and it tells me "Column is not iterable". However, using just concat works fine: context.table("table") .select( concat("$something.", F.col("key").alias(path) ); row | path 0 | $.something.a 1 | $.something.b I was able to do it using an UDF, but is there any way to acomplish this with PySpark out of the box?
upvote count: 1
has title: get_json_object with path based on row?

http://stackoverflow.com/q/51097460
answer count: 2
has title: how to download utf-8 encoded content with cyrillic
tagged with: encoding
has comment: http://stackoverflow.com/comment/89182621
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89182650
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89182625
type: UnansweredQuestion
downvote count: 1
tagged with: http
has body: Please show me the way to get correct utf-8 content with cyrillic. I use next code snippet: from http.client import HTTPSConnection conn = HTTPSConnection('lifehacker.ru') conn.request('GET', '/') resp = conn.getresponse() st = resp.read() content = ''.join(map(chr, st)) conn.close() print(content) As result I get content with some like: &lt;title&gt;ÐÐ°Ð¹ÑÑÐ°ÐºÐµÑ - ÑÐ¾Ð²ÐµÑÑ Ð¸ How to get correct cyrillic symbols?
has answer: http://stackoverflow.com/a/51097544
has answer: http://stackoverflow.com/a/51097746
type: Question

http://stackoverflow.com/comment/89077863
score: 1
comment on: http://stackoverflow.com/q/51043379
has text: Try `string="'10.240.165.151'"` (extra quotes)
type: Comment
type: QuestionComment

network-programming
tags question: http://stackoverflow.com/q/51163173
tags question: http://stackoverflow.com/q/51059607
tags question: http://stackoverflow.com/q/51045222
tags question: http://stackoverflow.com/q/51051996
tags question: http://stackoverflow.com/q/51071020
tags question: http://stackoverflow.com/q/51090637
type: Tag
tags question: http://stackoverflow.com/q/51110497
tag name: network-programming
tags question: http://stackoverflow.com/q/51034238
tags question: http://stackoverflow.com/q/51114554
tags question: http://stackoverflow.com/q/51144308
tags question: http://stackoverflow.com/q/51135332
tags question: http://stackoverflow.com/q/51103285

http://stackoverflow.com/comment/89267157
type: Comment
type: QuestionComment
has text: @coldspeed, The issue is I don't want a moving average. I want only the average of 1st four weeks
score: 0
comment on: http://stackoverflow.com/q/51141366

http://stackoverflow.com/q/51038493
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51039022
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89068615
has body: Explain this code to me. This is a program to print integer inputs as outputs in letters. if i input 35 then output will be thirty five. i understood most of it but want to know how tens take the value from twenty thirty forty fifty sixty seventy eighty ninety The code is: num = int(input("Enter the number:")) numbers = ("zero one two three four five six seven eight nine".split()) numbers.extend("ten eleven twelve thirteen fourteen fifteen sixteen".split()) numbers.extend("seventeen eighteen nineteen".split()) numbers.extend(tens if ones == "zero" else (tens + " " + ones) for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split() for ones in numbers[0:10]) print(numbers[num])
downvote count: 7
type: Question
linked to: http://stackoverflow.com/q/17006641
has answer: http://stackoverflow.com/a/51039022
has comment: http://stackoverflow.com/comment/89068979
has title: Nested for loops extending existing list
answer count: 1
has comment: http://stackoverflow.com/comment/89069026
score: -6

http://stackoverflow.com/q/51128996
has comment: http://stackoverflow.com/comment/89242912
tagged with: text-files
has answer: http://stackoverflow.com/a/51135307
tagged with: extract
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89242844
has answer: http://stackoverflow.com/a/51129027
type: Question
answer count: 2
has title: Extracted text comes out as a single line
has comment: http://stackoverflow.com/comment/89248306
has body: I'm wanting to extract ALL text between points A and B which repeats itself X amount of times throughout the text document and looks like: A Line 1 Line 2 Line 3 Line 4 . . . B Using the code: results = [] results = False for line in lines: line = line[1:-1] if "B" in line: results = False elif results == True: orbitals.append(line) elif "A" in line: results = True I am able to extract the desired text but it outputs as a single linear line/row of text ie. A Line 1 Line 2 Line 3 Line 4 B with each time it is repeated in the text also on the same line. Ideally I want it to output exactly how it is presented in the textfile that I am extracting it from (and if possible in columns next to each other in order for each time it is repeated through the text).
score: 0

http://stackoverflow.com/comment/89050678
comment on: http://stackoverflow.com/q/51028364
score: 0
type: Comment
has text: Thanks. I will try that out. I added some clarification to the OP.
type: QuestionComment

http://stackoverflow.com/a/51022504
has comment: http://stackoverflow.com/comment/89037567
has body: You're not running ping again each time you call wait() or poll() - you're just getting the result from the first run. As such, if it failed, the result is going to remain as a failure every time you call poll().
has comment: http://stackoverflow.com/comment/89037727
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51022298

http://stackoverflow.com/a/51030612
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89056979
type: Answer
has body: Seems like you're looking to use pd.concat instead of pd.join (seeing as you even called your variable fx_news_concatenate!). Try: fx_news_concatenate = pd.concat([macronews,fx_date],axis=1,join='inner') The "axis=1" indicates you want to concatenate column-wise (not row-wise) and "join=inner" specifies how you want to handle the axis indices. Hope it helps :) For more details, you can refer the Pandas documentation here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html Here's a good answer to the difference between merge, join and concat operations: Difference(s) between merge() and concat() in pandas
has comment: http://stackoverflow.com/comment/89057094
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51030338
answers question: http://stackoverflow.com/q/51030338
has comment: http://stackoverflow.com/comment/89053915
upvote count: 1
has comment: http://stackoverflow.com/comment/89053745

http://stackoverflow.com/q/51027943
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89049139
has comment: http://stackoverflow.com/comment/89048571
type: Question
has comment: http://stackoverflow.com/comment/89049315
tagged with: sys.path
has body: I use the following command to install modules in home/.local since I dont have admin rights pip install --install-option="--prefix=$HOME/.local" package_name it is installed in my home dir and other cant run my script, so I move them to python lib/site-packages directory where others have access to. Then I add sys.path.insert(0, path_to_lib) in my script to import that module. This is how I install and use modules in my script and it always works fine. But when I did the same for a module "marrow.mailer", my script shows No module named marrow.mailer not sure why, the lib/site-packages folder does have that module. Please help me in finding solution for this. Thanks.
score: 0
has comment: http://stackoverflow.com/comment/89050652
tagged with: python
has title: python cant find module in sys.path

http://stackoverflow.com/comment/89158293
score: 0
type: QuestionComment
type: Comment
has text: @tobias_k Updated my question accordingly. `ISO 8601` allows for several different time formats.
comment on: http://stackoverflow.com/q/51084316

http://stackoverflow.com/comment/89037585
comment on: http://stackoverflow.com/a/51022553
score: 0
type: AnswerComment
has text: Thank you for the reply! Could you please clarify why `list(map(...))` is equivalent to `append()` rather than to setting values in a preallocated list?
type: Comment

http://stackoverflow.com/comment/89151884
type: Comment
type: QuestionComment
has text: You should only bind to a *local* address. If you want to accept connections through any interface you can use the special IN_ADDR_ANY 0.0.0.0 address; `serversocket.bind(("0.0.0.0", port))`
score: 2
comment on: http://stackoverflow.com/q/51081741

http://stackoverflow.com/q/51050948
favorite count: 0
has comment: http://stackoverflow.com/comment/89278793
has comment: http://stackoverflow.com/comment/89207174
has comment: http://stackoverflow.com/comment/89270628
has comment: http://stackoverflow.com/comment/89194071
upvote count: 3
has comment: http://stackoverflow.com/comment/89093981
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/51197055
has comment: http://stackoverflow.com/comment/89309763
tagged with: mysql-python
has comment: http://stackoverflow.com/comment/89237728
tagged with: python
has comment: http://stackoverflow.com/comment/89097995
has comment: http://stackoverflow.com/comment/89309815
has answer: http://stackoverflow.com/a/51171014
has comment: http://stackoverflow.com/comment/89306367
has comment: http://stackoverflow.com/comment/89236053
has comment: http://stackoverflow.com/comment/110820312
has comment: http://stackoverflow.com/comment/89097620
type: AnsweredQuestion
score: 3
has body: I am trying to run my Django app on Google App Engine SDK (locally) inside a virtualenv with MySQL as a database. Everything in my requirements.txt file is installing perfectly. When I start the Google App Engine SDK environment, it throws me a nasty error that seems common, but Stack Overflow doesn't have any examples of solving this within Google App Engine SDK yet. Here is my work flow from the root dir of my project... virtualenv venv &amp;&amp; mkdir lib source venv/bin/activate pip install -r requirements.txt -t lib/ &amp;&amp; pip install -r requirements.txt When I run the following command to start up the SDK.... dev_appserver.py app.yaml I get the following error in my traceback... File "/Users/username/Repositories/projectname/lib/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/username/Repositories/projectname/lib/django/db/utils.py", line 115, in load_backend INFO 2018-06-26 20:09:30,812 module.py:846] default: "GET /_ah/start HTTP/1.1" 500 - return import_module('%s.base' % backend_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/username/Repositories/projectname/lib/django/db/backends/mysql/base.py", line 30, in &lt;module&gt; 'Did you install mysqlclient or MySQL-python?' % e ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql. Did you install mysqlclient or MySQL-python? My requirements.txt Django==1.11.8 djangorestframework==3.8.2 facebook-sdk oauth2client==2.0.1 google-api-python-client==1.6.2 facebookads==2.11.1 httplib2==0.10.3 enum==0.4.6 requests-toolbelt==0.8.0 google-cloud-storage==1.6.0 google-resumable-media==0.3.1 google-auth requests==2.18.0 lxml==3.8.0 pycrypto==2.6.1 MySQL-python==1.2.5 Contents of lib/ I am calling MySQLdb in my app.yaml as well... libraries: - name: MySQLdb version: "latest" Contents of appengine_config.py # [START vendor] from google.a…
possible better answer: http://stackoverflow.com/a/51197055
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/89278505
has comment: http://stackoverflow.com/comment/89270108
answer count: 2
has comment: http://stackoverflow.com/comment/89309129
has title: Google App Engine SDK: ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql
downvote count: 0
has comment: http://stackoverflow.com/comment/89324654
has comment: http://stackoverflow.com/comment/89093230
tagged with: virtualenv
accepted answer: http://stackoverflow.com/a/51171014
has comment: http://stackoverflow.com/comment/89307935

http://stackoverflow.com/q/51135131
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51136640
tagged with: python
linked to: http://stackoverflow.com/q/26738648
has body: #Each pic's size is 1280x720 import time from multiprocessing import Process,JoinableQueue,Queue,Value **def create_row(M, q_row,y_val):** #creating lines. len:720 len of each line_len=720 col_len=1280 for i in range(line_len): q_row.put(M[(i*col_len):((i+1)*col_len)]) **def create_col(M, q_col,x_val):** #creating cols col_len=1280 line_len=720 for i in range(col_len): l = list() for j in range(line_len): l.append(M[j*line_len + i]) q_col.put(l) **def main():** #creating row and col Queue q_row=JoinableQueue() q_col=JoinableQueue() x_val=Value('i',-1) y_val=Value('i',-1) p1=Process(target=create_row,args=(M,q_row,y_val)) p2=Process(target=create_col,args=(M,q_col,x_val)) q_row.join() q_col.join() p1.start() p2.start() p1.join() p2.join() Now to the problem: M is a list in size of 1280*720, which represent a picture. We want to divide the list into rows and cols, so we can go through the picture faster. We tried few things: Without joining the processes: in that scenario only one of the functions will work (We will get either the row_q only or the col_q) With joining the process:: The program will freeze. What should I do?
tagged with: multiprocessing
type: Question
has title: Can't use join on big Queue multiprocessing-Python

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

http://stackoverflow.com/a/51098795
has comment: http://stackoverflow.com/comment/89186302
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51098715
has comment: http://stackoverflow.com/comment/89188794
has body: I hope I understand your question correctly: There is a way to get probabilities. random forests in scikit-learn as well as many other classifiers provide a predict_proba function. using that function you get an array with the probabilities for the specific classes representing a specific column. So in your example you could write: predictions = classifier.predict_proba(data)
answers question: http://stackoverflow.com/q/51098715
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer

http://stackoverflow.com/q/51106669
has comment: http://stackoverflow.com/comment/89244304
tagged with: python
tagged with: linear-programming
type: AnsweredQuestion
tagged with: mathematical-optimization
has comment: http://stackoverflow.com/comment/89212843
has comment: http://stackoverflow.com/comment/89202401
has answer: http://stackoverflow.com/a/51142755
type: Question
accepted answer: http://stackoverflow.com/a/51142755
has body: Let say I have a variable Income per month, over a period of 1 to 12 months my total Income is 1700 $, I want to minimize tax on this income. How should I write this objective function in abstract algebra form Z = 1000 * 0.05 + 500 * 0.10 + 200 * 0.15 basically I want to put slab wise tax on total income, any suggestion ? I have three slabs 0-1000, 1000-1500, >1500 tax per slab 0.05, 0.10, 0.15
score: 0
has title: How to write cost slabs in objective function of Linear Programming?
has comment: http://stackoverflow.com/comment/89244340
answer count: 1

http://stackoverflow.com/comment/89255204
type: Comment
comment on: http://stackoverflow.com/a/51102285
has text: Sorry, my bad. I know from the example on InfluxDB website that that format is accepted but I need to get it down to milliseconds. Sorry for any confusion. I'm creating the time on the fly within a python script.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51057852
tagged with: date
has body: Inside of models I have: The Hotel Name The price for each night. models.py: class Hotel_Database(models.Model): hotel_name = models.CharField(max_length=20) class Hotel_Date_Price(models.Model): hotel = models.ForeignKey(Hotel_Database, on_delete=models.CASCADE , related_name='hotel') checkin = models.DateField(default= datetime.date.today()) checkout = models.DateField(default=datetime.date.today() + datetime.timedelta(1)) price = models.IntegerField() views.py: import datetime x = Hotel_Database.objects.get(id=1) #the price for the night of June 26th: Hotel_Date_Price.objects.create(hotel = x, checkin= datetime.date(2018, 6, 27), checkout=datetime.date(2018, 6,28), price=50).save() #the price for the night of June 27th: Hotel_Date_Price.objects.create(hotel = x, checkin= datetime.date(2018, 6, 28), checkout=datetime.date(2018, 6,29), price=50).save() Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__lte=datetime.date(2018, 6, 27), hotel__checkout__gte=datetime.date(2018, 6, 28)) #results: &lt;QuerySet [&lt;Hotel_Database: Shangri-La&gt;]&gt; Now here is what happens when I try to filter through more than one night: Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__lte=datetime.date(2018, 6, 27), hotel__checkout__gte=datetime.date(2018, 6, 29)) #results: &lt;QuerySet []&gt; # it returns an empty list I am basically trying to change the price of each night
score: 0
has comment: http://stackoverflow.com/comment/89105967
answer count: 1
has answer: http://stackoverflow.com/a/51057911
type: UnansweredQuestion
tagged with: python
has title: Django: how do you filter with dates and a foreign key
tagged with: django
type: Question

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/51066682
tags question: http://stackoverflow.com/q/51156402
tags question: http://stackoverflow.com/q/51100005
type: Tag
tags question: http://stackoverflow.com/q/51048266
tags question: http://stackoverflow.com/q/51132703
tag name: pdf
tags question: http://stackoverflow.com/q/51047220
tags question: http://stackoverflow.com/q/51067400
tags question: http://stackoverflow.com/q/51076717
tags question: http://stackoverflow.com/q/51138887
tags question: http://stackoverflow.com/q/51115171
tags question: http://stackoverflow.com/q/51105333
tags question: http://stackoverflow.com/q/51107368

http://stackoverflow.com/comment/89210720
comment on: http://stackoverflow.com/q/51111757
has text: @Blckknght Second intention is that A itself is inherited from an outside library. Since that library use double underscore to hide similar attributes, I think it favorable to inherit this convention too.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89175920
score: 0
type: AnswerComment
type: Comment
has text: That seems unlikely, but maybe possible if you are on something like cygwin, but I don't know
comment on: http://stackoverflow.com/a/51092378

trace
tag name: trace
type: Tag
tags question: http://stackoverflow.com/q/51159120

http://stackoverflow.com/q/51146012
has comment: http://stackoverflow.com/comment/89285042
upvote count: 1
tagged with: python
has body: We're working on an app and were collecting stats from it. Initially we were dumping stats on googl sheets so we downloaded it as csv and uploaded the data to bigquery. We succesfully uploaded data with the schema we wanted. When we are re-running the app and added a step to upload it to the test table which contains the initial data, gbq tells us the following error: Please verify that the structure and data types in the DataFrame match the schema of the destination table. I tried comparing the table with the data being uploaded. a.dtypes (bigquery table) Out[16]: start_timestamp datetime64[ns] name object url object email object destination object database object update_timestamp datetime64[ns] query_info object query_runtime float64 error_log object dtype: object upload_df.dtypes (df being uploaded) Out[17]: start_timestamp datetime64[ns] name object url object email object destination object database object update_timestamp datetime64[ns] query_info object query_runtime float64 error_log object dtype: object It's weird that they have the same schema but pandas gbq is giving an error. Any help or direction to resolve this issue is appreciated!
score: 1
tagged with: google-bigquery
type: Question
has title: Pandas to_gbq method DataFrame schema doesn't match to the table
tagged with: automation
tagged with: pandas
tagged with: data-warehouse
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51164769
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51163720
answers question: http://stackoverflow.com/q/51163720
has body: You can read python documentation -> setdefault: class MyClass: pass key = 'test python' item = MyClass() d = {} item = d.setdefault(key, item) It`s more pythonic!!!!
upvote count: 1
score: 1

http://stackoverflow.com/comment/89295140
comment on: http://stackoverflow.com/a/51155135
type: AnswerComment
has text: Ah, that's clever! Thanks :D
score: 1
type: Comment

http://stackoverflow.com/a/51034398
downvote count: 0
type: Answer
has body: Try it import itertools lst = ['d', '112', 'b', 'c', 'i', 'a', 'e'] for comb in itertools.combinations(lst, 2): print(comb)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51034264

http://stackoverflow.com/q/51093751
has title: AI/Deep Learning approach to judge reference in paper?
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/50946163
has body: This is a real part of my work. In order to keep students' paper follow given format standard, I have to judge the reference type in students' papers, separate its items(author, title, magazine name, year, etc), then give modification advice if some item is missing. It is tedious, so after some years' of work-by-people, I get too tired. I think to do it by programming. In a paper, many kinds of references will be citation, for example, Journal paper, Dissertation paper, book and so on. They have different format. On the other hand, if I submit a paper to different journal, maybe I have to met different format I am looking for algorithms ( you can read my previous try which use regex. but this obviously will fail when more diverse formats are used. python re can&#39;t find this grouped name ) which can judge a paper whether is journal, dissertation, book ... separate author, paper title, book name, publisher, year, and so on. Please note, there may be punctuation in author, paper title, book name if there are many authors, then tell each name. Because often we only need at most 3 authors, if more are found, we should use "et al" if some information is missing, then give hint for completeness the following is just an example for kinds of format for journal paper. We can find it is hard to understand them by simple string match. [example 1] Duan,C., X.Meng, C.Tu. How to make local image features more efficient and distinctive[J].IET Computer Vision,2008,2(3):178-189. we can find that there are 3 authors("Duan,C.", "X.Meng", "C.Tu") whose names are separated by comma, however comma are also used in one person name("Duan,C."). So it is actually hard to use regex to judge peoples' name [example 2] Harris,C. &amp; M.Stephens. A combined corner and edge detector[J]. Alvey Vision Conference,1988,5(7):147-151. &amp; is used to separate two names, however we can find maybe someone else write it as Harris,C., M.Stephens If we use MLA format( Autocite a Journal in MLA Format) [e…
favorite count: 0
tagged with: pattern-matching
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: artificial-intelligence
score: 1

http://stackoverflow.com/comment/89349328
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51116553
type: AnswerComment
has text: I have a database named login which has a table username and pass and another database named class which contains the sections table like (a,b,c..Like in college we have sections named after alpha s right.). When i run the code to select the students from a particular section by running the entire program i get the above errors but when i run the particular code it doesnt show any error

http://stackoverflow.com/comment/89048173
comment on: http://stackoverflow.com/a/51027749
score: 0
type: AnswerComment
has text: Thanks -- rookie mistake!
type: Comment

http://stackoverflow.com/a/51109464
has body: I think I should delete \ in the line target = target_dir + os.sep + \time.strftime('%Y%m%d%H%M%S') + '.zip' I have a misunderstanding of os.sep
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51109254

python-imaging-library
tags question: http://stackoverflow.com/q/51073292
tags question: http://stackoverflow.com/q/51084602
tags question: http://stackoverflow.com/q/51093667
tags question: http://stackoverflow.com/q/51100340
tags question: http://stackoverflow.com/q/51053725
tags question: http://stackoverflow.com/q/51024386
tags question: http://stackoverflow.com/q/51037333
tags question: http://stackoverflow.com/q/51151823
tags question: http://stackoverflow.com/q/51014439
tags question: http://stackoverflow.com/q/51163040
tags question: http://stackoverflow.com/q/51158106
tags question: http://stackoverflow.com/q/51164713
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/51118551
tags question: http://stackoverflow.com/q/51022577
tags question: http://stackoverflow.com/q/51164887
tags question: http://stackoverflow.com/q/51048266
type: Tag
tags question: http://stackoverflow.com/q/51164645
tags question: http://stackoverflow.com/q/51154279
tags question: http://stackoverflow.com/q/51103944

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

http://stackoverflow.com/q/51079559
linked to: http://stackoverflow.com/q/51030163
tagged with: uint16
tagged with: endianness
has title: numpy array convert uin8 lsb to uint16 msb
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51080035
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: list
score: 1
has body: I already asked here but I just wonder if this could not be done natively with numpy because I will use numpy later anyway with cv2 that reads numpy arrays. Background is, I read 13 chunks of 13680 bytes from a usb camera until I got 177840 bytes, that is one raw frame. I do this by appending the chunks: frame = dev.read(0x81, 0x3570, tout) frame += dev.read(0x81, 0x3570, tout) ... The list is then filled with 0-255 values and two of that values shall form one 0-65535 value. So my question is how can I convert that (I assume) uint8 LSB list to an uint16 numpy array with half size of the list. Lets assume I have that list: list = [3,103,3,103] I then want a numpy array with: [26371, 26371] or is there a way to straight away fill a numpy array with 13 reads from my usb device so that it has 177840/2 uint16 values at the end?
type: Question
tagged with: numpy

http://stackoverflow.com/comment/89123583
type: Comment
has text: @MohammedKashif I dont' understand your answer about pre-computed distances. How can we avoid to find centers while we need to find the closest center for each point. Have you any formula to find center with only pre-computed distances?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51059191

http://stackoverflow.com/comment/89314642
type: Comment
comment on: http://stackoverflow.com/a/51156431
type: AnswerComment
has text: thanks a lot @ncfirth. This works like a charm and super fast!
score: 0

http://stackoverflow.com/comment/89112909
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51056458
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173876/discussion-between-mufeed-and-sherin-sunny).

http://stackoverflow.com/q/51101891
tagged with: missing-data
has answer: http://stackoverflow.com/a/51103703
downvote count: 0
favorite count: 0
has body: So I have a dataframe like so: [5232 rows x 2 columns] 0 2 0 2018-02-01 00:00:00 2018-02-01 00:00:00 435.24 2018-02-01 00:30:00 2018-02-01 00:30:00 357.12 2018-02-01 01:00:00 2018-02-01 01:00:00 301.32 2018-02-01 01:30:00 2018-02-01 01:30:00 256.68 2018-02-01 02:00:00 2018-02-01 02:00:00 245.52 2018-02-01 02:30:00 2018-02-01 02:30:00 223.20 2018-02-01 03:00:00 2018-02-01 03:00:00 212.04 2018-02-01 03:30:00 2018-02-01 03:30:00 212.04 2018-02-01 04:00:00 2018-02-01 04:00:00 212.04 2018-02-01 04:30:00 2018-02-01 04:30:00 212.04 2018-02-01 05:00:00 2018-02-01 05:00:00 223.20 2018-02-01 05:30:00 2018-02-01 05:30:00 234.36 And what I can currently do is replace a portion of values (say 10% at random with NaN: df_missing.loc[df_missing.sample(frac=0.1, random_state=100).index, 2] = np.NaN What I'd like to be able to do, is do the same thing, but with random blocks of size x, say 10% of the data should be blocked NaN. For example, if the block size was 4, and and the proportion was 30%, the above dataframe might look like: [5232 rows x 2 columns] 0 2 0 2018-02-01 00:00:00 2018-02-01 00:00:00 435.24 2018-02-01 00:30:00 2018-02-01 00:30:00 357.12 2018-02-01 01:00:00 2018-02-01 01:00:00 NaN 2018-02-01 01:30:00 2018-02-01 01:30:00 NaN 2018-02-01 02:00:00 2018-02-01 02:00:00 NaN 2018-02-01 02:30:00 2018-02-01 02:30:00 NaN 2018-02-01 03:00:00 2018-02-01 03:00:00 212.04 2018-02-01 03:30:00 2018-02-01 03:30:00 212.04 2018-02-01 04:00:00 2018-02-01 04:00:00 212.04 2018-02-01 04:30:00 2018-02-01 04:30:00 212.04 2018-02-01 05:00:00 2018-02-01 05:00:00 223.20 2018-02-01 05:30:00 2018-02-01 05:30:00 234.36 I've figured out I can get the number of blocks with: number_of_samples = int((df.shape[0] * proporition) / block_size) But I can't figure out how to actually create the missing blocks. I've seen this question, which is helpful but it has two caveats: It doesn't modify the original dataframe with NaN values, just returns samples. There's no guarantee the samples won't overlap (which I…
has title: Generate missing blocks of data in pandas dataframe
possible better answer: http://stackoverflow.com/a/51103703
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51102982
tagged with: python
upvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51102982
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/45938227

http://stackoverflow.com/q/51083887
has title: Update Related Models When Deleting DJANGO
type: Question
has comment: http://stackoverflow.com/comment/89156317
has answer: http://stackoverflow.com/a/51086850
answer count: 2
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89156077
has body: I have a model that can be deleted in my app - Project User I want when the model is deleted every other Model that relates to it must be updated to a system user - so update all the references to this Project User to another user. Is that possible?
tagged with: django
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51084443

http://stackoverflow.com/a/51064692
score: 1
has body: If performance is more important than elegance, a classic algorithm can do the trick. The following code will never win a beauty contest, but it's about 350 - 400% more performant (on my ThinkPad) than the, admittedly, much nice list comprehension approach. The gap will grow with the size of your data set, as it's working in more primitive datatype (lists) and converts back to pandas in the end. temp_list = list() for serie in df: elements = list() for element in serie: for word in element.split(): if word in stop_words: element = element.replace(f' {word} ', ' ') elements.append(element) temp_list.append(elements) df = pd.Series(temp_list) print(df) The choice is your up to you :)
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89162036
answers question: http://stackoverflow.com/q/51062770
has comment: http://stackoverflow.com/comment/89160988
upvote count: 1

http://stackoverflow.com/q/51052022
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: iframe
tagged with: selenium
has comment: http://stackoverflow.com/comment/89100206
type: Question
has comment: http://stackoverflow.com/comment/89100793
has title: Timing out when trying to switch to iframe with Selenium for Python
has comment: http://stackoverflow.com/comment/89100575
has comment: http://stackoverflow.com/comment/89100728
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89101603
has comment: http://stackoverflow.com/comment/89101650
has comment: http://stackoverflow.com/comment/89101962
has body: When I have selenium click a button on the webpage, a popup opens and I've tried a few ways to switch to the iframe popup but I'm using WebDriverWait(driver, 10).until() and after 10 seconds it will just timeout. I'm guessing it never recognizes the iframe and I'm sure it must be because I'm having it look for it incorrectly. Here is the HTML: &lt;div class="indeed-apply-popup" tabindex="0" id="indeed-ia-1530049657884-0-modal" style="position: absolute; left: 216px; top: 80px;"&gt;&lt;div class="indeed-apply-container" id="indeedapply-modal-preload-container" style="height: 572px; width: 540px;"&gt;&lt;div class="indeed-apply-branding" id="indeedapply-modal-preload-branding"&gt;&lt;/div&gt;&lt;div class="indeed-apply-bd" id="indeedapply-modal-preload-bd"&gt;&lt;iframe name="indeedapply-modal-preload-iframe" id="indeedapply-modal-preload-iframe" scrolling="no" frameborder="0" src="https://apply.indeed.com/indeedapply/xpc?v=5#%7B%22cn%22:%22onESpqgxSb%22,%22ppu%22:%22https://www.indeed.com/robots.txt%22,%22lpu%22:%22https://apply.indeed.com/robots.txt%22,%22setupms%22:1530049660417,%22preload%22:true,%22iaUid%22:%221cgv11tjq1b2b0o4%22,%22parentURL%22:%22https://www.indeed.com/jobs?q=it&amp;amp;l=252C%2520FL&amp;amp;vjk=ff1572a95b1b84bf%22%7D" style="border: 0px; vertical-align: bottom; width: 100%; height: 100%;"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; the popup that contains the iframe has HTML like this: &lt;div class="indeed-apply-popup" tabindex="0" id="indeed-ia-1530049657884-0-modal" style="position: absolute; left: 208px; top: 80px;"&gt;&lt;div class="indeed-apply-container" id="indeedapply-modal-preload-container" style="height: 572px; width: 540px;"&gt;&lt;div class="indeed-apply-branding" id="indeedapply-modal-preload-branding"&gt;&lt;/div&gt;&lt;div class="indeed-apply-bd" id="indeedapply-modal-preload-bd"&gt; The part of my code I'm using looks like this: for item in page_results: item.click() WebDriverWait(driver, 10).until( EC.presence_of_…
has comment: http://stackoverflow.com/comment/89100764
has comment: http://stackoverflow.com/comment/89100535
has comment: http://stackoverflow.com/comment/89101270
has comment: http://stackoverflow.com/comment/89100689
tagged with: python
has comment: http://stackoverflow.com/comment/89101186

http://stackoverflow.com/a/51150104
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
score: 6
accepted answer of: http://stackoverflow.com/q/51149735
has body: This should be much faster: df = pd.DataFrame({'list1': [["a","b"], ["a","c"], ["a","d"], ["b","c"], ["b","d"], ["c","d"]]*100}) df2 = pd.DataFrame({'list2': [["a","b","c","d"], ["a","b"], ["b","c"], ["c","d"], ["b","c"]]*100}) list2 = df2['list2'].map(set).tolist() df['occurance'] = df['list1'].apply(set).apply(lambda x: len([i for i in list2 if x.issubset(i)])) Using your approach: %timeit for index, row in df.iterrows(): df.at[index, "occurrence"] = df2["list2"].apply(lambda x: all(i in x for i in row['list1'])).sum() 1 loop, best of 3: 3.98 s per loop Using mine: %timeit list2 = df2['list2'].map(set).tolist();df['occurance'] = df['list1'].apply(set).apply(lambda x: len([i for i in list2 if x.issubset(i)])) 10 loops, best of 3: 29.7 ms per loop Notice that I've increased the size of list by a factor of 100. EDIT This one seems even faster: list2 = df2['list2'].sort_values().tolist() df['occurance'] = df['list1'].apply(lambda x: len(list(next(iter(())) if not all(i in list2 for i in x) else i for i in x))) And timing: %timeit list2 = df2['list2'].sort_values().tolist();df['occurance'] = df['list1'].apply(lambda x: len(list(next(iter(())) if not all(i in list2 for i in x) else i for i in x))) 100 loops, best of 3: 14.8 ms per loop
answers question: http://stackoverflow.com/q/51149735

http://stackoverflow.com/q/51101132
has comment: http://stackoverflow.com/comment/89189782
type: Question
upvote count: 1
has title: How to remove Class name from exception message in python
favorite count: 0
tagged with: exception
tagged with: python
has comment: http://stackoverflow.com/comment/89227357
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: Here is the exception message in my python code: Common.AnimalClass.NestedClass: Id is not found I want to exclude the class name and just want to print the message like below: Id is not found I am new to python , How can I achieve this in python3? if not (is_id_present): self.log_step_status("FAIL", step_name) log_message = 'id is not found' raise TestCaseFailureError(log_message) class TestCaseFailureError(Exception, vlogger): """Base Error class for tests""" def __init__(self, *args, **kwargs): self.vlog('Message: {0}', args[0]) Exception.__init__(self, *args, **kwargs)
has comment: http://stackoverflow.com/comment/89189468
has comment: http://stackoverflow.com/comment/89189773
score: 1

http://stackoverflow.com/a/51122607
has comment: http://stackoverflow.com/comment/89231153
has comment: http://stackoverflow.com/comment/89293722
has comment: http://stackoverflow.com/comment/89231702
has comment: http://stackoverflow.com/comment/89230701
answers question: http://stackoverflow.com/q/51122355
accepted answer of: http://stackoverflow.com/q/51122355
has comment: http://stackoverflow.com/comment/89247807
has comment: http://stackoverflow.com/comment/89232721
score: 0
has comment: http://stackoverflow.com/comment/89230877
type: AcceptedAnswer
has body: If you've not come across it yet, you may find the ListView useful for displaying objects in a table. For example you could do; CarsList(ListView): model = Car def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['features'] = Feature.objects.filter( primary_feature=True ) return context Then in your template; Car {% for feature in features %} {{ feature.name }} {% endfor %} {% for car in object_list %} {{ car.name }} {% for car_feature in car.carfeatures_set.all %} {{ car_feature.feature }} {% endfor %} {% endfor %} Now you've asked how to get all cars for a particular feature. That would involve a reverse lookup on the CarFeature objects which relate to the Feature you want. For example; special_feature = Features.objects.get(name='Special') car_features = special_feature.carfeatures_set.all() # Then all cars with `special_feature` is special_cars = car_features.values('car') Or in a template; {% for car_feature in car_features %} {{ car_feature.car.name }} {% endfor %} You might find it beneficial to also read through the Many to One relationship docs; https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/ To show all the cars, with associated primary features you'd need to query the CarFeatures table similar to; def get_context_data(self, **kwargs): context = super(CarList, self).get_context_data(**kwargs) cars = list() for obj in Car.objects.all(): cars.append( (obj.name, obj.carfeatures_set.filter(feature__primary_feature=True)) ) context['cars'] = cars return context Which in the template would look like; Cars {% for car, carfeatures in cars %} {{ car }} {% for carfeature in carfeatures %} {{ carfeature.feature.name }} {% endfor %} {% endfor %}
has comment: http://stackoverflow.com/comment/89230571
has comment: http://stackoverflow.com/comment/89232636
type: Answer

http://stackoverflow.com/comment/89317238
type: QuestionComment
comment on: http://stackoverflow.com/q/51166817
has text: You need to do some image processing. Subtract the mean from the data, normalise values between -1 and 1, and do scatter plot in 3D, I think that would give some intuition. Could you describe more about your problem? what are you trying to achieve?
score: 0
type: Comment

http://stackoverflow.com/comment/124406669
type: AnswerComment
type: Comment
score: 5
has text: Copying the entire root from one image to another is bound to be trouble. Who knows what you are clobbering there? If it does work then it's luck and unless you precisely pin those image versions it's probably going to break on you as updates occur.
comment on: http://stackoverflow.com/a/58293896

http://stackoverflow.com/q/51088145
has comment: http://stackoverflow.com/comment/89168572
has comment: http://stackoverflow.com/comment/89168243
accepted answer: http://stackoverflow.com/a/51099116
tagged with: python
type: AnsweredQuestion
has title: Azure Python SDK & Machine Learning Studio Web Service Batch Execution Snippet: TypeError
has body: First Issue resolved, please read scroll down to EDIT2 I'm trying to access a Web Service deployed via Azure Machine Learning Studio, using the Batch Execution-Sample Code for Python on the bottom of below page: https://studio.azureml.net/apihelp/workspaces/306bc1f050ba4cdba0dbc6cc561c6ab0/webservices/e4e3d2d32ec347ae9a829b200f7d31cd/endpoints/61670382104542bc9533a920830b263c/jobs I have already fixed an Issue according to this question (replaced BlobService by BlobBlockService and so on): https://studio.azureml.net/apihelp/workspaces/306bc1f050ba4cdba0dbc6cc561c6ab0/webservices/e4e3d2d32ec347ae9a829b200f7d31cd/endpoints/61670382104542bc9533a920830b263c/jobs And I also have entered the API-Key, Container-Name, URL, account_key and account_name according to the instructions. However it seems that today the Code Snippet is even more outdated than it was back then because I receive a different error now: File "C:/Users/Alex/Desktop/scripts/BatchExecution.py", line 80, in uploadFileToBlob blob_service = asb.BlockBlobService(account_name=storage_account_name, account_key=storage_account_key) File "C:\Users\Alex\Anaconda3\lib\site-packages\azure\storage\blob\blockblobservice.py", line 145, in __init__ File "C:\Users\Alex\Anaconda3\lib\site-packages\azure\storage\blob\baseblobservice.py", line 205, in __init__ TypeError: get_service_parameters() got an unexpected keyword argument 'token_credential' I also noticed, that when installing the Azure SDK for Python via pip, I get the following warnings in the end of the process (installation is successful however): azure-storage-queue 1.3.0 has requirement azure-storage-common&lt;1.4.0,&gt;=1.3.0, but you'll have azure-storage-common 1.1.0 which is incompatible. azure-storage-file 1.3.0 has requirement azure-storage-common&lt;1.4.0,&gt;=1.3.0, but you'll have azure-storage-common 1.1.0 which is incompatible. azure-storage-blob 1.3.0 has requirement azure-storage-common&lt;1.4.0,&gt;=1.3.0, but you'll have azure-storage-common 1.…
tagged with: azure-blob-storage
tagged with: azure-machine-learning-service
type: Question
has answer: http://stackoverflow.com/a/51099116
score: 0
tagged with: rest
tagged with: azure
answer count: 1

http://stackoverflow.com/a/51062865
accepted answer of: http://stackoverflow.com/q/51054082
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: This was also reported at the pydev issue tracker at: https://www.brainwy.com/tracker/PyDev/923 So, please refer to that ticket (the issue is already fixed for 6.4.2 and there's a solution you can use at that ticket while the new version is not released).
answers question: http://stackoverflow.com/q/51054082
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89116839

http://stackoverflow.com/comment/89104661
score: 0
has text: What do you mean by "match"?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51057028

http://stackoverflow.com/q/51143074
downvote count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/19960077
type: Question
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51143142
tagged with: dataframe
score: -1
linked to: http://stackoverflow.com/q/12065885
answer count: 1
has comment: http://stackoverflow.com/comment/89270684
has title: Remove Values from Pandas Dataframe Based off of Excluded Values Contained in List
has body: Let's say I have a pandas dataframe, which looks as follows: Column1 Column2 Column3 A 1 Y8 B 1 G2 C 1 T1 D 2 A6 E 2 P0 F 3 M2 G 4 O2 I want to remove all values from this dataframe which appear in this list, called 'excl_list', if they are contained in Column3. The idea would be to exclude by the list object and not the individual items in the list: ['A6','P0','M2'] How would I go about doing that?
favorite count: 0
has comment: http://stackoverflow.com/comment/89270284
accepted answer: http://stackoverflow.com/a/51143142
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89270243

http://stackoverflow.com/q/51161620
tagged with: linear-regression
has title: Linear Regression python
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89306630
type: Question
has comment: http://stackoverflow.com/comment/89306744
score: 0
favorite count: 0
type: UnansweredQuestion
has body: I want to implement the Linear Regression in python, without scikit-learn, but I dont know why, the variable "error" always increment and that shouldnt, and I think maybe the problem is in the Formula, but I dont no where. Is the algorthm fine? def linear_regression(X, y, learning_rate=0.01, max_num_iterations=500, opt=True): # Your code goes here # Your code goes here w = np.zeros(len(X[0])) error=0 gradient=X variable =X print(f"X:{X}") for a in range(max_num_iterations): o = np.sum(X*w) error = y-o print(f"sum1:{np.sum(X*w)}") print(f"y:{y}") print(f"error: {error}") print (f"gradient1: {gradient}") print(f"w: {w}") for i in range(800): gradient[i][0]=-X[i][0]*error[i] gradient[i][1]=-X[i][1]*error[i] gradient=-learning_rate*gradient w=w+gradient return w
tagged with: python
has comment: http://stackoverflow.com/comment/89306738
has comment: http://stackoverflow.com/comment/89307187
answer count: 0

http://stackoverflow.com/comment/89280356
comment on: http://stackoverflow.com/q/51148129
has text: @hellow - the regex option would help me identify the function name but would need additional code to update something in the function. I was looking at maybe finding the opening and closing braces of a function and add the printf.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/121442791
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/60571905
has text: I like this solution better because it makes clear that the root of the problem is attempting to perform string operations on non-string values, which is not easily inferable from the error message.

http://stackoverflow.com/comment/89251096
has text: Could you expand on the *context*; why do you want to do this?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51133287

http://stackoverflow.com/comment/89216457
has text: This command oututs: `Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3q/xfr2ttbd0gl0wzmvc267pwv40000gp/T/pip-req-build-i3ftug_y/ ` and says that it didn't find the file
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51113821
type: Comment

http://stackoverflow.com/comment/89481270
has text: Why are you casting to a string?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51090140

http://stackoverflow.com/a/62325570
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51025269
downvote count: 0
type: Answer
has body: As @HMK said, on_epoch_begin and on_epoch_end methods provide the current epoch. For example, to apply a function every 10th epochs you can edit your custom callback like that: class myCallback(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None) if epoch % 10 == 0: your_func()

http://stackoverflow.com/comment/89242441
comment on: http://stackoverflow.com/q/51128696
score: 1
type: Comment
type: QuestionComment
has text: It would help if you gave each frame distinct colors while debugging this. Otherwise it's impossible to see where one frame ends and the next begins.

http://stackoverflow.com/a/51132105
has comment: http://stackoverflow.com/comment/89251136
has comment: http://stackoverflow.com/comment/89250872
has body: Try this simple code import os import time while True: time.sleep(3600) # pending for 1 hour (3600 seconds) os.makedirs(your directory) # create the directory EDIT (using parallel programming) import os import time from datetime import datetime from multiprocessing import Pool def create_folder(now): # you can manipulate variable "now" as you wish time.sleep(3600) # pending for 1 hour (3600 seconds) os.makedirs(your directory) # create the directory return while True: pool = Pool() now = datetime.now() result = pool.apply_async(create_folder, [now]) # asynchronously evaluate 'create_folder(now)' this may consume many of your computer resources
downvote count: 0
has comment: http://stackoverflow.com/comment/89251941
has comment: http://stackoverflow.com/comment/89254226
answers question: http://stackoverflow.com/q/51132025
has comment: http://stackoverflow.com/comment/89254352
upvote count: 2
has comment: http://stackoverflow.com/comment/89253171
has comment: http://stackoverflow.com/comment/89251993
type: Answer
has comment: http://stackoverflow.com/comment/89249700
score: 2
has comment: http://stackoverflow.com/comment/89253908

http://stackoverflow.com/q/51119584
downvote count: 0
answer count: 1
tagged with: string
accepted answer: http://stackoverflow.com/a/51121788
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am a beginner in python pandas, i am trying to scrap a paginated table using beautiful soup package, the data is scraped, but the content of each cell comes in a single row, i couldn't get a coherent csv file here is my code : import urllib import urllib.request from bs4 import BeautifulSoup import os file=open(os.path.expanduser("sites_commerciaux.csv"), "wb") def make_soup(url): thepage=urllib.request.urlopen(url) soupdata=BeautifulSoup(thepage,"html.parser") return soupdata headers="Nom_commercial_du_Site,Ville,Etat,Surface_GLA,Nombre_de_boutique,Contact" file.write(bytes(headers,encoding='ascii',errors='ignore')) save="" for num in range(0,22): soup=make_soup("http://www.ceetrus.com/fr/implantations-sites-commerciaux?page="+str(num)) for rec in soup.findAll('tr'): saverec="" for data in rec.findAll('td'): saverec=saverec+","+data.text if len(saverec)!=0: save=save+"\n"+saverec[1:] file.write(bytes(save,encoding='ascii',errors='ignore')) can anyone help me fix it please
has title: Scraping paginated web table with python pandas & beautifulSoup
type: Question
has answer: http://stackoverflow.com/a/51121788
tagged with: for-loop

http://stackoverflow.com/q/51094020
accepted answer: http://stackoverflow.com/a/51094159
has title: add specific value to rows selected based on conditions with Pandas
has body: If I have a following dataframe: id fruits 01 Apple, Apricot 02 Apple, Banana, Clementine, Pear 03 Orange, Pineapple, Pear I want to add Fruit to rows where Apple exists to generate a new dataframe like this: id fruits 01 Apple, Apricot, Fruit 02 Apple, Banana, Clementine, Pear, Fruit 03 Orange, Pineapple, Pear How should i do it? Thanks. Sorry i makeup this example to represent my real problem.
tagged with: pandas
has comment: http://stackoverflow.com/comment/89176299
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51094173
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51094173
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51094159
upvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/a/51050663
has comment: http://stackoverflow.com/comment/89173605
has body: The problem is probably that you are doing the delay while the file is still open and thus not written to disk. Try something like this: home = os.getcwd() os.chdir(r'\\CREOL-FAST-01\data') with open('request.txt', 'w') as file: proj = r'C:\dazzler\data\wavefile.txt' file.write(proj) time.sleep(0.05) os.chdir(home) The only difference here is that the sleep is done after the file is closed (the file is closed when the with block ends), and thus the delay doesn't happen until after the text is written to disk. To put it in words, what you are doing is: Open (and create) file Write text to a buffer (in memory, not on disk) Wait 50 ms Close (and write) the file What you want to do is: Open (and create) file Write text to a buffer (in memory, not on disk) Close (and write) the file Wait 50 ms So what you end up with is a period of at least 50 ms where the text file has been created, but where there is nothing in it because the text is sitting in your computer memory not on disk. To be honest, I would put as little in the with block as possible, to avoid issues like this. So I would write it like so: home = os.getcwd() os.chdir(r'\\CREOL-FAST-01\data') proj = r'C:\dazzler\data\wavefile.txt' with open('request.txt', 'w') as file: file.write(proj) time.sleep(0.05) os.chdir(home) Also keep in mind that you also can't do the opposite: assume that no text is written until you close. For small files like this, that will probably happen. But when the file is written to disk depends on a lot of factors. When a file is closed, it is written, but it may be written before that too.
type: Answer
has comment: http://stackoverflow.com/comment/89136692
has comment: http://stackoverflow.com/comment/89169942
answers question: http://stackoverflow.com/q/51033026
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51096550
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51097345
tagged with: python
downvote count: 0
score: 1
type: Question
has body: I have a set of data that follows a double gaussian distribution, whose equation depends on 4 parameters. What I'd like to do is: starting from a value for each of the 4 parameters (that are the ones I know that are closer to the parameters of the double gaussian that I obtain from the set of data) increasing them step by step plot the double gaussian with these parameters and check, using the least squares method, which are the better values to plot a double gaussian that is the best fit for the double gaussian that I obtain with the set of data. I've tried to do it, below is my code: import matplotlib.pyplot as plt import numpy as np def DGauss(x,I1,I2,sigma1,sigma2): return (I1/np.sqrt(2*np.pi*sigma1))*np.exp(-x*x/(2*sigma1*sigma1)) + (I2/np.sqrt(2*np.pi*sigma2))*np.exp(-x*x/(2*sigma2*sigma2)) def Inte(x0,xf,npoints,I1,I2,sigma1,sigma2): delta = (xf-x0)/npoints h = 0 for i in range(npoints): x = x0 + i*delta if (i % 2) == 0: fact = 4.0 else: fact = 2.0 h += fact*DGauss(x,I1,I2,sigma1,sigma2) return (abs(delta)/3.0)*(h + DGauss(x0,I1,I2,sigma1,sigma2) + DGauss(xf,I1,I2,sigma1,sigma2)) def IntBLM(start,end): delta = 1 VarIntBLM = (1.0/3.0)*(BLM[start]+4.0*BLM[start+delta]+BLM[end]) return VarIntBLM Position = [9.88, 8.68, 7.48, 6.28, 5.08, 3.88, 3.28, 3.13, 3.08, 3.03, 2.98, 2.93, 2.88, 2.83, 2.78, 2.73, 2.68, 2.63, 2.58, 2.53, 2.48, 2.43, 2.38, 2.33, 2.28, 2.23, 2.18, 2.13, 2.08, 2.03, 1.98, 1.93, 1.88, 1.83, 1.78, 1.73, 1.68, 1.63, 1.58, 1.53, 1.48, 1.43, 1.38, 1.33, 1.28, 1.23, 1.18, 1.13, 1.08, 1.03, 0.98, 0.93, 0.88, 0.83, 0.78, 0.73, 0.68, 0.63, 0.58, 0.53, 0.48, 0.43, 0.38, 0.33, 0.28, 0.23, 0.18, 0.13, 0.08, 0.03] yVal = [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.05493778e-04, 3.68936803e-04, 1.73977308e-03, 9.86279398e-03, 1.52954321e-02, 2.42624032e-02, 2.87455974e-02, 3.23848413e-02, 3.28592719e-02, 3.94523416e-02, 4.61509051e-02, 5.70161813e-02, 6.37672003e-02, 7.19426767e-02, 7.76393407e-02, 8.56568678e-02, 9.61526244e-02, 1.04328101e-01, 1.135…
has comment: http://stackoverflow.com/comment/89187475
has comment: http://stackoverflow.com/comment/89184944
has comment: http://stackoverflow.com/comment/89182164
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89182013
has title: Least squares method
favorite count: 0

http://stackoverflow.com/q/51154906
type: Question
has title: How to make TCK_QUICKACK work in Python
downvote count: 0
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has body: I want to implement tcp check with Python. I found a magic way in this article. It introduce a efficient way to do a tcp-health-check. Client: SYN Server: SYN-ACK Client: RST I also found a Go implementer https://github.com/tevino/tcp-shaker. But i hope to implement SYN,SYN-ACK,RST in python. My code is there: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_TCP, socket.TCP_QUICKACK, 0) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 0) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) s.connect((ip, port)) s.close() But it didn't work as I expected. The client send a ACK to the server when the SYN-ACK received from server. How could I disable TCP_QUICKACK in Python?
score: 3
answer count: 0
upvote count: 3
tagged with: tcp

http://stackoverflow.com/comment/89070199
has text: Thank you @Sunitha ma'am for the help but checking till the square root of the target number will not work in cases where the square root is smaller than the largest factor. For example- in case of the number 10, the largest factor is 5 but the square root is 3.16, so this code will return 2 as the output while it should have given 5.
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51018345

http://stackoverflow.com/q/51080746
has answer: http://stackoverflow.com/a/51279038
upvote count: 1
answer count: 1
favorite count: 0
has title: Tensorflow GPU model failing to train on custom images
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
tagged with: machine-learning
downvote count: 1
tagged with: tensorflow
type: Question
has body: i have recently been playing around with tensorflow object detection with GPU processor, and i have encountered an error when trying to train my model with custom images.The error tracestack is as follows: WARNING:tensorflow:From C:\tensorflow1\models\research\object_detection\trainer.py:260: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Please switch to tf.train.create_global_step WARNING:tensorflow:num_readers has been reduced to 1 to match input file shards. Traceback (most recent call last): File "train.py", line 184, in &lt;module&gt; tf.app.run() File "C:\Users\Dan\AppData\Local\conda\conda\envs\tensorflow1\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run _sys.exit(main(argv)) File "train.py", line 180, in main graph_hook_fn=graph_rewriter_fn) File "C:\tensorflow1\models\research\object_detection\trainer.py", line 274, in train train_config.prefetch_queue_capacity, data_augmentation_options) File "C:\tensorflow1\models\research\object_detection\trainer.py", line 80, in create_input_queue include_keypoints=include_keypoints)) File "C:\tensorflow1\models\research\object_detection\core\preprocessor.py", line 3147, in preprocess (func.__name__)) ValueError: The function random_horizontal_flip does not exist in func_arg_map I am using an Anaconda interpreter with Python 3.6, tio reproduce this error i followed all the steps in the link https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10 . The command which gave me this error was: python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config it is important to note i did not encounter any issues before training the model. I would be greatfull if someone could explain this error to me and even help me fix it, thanks in advance :-)
score: 0
has comment: http://stackoverflow.com/comment/104306702

http://stackoverflow.com/comment/89289393
has text: Yes. It will b in the same format
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51152939
type: Comment

http://stackoverflow.com/a/51017558
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51017468
upvote count: 1
has body: from time import sleep import threading def whatever(i): print("Hey! It's me number " + str(i)) for i in range(3): t = threading.Thread(target=whatever, args=(i,)) t.start() You have to consider one thing though. In Python we have something called GIL - Global Interpreter Lock. It's something that, in short, makes it possible for only one thread of your python application, to execute in a given interpreter at once. What does it mean? That it's not quite that easy do achieve true concurrency in Python - while it may seem like the instructions are being executed simultaneously because of the super quick CPUs we have today, they are, in fact, not.

http://stackoverflow.com/q/51043744
has answer: http://stackoverflow.com/a/51155330
upvote count: 1
has title: Installing Django-channels error
accepted answer: http://stackoverflow.com/a/51155330
has answer: http://stackoverflow.com/a/57913285
favorite count: 0
has answer: http://stackoverflow.com/a/58925334
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51155503
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51155503
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51044283
has body: I'm trying to develop a chat application in Django on mac OS. I've tried to install Django-Channels in virtualenv, with this commands: pip install channels pip install django-channels but this error occurred: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/4c/xy3rtg_165l0650j4tq7fvrh0000gn/T/pip-install-7anqvzhg/twisted/ Python version = 3.5.2, Django version = 1.11, pip is already up-tp-date
type: Question

http://stackoverflow.com/a/51043476
downvote count: 0
type: Answer
has body: XML is case-sensitive. I believe that root.findall('safemap:CTPRVN_CD') might work better. Also I noticed that your xml seems to use namespaces. Usually there is a problem with namespaces, when working with xmls using lxml or xml package in python.
has comment: http://stackoverflow.com/comment/89078075
answers question: http://stackoverflow.com/q/51043406
score: 1
upvote count: 1

http://stackoverflow.com/comment/89279407
score: 0
type: Comment
type: QuestionComment
has text: nulls in the categorical features will either be gone (0) or will be transformed to a new column (with a 1 in them) if you specify dummy_na=True to get_dummies. The rest should still be there (at least that's what I see with pandas 0.23.1)
comment on: http://stackoverflow.com/q/51147326

http://stackoverflow.com/q/51085465
has answer: http://stackoverflow.com/a/51087217
has answer: http://stackoverflow.com/a/51085466
has title: access "implicit" metavar value in argument help string
answer count: 2
tagged with: argparse
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: When you call add_argument on an argparse.ArgumentParser() without an explicit action, you get the "store" action. In the auto-generated --help output you get the uppercase of the long option, unless you set metavar: import argparse parser = argparse.ArgumentParser() parser.add_argument('--version', metavar='X.Y.Z') parser.add_argument('--date'), parser.parse_args(['--help']) displays: usage: try.py [-h] [--version X.Y.Z] [--date DATE] optional arguments: -h, --help show this help message and exit --version X.Y.Z --date DATE In this I would call X.Y.Z an explicit metavar, and DATE an implicit metavar. If you want to have more useful help you can do: parser.add_argument('--version', metavar='X.Y.Z', help = "set version to % (metavar)s") which gives (only changed lines shown): --version X.Y.Z set version to X.Y.Z and being able to use that %(metavar)s in the help string is nice because when you change metavar='MAJOR.MINOR', the help doesn't need to be updated (which you are bound to forget). But if you add the help for the --date argument, with the implicit metavar: parser.add_argument('--date', help="use %(metavar)s instead of today's date") you get: --date DATE use None instead of today And that None is not what I expected, nor what I want. Of course I can always hard-code 'DATE' in the help, or explicitly provide the metavar (especially when it is used in the help string). But when I do that, I am bound to forget to update the metavar when I change the name of the long option. Is there an "automatic" way to get DATE in the help string instead of None ? Or am I using %(metavar)s where I should be using something else (and if so, what)?
tagged with: python
score: 3
upvote count: 3
type: Question

http://stackoverflow.com/comment/89196408
comment on: http://stackoverflow.com/a/51103991
score: 0
type: AnswerComment
has text: I think it's the same idea. I edited the answer to make the assignment from `X1` to `X` more explicit. Is this not what you're asking?
type: Comment

http://stackoverflow.com/comment/89257583
comment on: http://stackoverflow.com/a/51136387
type: AnswerComment
score: 0
type: Comment
has text: @Jmons This assumption works too. But I needed to know if I could make it.

http://stackoverflow.com/a/51094109
has comment: http://stackoverflow.com/comment/89204411
has comment: http://stackoverflow.com/comment/89531828
type: Answer
has body: You may want to look at this Chainer Example. https://colab.research.google.com/drive/1SsxHvQdSz23kaVov8yKizVD3_2tkXdZM
upvote count: 1
answers question: http://stackoverflow.com/q/51077870
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51077870

http://stackoverflow.com/comment/89238593
has text: What language is that, in your input.txt? I would check if there's a python library that can parse it, then you can interact with it conceptually, instead of hacking the syntax with direct reads and writes.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51126527

http://stackoverflow.com/comment/89030241
type: Comment
comment on: http://stackoverflow.com/a/51018027
score: 0
type: AnswerComment
has text: For now link_list return 10 links, and then GetData process each in turn. I will create loop to get 600 links in all website.

http://stackoverflow.com/a/51094290
score: 2
has body: Given some string set as s = '419' you can get the upper and lower digits by converting to an integer, then using modulo and integer division. The integer conversion can be encapsulated in a try-except block catching ValueError if you have a reasonable response to invalid inputs: n = int(s) hours = n // 100 # Truncating integer division minutes = n % 100 # Modulo removes the upper digits
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51094181
type: Answer

http://stackoverflow.com/comment/89185435
comment on: http://stackoverflow.com/q/51098714
score: 0
type: Comment
has text: I think it is logically not possible to introduce a new standard value (say `Undef`) for that purpose. We would then need to distinguish between "any value except Undef" (formerly known as "any value") and "any value including Undef".
type: QuestionComment

http://stackoverflow.com/comment/89311361
score: 0
comment on: http://stackoverflow.com/a/51162029
type: Comment
has text: They were not the same version but I already uninstalled both ands reinstalled python 3.7 but it still does not recognize pip on cmd.
type: AnswerComment

http://stackoverflow.com/a/51062680
score: 0
has body: The problem in your code is that arr.index(elem) always returns 1 (first index of elem in arr) if elem equals 10, in your second call of find_even_index(). So it can't work. I suggest you the following solution, iterating directly on the indexes instead of on the values of the list: def find_even_index(arr): for i in range(len(arr)): if sum(arr[0:i]) == sum(arr[i+1:]): return i return None print(find_even_index([1,2,3,4,3,2,1])) # 3 print(find_even_index([20,10,30,10,10,15,35])) # 3
type: Answer
has comment: http://stackoverflow.com/comment/89128925
has comment: http://stackoverflow.com/comment/89129764
accepted answer of: http://stackoverflow.com/q/51062136
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51062136

http://stackoverflow.com/comment/89022431
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51014688
type: QuestionComment
has text: so you need that folder named "tf_env" that I call "the name" of the environment but is actually a folder that will contain executable python files.

http://stackoverflow.com/comment/89297820
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51147762
has text: Not a duplicate, this question is specifically about usage of success/failure callbacks
score: 0

http://stackoverflow.com/q/51092139
tagged with: django
has answer: http://stackoverflow.com/a/51093208
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51092161
has body: Here's my template: /{{ user_settings.room2 }} /{{ user_settings.room3 }} /{{ user_settings.room4 }} If the value of {{ user_settings.room2 }} is null, hide its parent. If the value of {{ user_settings.room3 }} is null, hide its parent. What is an efficient way this can be done?
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51092161
tagged with: http://stackoverflow.com/tag/html
has title: If template variable is null, hide it's nesting html element
tagged with: python
possible better answer: http://stackoverflow.com/a/51093208

http://stackoverflow.com/q/51069286
upvote count: 1
has answer: http://stackoverflow.com/a/51069415
type: Question
has answer: http://stackoverflow.com/a/51069360
has answer: http://stackoverflow.com/a/51069397
possible better answer: http://stackoverflow.com/a/51069418
has body: I have this code so far data = ['fx_name_v002.1001.exr fx_name_v002.1016.exr' 'fx_name_v002.1002.exr fx_name_v002.1018.exr'] data.sort() frames = [] def string_split(data): for i in data: print(i.split('.')) I need to split the list like I have. Once the list is split I need to add the 1002, 1001, of the split ends into the empty list frames
downvote count: 0
has answer: http://stackoverflow.com/a/51069418
score: 1
has comment: http://stackoverflow.com/comment/89128530
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89128554
tagged with: python
has comment: http://stackoverflow.com/comment/89128484
has comment: http://stackoverflow.com/comment/89128421
answer count: 4
has comment: http://stackoverflow.com/comment/89128492
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51069397
has title: Python String Segment Manipulation

http://stackoverflow.com/a/51279038
has body: You might forget to add the below line to ~/.bashrc: export PYTHONPATH=$PYTHONPATH:pwd:pwd/slim
answers question: http://stackoverflow.com/q/51080746
type: Answer
score: 0

http://stackoverflow.com/q/51164020
has title: How do I resolve this pivot_table error?
tagged with: pandas
tagged with: python-3.x
answer count: 0
tagged with: pivot-table
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89311329
tagged with: python
has comment: http://stackoverflow.com/comment/89311457
has comment: http://stackoverflow.com/comment/89311734
has body: The error description says almost nothing about the cause. What actually caused this error? What should I change to resolve this error? The command I ran in my Jupyter notebook: temp2 = df.pivot_table(values='Loan_Status',index= 'Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean()) And the error displayed in console: KeyError Traceback (most recent call last) &lt;ipython-input-70-36df2773019b&gt; in &lt;module&gt;() ----&gt; 1 temp2 = df.pivot_table(values='Loan_Status',index=['Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean()) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in pivot_table(self, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name) 5298 aggfunc=aggfunc, fill_value=fill_value, 5299 margins=margins, dropna=dropna, -&gt; 5300 margins_name=margins_name) 5301 5302 def stack(self, level=-1, dropna=True): C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py in pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name) 57 for i in values: 58 if i not in data: ---&gt; 59 raise KeyError(i) 60 61 to_filter = [] KeyError: 'Loan_Status' **Here is a sample of my dataframe: ** **Here is df.columns(): **
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89311541
has comment: http://stackoverflow.com/comment/89311627

http://stackoverflow.com/comment/89185673
type: QuestionComment
comment on: http://stackoverflow.com/q/51096500
score: 0
has text: Can you provide a more complete example of the GUI code you are using? The code section provided above isn't complete, some text has been truncated etc.
type: Comment

http://stackoverflow.com/a/51039326
has body: Maybe the below: import platform if platform.python_version().startswith('2.7'): from Queue import Queue elif platform.python_version().startswith('3.6'): from queue import Queue
answers question: http://stackoverflow.com/q/51039167
score: 0
has comment: http://stackoverflow.com/comment/89070089
type: Answer

http://stackoverflow.com/comment/89222533
comment on: http://stackoverflow.com/a/51116992
type: Comment
has text: @aguntuk - It is only display issue, no problem if write to file. For prevent it check [this](https://stackoverflow.com/q/11707586/2901002)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89271951
type: QuestionComment
comment on: http://stackoverflow.com/q/51143858
has text: Multi-line list merger ? Please... At least use a for loop to iterate over the lists and combine them.
score: 0
type: Comment

http://stackoverflow.com/comment/89133189
has text: Hi, I have updated the code, you need to use np.swapaxes.
comment on: http://stackoverflow.com/a/51071518
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51140092
downvote count: 0
has comment: http://stackoverflow.com/comment/89266660
type: Answer
has body: You can access all answers by using the related_name: &gt;&gt;&gt; question = Question.objects.get(question_text='random question') &gt;&gt;&gt; print(question.answer_set.all()) You can read more about this on: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name
upvote count: 1
answers question: http://stackoverflow.com/q/51140048
score: 1

http://stackoverflow.com/comment/89076240
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51042659
score: 0
has text: `username= self.username1.get ()` why a space ? is this a typo ?

http://stackoverflow.com/comment/128202797
score: 0
comment on: http://stackoverflow.com/q/51149865
type: QuestionComment
type: Comment
has text: Short answer is `data.item()`.

http://stackoverflow.com/a/51137193
score: 1
answers question: http://stackoverflow.com/q/51137021
upvote count: 1
type: Answer
has body: You can use regex for this. import re bool(re.search(r'\b[a-z]+\s+[a-z]+\s+[a-z]+\b', 'test test 1 test', re.IGNORECASE))
downvote count: 0

http://stackoverflow.com/q/51072469
tagged with: python
answer count: 0
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has body: I want to create custom batches using a pandas dataframe df_train which has all of my training dataset and a numpy array arr_train which has starting and ending index of my batches. I want to generate batches based on the start and end indexs. For example my df_train looks something like index col1 col2 col3 0 100 121 A 1 101 211 A 2 102 213 B and my arr_train loos like arr_train = [[0 1] [2 2]] Which means my ith batch will be df_train.loc[arr_train[i,0]:arr_train[i,1],:] I know how to do this using keras. But I want to convert my keras model to tensorflow.estimator so I need to convert my batch_generator for tensorflow.estimator Here is my keras data_generator import numpy as np from tensorflow import keras class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, df,arr_df,predictors,response,weight=None, shuffle = False, training=False): 'Initialization' self.arr_df = arr_df self.df = df self.shuffle = shuffle self.predictors = predictors self.response = response self.weight = weight self.traning = training self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return self.arr_df.shape[0] def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of batch # idx = self.indexes[self.arr_df[index,0]:self.arr_df[index,1]] # Generate data a1 = self.arr_df[index,0] a2 = self.arr_df[index, 1] X1 = self.df.loc[a1:a2,self.predictors].as_matrix().reshape((1,-1,len(self.predictors))) if (self.traning) &amp; (self.weight !=None): y = self.df.loc[a1:a2,self.response].as_matrix().reshape((1,-1,1)) w = self.df.loc[a1:a2, self.weight].unique() return X1,y,w elif (self.traning) &amp; (self.weight ==None): y = self.df.loc[a1:a2, self.response].as_matrix().reshape((1,-1, 1)) return X1,y return X1 def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(self.arr_df.shape[0]) if self.shuffle == True: np.random.shuffle(self.indexes)
tagged with: tensorflow-estimator
has title: convert keras datagenerator for tensorflow estimator
upvote count: 1
tagged with: keras
tagged with: tensorflow-datasets
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51088725
has comment: http://stackoverflow.com/comment/89166418
has comment: http://stackoverflow.com/comment/89166664
has comment: http://stackoverflow.com/comment/89166594
has body: I try to write some batch that can autorun my python scripts.Here is my batch file: @echo off :: do something here pythonw xx.py rem run python script in the backgroud rem but batch stops here, doesn't run the rest code :: do something else again So how can I fix this. Any help will be appreciated! Related question: Running Python Script as a Windows background process
tagged with: batch-file
has answer: http://stackoverflow.com/a/51089800
has comment: http://stackoverflow.com/comment/89167080
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/9705982
has comment: http://stackoverflow.com/comment/89167542
tagged with: windows
tagged with: python
linked to: http://stackoverflow.com/q/32808730
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51089800
has title: Batch stops running when running `pythonw xx.py`
score: 1
has comment: http://stackoverflow.com/comment/89166899
has comment: http://stackoverflow.com/comment/89166388
upvote count: 1
has comment: http://stackoverflow.com/comment/89166494
type: Question

http://stackoverflow.com/q/51146117
upvote count: 30
has answer: http://stackoverflow.com/a/57134682
has title: Installing mysqlclient in Python 3.6 in windows
has answer: http://stackoverflow.com/a/51149017
has answer: http://stackoverflow.com/a/73726980
tagged with: mysql-python
possible better answer: http://stackoverflow.com/a/51164104
answer count: 10
has answer: http://stackoverflow.com/a/51164104
tagged with: python-wheel
score: 29
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/51787405
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51149017
has answer: http://stackoverflow.com/a/59084234
has answer: http://stackoverflow.com/a/56062061
linked to: http://stackoverflow.com/q/26866147
has answer: http://stackoverflow.com/a/53265538
type: Question
has answer: http://stackoverflow.com/a/61167792
has body: I want to install MySqlclient on my windows system. I am Currently using Python 3.6. After going through the various post over Stackoverflow, I could Not find the correct way. This is what I have done so far: 1) Installation by using pip pip install mysqlclient. Error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools" http://landinghub.visualstudio.com/visual-cpp-build-tools I already have Microsoft Visual C++ installed on my laptop. Some are saying you need 2015 edition. 2) Installation by using wheel file pip install mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl. Error: Requirement mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl looks like a filename, but the file does not exist. mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. 2.1) Changing the whl file to different version pip install mysqlclient-1.3.13-cp36-cp36m-win32.whl. Error: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\Foxtrot\\Desktop\\finaltest\\mysqlclient-1.3.13-cp36-cp36m-win32.whl' Other things that are done: updated setuptools, updated wheel.
favorite count: 0
has answer: http://stackoverflow.com/a/59878580

automation
tags question: http://stackoverflow.com/q/51155196
tags question: http://stackoverflow.com/q/51014738
tag name: automation
tags question: http://stackoverflow.com/q/51165461
tags question: http://stackoverflow.com/q/51067922
tags question: http://stackoverflow.com/q/51014205
type: Tag
tags question: http://stackoverflow.com/q/51046320
tags question: http://stackoverflow.com/q/51157380
tags question: http://stackoverflow.com/q/51146012
tags question: http://stackoverflow.com/q/51129251
tags question: http://stackoverflow.com/q/51133630
tags question: http://stackoverflow.com/q/51040572

http://stackoverflow.com/a/51071890
accepted answer of: http://stackoverflow.com/q/51071691
has comment: http://stackoverflow.com/comment/134783157
upvote count: 9
answers question: http://stackoverflow.com/q/51071691
score: 9
has body: If you only want this for interactive sessions (as opposed to also happening every time you run a script with python myscript.py or ./myscript or a module with python -m mymodule), what you want is the environment variable PYTHONSTARTUP: If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session… If you want this to always happen forever, of course, you need to set this environment variable in some appropriate global place—e.g., your shell profile on most *nix platforms, or both your shell profile and your launchd profile on macOS, or the appropriate part of the Control Panel on Windows (the appropriate part changes with almost every new version of Windows, but it usually has "System" in the name). If you want this to happen for all users, not just the current user… the details for how to set a system-wide environment variable are more platform-specific, but otherwise the idea is the same. If you want this to happen for every Python session, even when some other program is running a Python script and you didn't even know it was doing that… what you want is either usercustomize or sitecustomize, as documented in the site documentation: This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option. … After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory. After this, an attempt is made to import a module named usercustomize, which can perform arbitrary user-specific customizations, if ENABLE_USER_SITE is true. This file is intended to be created in the user si…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/126579184
type: Answer

http://stackoverflow.com/comment/89017358
type: QuestionComment
type: Comment
has text: change to `check_output(['sbdart >> output1.csv'],shell=True)` note [...] and see if it makes a difference
comment on: http://stackoverflow.com/q/51011742
score: 0

http://stackoverflow.com/comment/89170969
has text: @MikeyMike fixed the source link
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51091037

http://stackoverflow.com/comment/124206210
comment on: http://stackoverflow.com/a/56134984
has text: For anyone looking at 2021-12-07, conda way is the best and only way that worked for me personally.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51107509
favorite count: 0
tagged with: python
has title: Tensorflow: differences on how to save a trained model
accepted answer: http://stackoverflow.com/a/51136203
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51136203
type: Question
has body: I noticed that in Python there exist several ways for saving a trained model However I am not able to see the real difference between them. Checkpoints saver = tf.train.Saver() saver.save(session, output_path) Freezing from tensorflow.python.framework import graph_util input_graph_def = graph.as_graph_def() output_graph_def = graph_util.convert_variables_to_constants( session, input_graph_def, output_nodes_names) with tf.gfile.GFile(output_graph, "wb") as output_graph_file: output_graph_file.write(output_graph_def.SerializeToString()) SavedModelBuilder builder = tf.saved_model.builder.SavedModelBuilder(output_path) builder.add_meta_graph_and_variables( session, [tf.saved_model.tag_constants.SERVING], clear_devices=True) builder.save() Let's consider different scenarios: evaluation/inference, fine-tuning, serving API, export to other frameworks. What's the best way for saving a model for each of these situtations? Are there rules about when to use one method or the other? Thanks
tagged with: tensorflow-serving
downvote count: 0
answer count: 1

teradata
type: Tag
tags question: http://stackoverflow.com/q/51026016
tags question: http://stackoverflow.com/q/51035435
tag name: teradata
tags question: http://stackoverflow.com/q/51051745
tags question: http://stackoverflow.com/q/51062715

http://stackoverflow.com/comment/89362697
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51178730
has text: but, what if i want to use a function instead of `tornado.gen.sleep(2)`, for example mysql queries, i just tested a non-async function and it blocked. i just want the application server response to other clients while a client request is processing

http://stackoverflow.com/q/51123415
accepted answer: http://stackoverflow.com/a/51123449
type: AnsweredQuestion
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51123449
has body: I'm trying this code in django: The urls.py has: re_path(r'^(?P&lt;site_url_var&gt;[-\w.]+)/$', views.FnDetails, name='detail'), The views.py has: def FnDetails(request, site_url_var): try: url_details = detail.objects.get(page_end_url=site_url_var) except detail.DoesNotExist: raise Http404("Url Does Not Exist") return render(request, 'base.html', {'url_details' : url_details}) But in some cases when the values are present in some other url.py, it returns an HTTP 404 error. What I want is something which does something like: except: redirect("to Other View")
has answer: http://stackoverflow.com/a/51123489
has comment: http://stackoverflow.com/comment/89231990
possible better answer: http://stackoverflow.com/a/51123489
has title: How do I redirect a user to some other views.py if nothing is found in the query set?
tagged with: django
tagged with: python

http://stackoverflow.com/q/51120783
answer count: 3
has comment: http://stackoverflow.com/comment/89230671
has comment: http://stackoverflow.com/comment/89227455
downvote count: 1
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/51121027
has body: I am trying to convert dictionary to CSV so that it is readable (in their respective key). import csv import json from urllib.request import urlopen x =0 id_num = [848649491, 883560475, 431495539, 883481767, 851341658, 42842466, 173114302, 900616370, 1042383097, 859872672] for bilangan in id_num: with urlopen("https://shopee.com.my/api/v2/item/get?itemid="+str(bilangan)+"&amp;shopid=1883827")as response: source = response.read() data = json.loads(source) #print(json.dumps(data, indent=2)) data_list ={ x:{'title':productName(),'price':price(),'description':description(),'preorder':checkPreorder(), 'estimate delivery':estimateDelivery(),'variation': variation(), 'category':categories(), 'brand':brand(),'image':image_link()}} #print(data_list[x]) x =+ 1 i store the data in x, so it will be looping from 0 to 1, 2 and etc. i have tried many things but still cannot find a way to make it look like this or close to this: https://i.sstatic.net/WoOpe.jpg
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51120913
accepted answer: http://stackoverflow.com/a/51120913
has answer: http://stackoverflow.com/a/51122824
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/89227088
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51121027
type: Question
tagged with: export-to-csv
upvote count: 1
has title: Python convert dictionary to CSV
score: 0

http://stackoverflow.com/a/54751593
has comment: http://stackoverflow.com/comment/96286183
type: Answer
answers question: http://stackoverflow.com/q/51155313
score: 2
upvote count: 2
has body: If that can help, I found that: import multiprocessing as mp import time import random import os import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore #from pyqtgraph.dockarea import * class PLT(): def __init__(self): self.win = pg.GraphicsWindow(title="Basic plotting examples") self.win.setWindowTitle('pyqtgraph example: Plotting') #self.win.resize(1000,600) self.p2 = self.win.addPlot(title="Updating plot") self.curve = self.p2.plot(pen='y') #QtGui.QApplication.instance().exec_() # ---&gt; if it's in effect, the plotting window shows up, but the data exchange doesn't happen. def update(self, data): self.curve.setData(data) QtGui.QApplication.processEvents() # &lt;--- Here is the way to update the window. class sender(mp.Process): def __init__(self, pipe): mp.Process.__init__(self) self.pipe = pipe def run(self): print('SENDER PID: ', os.getpid() ) while True: value = random.randint(0, 10) self.pipe.send(value) time.sleep(.01) class receiver(mp.Process): def __init__(self, pipe): mp.Process.__init__(self) self.pipe = pipe def run(self): self.p = PLT() print('RECEIVER PID: ', os.getpid() ) while True: integer = self.pipe.recv() print(integer) self.p.update(np.random.normal(size=(10,1000))[integer%10]) if __name__ == '__main__': mp.freeze_support() print('MAIN PID: ', os.getpid() ) out_pipe, in_pipe = mp.Pipe() p1 = sender(pipe=in_pipe) p2 = receiver(pipe=out_pipe) p1.start() p2.start()
downvote count: 0
has comment: http://stackoverflow.com/comment/119763575

http://stackoverflow.com/a/51040149
accepted answer of: http://stackoverflow.com/q/51040077
type: AcceptedAnswer
downvote count: 0
has body: argv collects all the command line parameters, including the name of the script itself. If you want to exclude the name, use argv[1:]. If you want just the filename, use argv[0]. In your case: script = argv[0].
answers question: http://stackoverflow.com/q/51040077
score: 5
type: Answer
upvote count: 5

http://stackoverflow.com/comment/89090803
type: QuestionComment
has text: Hi Ziyad,Thanks for quick rply I removed the block indentation,this time i am getting unable to impaort 'pandas' import pandas as pd import pyodbc import shutil import numpy as np def My_ListSource(): dataincsv = data.to_csv(r'export into my csv path',sep=r'|') cnxn = pyodbc.connect('''connection string''') stmt1 = """Select column 1 from mytable""" try: Out_service = pd.read_sql(stmt1,cnxn) except: print("File format might be wrong,check the error") else: print(Out_service) exit()
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51049819

http://stackoverflow.com/q/51158992
type: Question
score: 1
answer count: 3
possible better answer: http://stackoverflow.com/a/51159166
upvote count: 1
has comment: http://stackoverflow.com/comment/89301377
has comment: http://stackoverflow.com/comment/89301314
favorite count: 0
has comment: http://stackoverflow.com/comment/89301433
tagged with: python
has body: I'm a beginner developer and I'm trying to write the following variable in a for loop to a file, but it's trying to write as a str when it's a generator. I also receive unsupported operand type when trying with my second method. divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member']) for b in divdir: with open ('test2.txt', 'w') as file: file.write (b) I've also tried the following: divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member']) my_file=open("test2.txt","w") for b in divdir: my_file.write(b.get('divdir')+'\n') my_file.close() The error it gives is: TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
type: AnsweredQuestion
has title: Python - Writing For Loop as file as generator not str/dict
has answer: http://stackoverflow.com/a/51159166
downvote count: 0
has answer: http://stackoverflow.com/a/51159163
accepted answer: http://stackoverflow.com/a/51159163
has answer: http://stackoverflow.com/a/51159261

http://stackoverflow.com/q/51133277
type: Question
answer count: 1
downvote count: 0
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51135450
accepted answer: http://stackoverflow.com/a/51135450
linked to: http://stackoverflow.com/q/38533897
tagged with: macos
favorite count: 0
score: 2
tagged with: amazon-rekognition
upvote count: 2
has title: AWS Connection error to Endpoint URL for Rekognition
tagged with: python
type: AnsweredQuestion
has body: I have just started with AWS Rekognition and I have run into a problem that I can't seem to solve. I am using the Python script supplied on Detecting Text in an Image - Amazon Rekognition to test how the service works and how I could possibly integrate it into other apps. I know that I have entered the correct data for the config and credential files, found here: ~/.aws/credentials as other services such as S3 work without a problem using command line code. In the supplied code (I will include it at the end) I have specified the correct bucket as well as the name of the picture I'm trying to use. When running the script, on terminal everything works fine until after a few seconds the following error message is displayed: botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://rekognition.eu-west-2.amazonaws.com/" I have also tried several other availability zones such as: us-east-1, us-west-1, eu-central-1 yet they all result in the same error. A similar issue has already been discussed in python - botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint - Stack Overflow. However, the solution offered in that discussion did not solve the problem I am encountering. I would appreciate any help and tips that can solve this issue. import boto3 bucket='bucket' photo='inputtext.jpg' client=boto3.client('rekognition') response=client.detect_text(Image={'S3Object':{'Bucket':bucket,'Name':photo}}) textDetections=response['TextDetections'] print response print 'Matching faces' for text in textDetections: print 'Detected text:' + text['DetectedText'] print 'Confidence: ' + "{:.2f}".format(text['Confidence']) + "%" print 'Id: {}'.format(text['Id']) if 'ParentId' in text: print 'Parent Id: {}'.format(text['ParentId']) print 'Type:' + text['Type'] print

http://stackoverflow.com/comment/89290824
comment on: http://stackoverflow.com/a/51153697
type: Comment
has text: You can also replace the space by \s+ in the RegEx
type: AnswerComment
score: 0

http://stackoverflow.com/a/53920257
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51118963
has body: None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS. I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now

http://stackoverflow.com/q/51150898
has body: I have a QuerySet object with 100 items, for each of them I need to know how many times a particular contract_number occurs in the contract_number field. Example of expected output: [{'contract_number': 123, 'contract_count': 2}, {'contract_number': 456, 'contract_count': 1} ...] This means that value 123 occurs 2 times for the whole contract_number field. Important thing: I cannot reduce the amount of items, so grouping won't work here. The SQL equivalent for this would be an additional field contract_count as below: SELECT *, (SELECT count(contract_number) FROM table where t.contract_number = contract_number) as contract_count FROM table as t The question is how to do it with a Python object. After some research, I have found out that for more complex queries the Queryset extra method should be used. Below is one of my tries, but the result is not what I have expected queryset = Tracker.objects.extra( select={ 'contract_count': ''' SELECT COUNT(*) FROM table WHERE contract_number = %s ''' },select_params=(F('contract_number'),),) My models.py: class Tracker(models.Model): contract_number = models.IntegerField() EDIT: The solution to my problem was Subquery()
tagged with: extra
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51151006
linked to: http://stackoverflow.com/q/42543978
has answer: http://stackoverflow.com/a/74665551
type: Question
upvote count: 4
answer count: 2
has title: Django QuerySet: additional field for counting value's occurence
downvote count: 0
score: 4
tagged with: django-queryset
tagged with: sql
favorite count: 0

http://stackoverflow.com/comment/89198822
score: 0
comment on: http://stackoverflow.com/q/51105841
has text: Just use `[e for i, e in enumerate(y) for j in range(x[i])]`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51013537
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51013630
tagged with: django-templates
type: Question
tagged with: frameworks
tagged with: django-models
has title: django.urls.exceptions.NoReverseMatch: Reverse for 'favorite' not found
score: 0
has body: Django version 2.0 views.py from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/details.html' details.html {% extends 'music/base.html' %} {% block body %} &lt;!-- {{album}} --&gt; &lt;img src="{{album.album_logo}}"&gt; &lt;h1&gt;{{album.album_title}}&lt;/h1&gt; &lt;h3&gt;{{album.artist}}&lt;/h3&gt; {% if error_message %} &lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt; {% endif %} &lt;form action="{% url 'music:favorite' album.id %}" method="post"&gt; {% csrf_token %} {% for song in album.song_set.all %} &lt;input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}"&gt; &lt;label for="song{{ forloop.counter }}"&gt; {{ song.song_title }} {% if song.is_favorite %} &lt;img src="http://i.imgur.com/b9b13Rd.png" /&gt; {% endif %} &lt;/label&gt;&lt;br&gt; {% endfor %} &lt;input type="submit" value="Favorite"&gt; &lt;/form&gt; {% endblock %} index.html {% extends 'music/base.html' %} {% block body %} {% if all_albums %} &lt;h3&gt;Here are all my Albums:&lt;/h3&gt; &lt;ul&gt; {% for album in all_albums %} &lt;li&gt;&lt;a href="{% url 'music:details' album.id %}"&gt;{{ album.album_title }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;h3&gt;You don't have any albums&lt;/h3&gt; {% endif %} {% endblock %} base.html &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;Viberr&lt;/title&gt; {% load staticfiles %} &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /&gt; &lt;link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type="text/css"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /&gt; &lt;script src="https://ajax.googleapis.com/aja…
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/51116797
favorite count: 0
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/51116878
type: Question
has body: I am new to Python, I need to get title, isbn, price and publication date for my very first crawler. Pocket Anatomy and Physiology, 3rd Edition Shirley A. Jones ISBN-13: 978-0-8036-5658-1 $39.95 (US) Add to Cart Publication Date: 10/12/2016 Available
has comment: http://stackoverflow.com/comment/89221246
downvote count: 5
score: -4
answer count: 1
accepted answer: http://stackoverflow.com/a/51116878
has title: How to extract divs and classes

http://stackoverflow.com/a/51069549
has comment: http://stackoverflow.com/comment/106000151
has body: 2 issues here: no need to extra-quote the filename. It's passed to the system literally and since there's no file called "/tmp/something" the command fails. second, to be able to pass a pipe, you need shell=True so quickfix: command = ["raster2pgsql", "-a", file_name, self.schema_name + "." + identifier, "|", "psql", "-h", "localhost", "-p", "5432", "-d", self.dbname] run(command,shell=True) or using a command string (because shell=True is picky with argument list): command = "raster2pgsql -a "+ file_name + " " + self.schema_name + "." + identifier + " | psql -h localhost -p 5432 -d" + self.dbname run(command,shell=True) (ugly, isn't it?) It's much better to run 2 processes without shell=True and pipe them together using python, more portable &amp; secure (not sure how shell=True reacts with an argument list on Linux): from subprocess import * command1 = ["raster2pgsql", "-a", file_name, self.schema_name + "." + identifier] p = Popen(command1,stdout=PIPE) command2 = ["psql", "-h", "localhost", "-p", "5432", "-d", self.dbname] run(command2,stdin=p.stdout) The first Popen object created writes its output to a pipe (thanks to stdout=PIPE argument). The run function can take an input as a pipe too (thanks to stdin=p.stout). It consumes the output of the first command, creating a native piped chain of commands, without the need of the shell (and the caveats of quoting, spaces, special character interpretation and such...)
upvote count: 5
has comment: http://stackoverflow.com/comment/106030463
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/106000222
has comment: http://stackoverflow.com/comment/127143749
accepted answer of: http://stackoverflow.com/q/51069486
type: Answer
answers question: http://stackoverflow.com/q/51069486

http://stackoverflow.com/q/51021237
has comment: http://stackoverflow.com/comment/89036714
type: Question
has comment: http://stackoverflow.com/comment/89035473
answer count: 1
has answer: http://stackoverflow.com/a/51021388
score: 0
has comment: http://stackoverflow.com/comment/89035009
tagged with: python
accepted answer: http://stackoverflow.com/a/51021388
type: AnsweredQuestion
tagged with: syntax
has title: An Python syntax error in my script
has body: text = open(name + ".txt", "w") text.write(con_person + "\n" + con_key_words_list+ "\n" + con_person_rand + "\n" + con_person_rev_rand + "\n" + con_person_up_rand + "\n" + con_person_up_rev_rand + "\n" + con_key_words_list_rand + "\n" + con_key_words_list_rev_rand + "\n" + con_per_per + "\n" + con_per_perrev + "\n" + con_per_perup + "\n" + con_per_kw + "\n" + con_per_kwr + "\n" + con_per_brith02 + "\n" + con_per_brith04 + "\n" + con_per_brith06 + "\n" + con_per_brith68 + "\n" + con_per_rev_brith02 + "\n" + con_per_rev_brith04 + "\n" + con_per_rev_brith06 + "\n" + con_per_rev_brith68 + "\n" con_kw_per + "\n" + con_kw_per_rev + "\n" + con_kw_per_up + "\n" + con_kw_per_up_rev + "\n" + con_kw_kw + "\n" + con_kw_kwr + "\n" + con_kw_brith02 + "\n" + con_kw_brith04 + "\n" + con_kw_brith06 + "\n" + con_kw_brith68 + "\n" + con_kwr_kwr + "\n" + con_kwr_kw + "\n" + con_kwr_brith02 + "\n" + con_kwr_brith04 + "\n" + con_kwr_brith06 + "\n" + con_kwr_brith68) text.close() E0001:invalid syntax (, line 259) I don't see anything wrong in this line please help.

http://stackoverflow.com/a/51095114
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89178464
has comment: http://stackoverflow.com/comment/89178379
has comment: http://stackoverflow.com/comment/89178416
type: Answer
has comment: http://stackoverflow.com/comment/89178581
has body: First need columns names with lowercase year and month and pandas version 0.18.1+. Then use to_datetime for convert by multiple columns with strftime for strings: df['MonthYear']=pd.to_datetime(df.assign(day=1)'year','month','day').dt.strftime('%m-%Y') print (df) Sr. month year MonthYear 0 1.0 3.0 2015.0 03-2015 1 2.0 6.0 2018.0 06-2018 2 3.0 9.0 2017.0 09-2017 3 4.0 NaN NaN NaT 4 5.0 5.0 2015.0 05-2015 print (type(df.loc[0, 'MonthYear'])) &lt;class 'str'&gt; Similar for month period use to_period: df['MonthYear'] = pd.to_datetime(df.assign(day=1)'year','month','day').dt.to_period('m') print (df) Sr. month year MonthYear 0 1.0 3.0 2015.0 2015-03 1 2.0 6.0 2018.0 2018-06 2 3.0 9.0 2017.0 2017-09 3 4.0 NaN NaN NaT 4 5.0 5.0 2015.0 2015-05 print (type(df.loc[0, 'MonthYear'])) &lt;class 'pandas._libs.tslibs.period.Period'&gt;
score: 2
has comment: http://stackoverflow.com/comment/89178605
downvote count: 0
has comment: http://stackoverflow.com/comment/89178454
has comment: http://stackoverflow.com/comment/89178423
accepted answer of: http://stackoverflow.com/q/51095085
answers question: http://stackoverflow.com/q/51095085
upvote count: 2
has comment: http://stackoverflow.com/comment/89178707

http://stackoverflow.com/a/51139530
has comment: http://stackoverflow.com/comment/89274453
type: Answer
has body: This solution is quite awful if you have a large dataframe, but here something different and simpler from your solution (which is nice): pd.qcut(np.concatenate([[s]*v for s,v in zip(df.s, df.v)]), 3, labels=[-1,0,1]) You may check before with cumsum on v if your computer is going to explode before...
answers question: http://stackoverflow.com/q/51133009
score: 0

http://stackoverflow.com/a/51146920
score: 19
upvote count: 19
downvote count: 0
has comment: http://stackoverflow.com/comment/89280613
accepted answer of: http://stackoverflow.com/q/51146723
answers question: http://stackoverflow.com/q/51146723
type: AcceptedAnswer
has body: It is generally not good practice to use manipulate sys.path within a python library or program. You should add the relevant paths to the PYTHONPATH in the calling environment for your python program: PYTHONPATH="/path/to/other/projects/directory:$PYTHONPATH" python ... or export PYTHONPATH="/path/to/other/projects/directory:$PYTHONPATH" python ... This allows you to easily manipulate the paths that your program or library will search for dependencies easily without modifying your code. It is also very easy to manage this in your personal development environment by modifying your bashrc or in your production environments in your init script (or other wrapper script) and provides you with one place to update each time you add or modify your project paths. Given that you mention that you have almost one directory per .py file, you should also consider how your code might be organized into packages to further simplify your setup.
type: Answer

http://stackoverflow.com/q/51048407
possible better answer: http://stackoverflow.com/a/51051565
has answer: http://stackoverflow.com/a/51051565
tagged with: django
type: AnsweredQuestion
has body: I have Char objects with ManyToMany relationships to Source objects. Because a Char can appear in many Sources and many Sources can contain multiple Chars. The MtM relationship goes through a through table which also contains page number. In my API response, which I built using the Django REST framework I want to avoid resolving the full Source title, author etc. for every Char. Rather, in order to reduce the size of the JSON response, I want to refer it by id and include a sources section so the client can look it up. I.e. a client visiting /api/char/26 should get the following response: "chars": [ { "id": 26, "name": "龜", "locations": [ { "page": 136, "source": 1 }, { "page": 162, "source": 1 } ] } ], "sources": [ { "id": 1, "title": "Bruksanvisning Foamglass", "author": "Bluppfisk" } ] Here's the API view: class CharAPIView(generics.RetrieveAPIView): queryset = Char.objects.all() serializer_class = CharSerializer and the Serializers: class CharSerializer(serializers.ModelSerializer): locations = serializers.SerializerMethodField() class Meta: model = Char fields = ('id', 'name', 'locations',) depth = 1 def get_locations(self, obj): qset = CharInSource.objects.filter(char=obj) return [CharInSourceSerializer(m).data for m in qset] class CharInSourceSerializer(serializers.ModelSerializer): class Meta: model = CharInSource fields = ('page', 'source',) The problem is I do not know how to hook into the generics.RetrieveAPIView class so it will include a list of relevant sources. I've been digging through the source, but I cannot figure out how to even get the pk value.
accepted answer: http://stackoverflow.com/a/51060677
type: Question
score: 0
answer count: 2
tagged with: django-rest-framework
has title: Django Rest framework: custom API response
tagged with: python
has answer: http://stackoverflow.com/a/51060677

http://stackoverflow.com/a/51150028
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/89284875
answers question: http://stackoverflow.com/q/51149934
type: Answer
has body: This is what you need. ./manage.py ./hello_project/__init__.py ./hello_project/urls.py ./hello_project/hello/__init__.py ./hello_project/hello/urls.py ./hello_project/hello/views.py ./hello_project/settings.py ./hello_project/urls.py from django.conf.urls import include, url urlpatterns = [ url(r'^hello/', include('hello_project.hello.urls')), ] ./hello_project/hello/urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^hello1', views.hello1), url(r'^hello2', views.hello2), ] ./hello_project/hello/views.py from django.http import HttpResponse def hello1(request): return HttpResponse('hello1\n') def hello2(request): return HttpResponse('hello2\n') ./hello_project/settings.py .. INSTALLED_APPS = [ .... 'hello_project.hello' ] .. https://docs.djangoproject.com/en/1.11/ref/urls/#url In action: bash-4.4$ curl http://127.0.0.1:8000/hello/hello1 hello1 bash-4.4$ curl http://127.0.0.1:8000/hello/hello2 hello2 PS. Don't be afraid of "code" / "too many lines of code". Look at the zen of python for inspiration. Full source: https://files.fm/down.php?i=78kartk (available for 2 weeks, then it dies.)
upvote count: 1
has comment: http://stackoverflow.com/comment/89283676

http://stackoverflow.com/comment/89222984
has text: Thanks, that was what I had before, but it would bring up the error: NameError: name 'Robot' is not defined. So, if I change it to your suggestion, I just get a new error.
type: QuestionComment
comment on: http://stackoverflow.com/q/51118428
score: 0
type: Comment

http://stackoverflow.com/q/51014504
accepted answer: http://stackoverflow.com/a/51014859
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: heroku
has title: Allow communication between multiple python files
has answer: http://stackoverflow.com/a/51014859
score: 0
answer count: 1
tagged with: github
has body: I am using github to store my code so heruku can use it My question is how would I create two python scripts in github and have one store all the static data and allow the other script to read from the first script? Also would I need to update my 'Procfile'. All I currently have in there is 'worker: python main.py' where main is one of my scripts. I would like to add another script called 'staticData.py' Here is my github if it helps: https://github.com/MeHead/lol_BOT I'm fairly new to all this so a more explained answer would be appreciated Thanks!

http://stackoverflow.com/comment/89238852
has text: A possibility is to use pipes. And also that’s why I mentioned multithreading instead of multiprocessing. There you can share.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51124688
type: AnswerComment

http://stackoverflow.com/a/54443920
upvote count: 32
has body: What I did was first I installed python 3.7 and then unlinked it using the following commands brew install python3 brew unlink python then I installed python 3.6.5 using the following command taken from above answer. brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb --ignore-dependencies After that I ran the following command brew link --overwrite python Now I have all pythons in the system. To find out run mian@tdowrick2~ $ python --version Python 2.7.10 mian@tdowrick2~ $ python3.7 --version Python 3.7.1 mian@tdowrick2~ $ python3.6 --version Python 3.6.5 To create Python 3.7 virtual environment. mian@tdowrick2~ $ virtualenv -p python3.7 env Already using interpreter /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7' New python executable in /Users/mian/env/bin/python3.7 Also creating executable in /Users/mian/env/bin/python Installing setuptools, pip, wheel... done. mian@tdowrick2~ $ source env/bin/activate (env) mian@tdowrick2~ $ python --version Python 3.7.1 (env) mian@tdowrick2~ $ deactivate To create Python 3.6 virtual environment mian@tdowrick2~ $ virtualenv -p python3.6 env Running virtualenv with interpreter /usr/local/bin/python3.6 Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/mian/env/bin/python3.6 Not overwriting existing python script /Users/mian/env/bin/python (you must use /Users/mian/env/bin/python3.6) Installing setuptools, pip, wheel... done. mian@tdowrick2~ $ source env/bin/activate (env) mian@tdowrick2~ $ python --version Python 3.6.5 (env) mian@tdowrick2~ $ deactivate
downvote count: 2
answers question: http://stackoverflow.com/q/51125013
has comment: http://stackoverflow.com/comment/100394654
score: 30
type: Answer
has comment: http://stackoverflow.com/comment/98474113
has comment: http://stackoverflow.com/comment/98491776

http://stackoverflow.com/a/56251556
upvote count: 27
answers question: http://stackoverflow.com/q/51117503
score: 27
downvote count: 0
has comment: http://stackoverflow.com/comment/99411256
has body: You need to install the following dependencies before installing mysqlclient for python 3.7 in your system. sudo apt-get install python3.7-dev default-libmysqlclient-dev I hope this will help you.
has comment: http://stackoverflow.com/comment/99944720
type: Answer

http://stackoverflow.com/q/51103686
upvote count: 3
answer count: 2
linked to: http://stackoverflow.com/q/26763344
has answer: http://stackoverflow.com/a/51103711
duplicate of: http://stackoverflow.com/q/26763344
type: UnansweredQuestion
tagged with: pandas
score: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: datetime
has title: Converting pandas Column to datetime
tagged with: python
has answer: http://stackoverflow.com/a/51103727
has body: I am trying to convert a pandas column to datetime. This is my error message. ValueError: time data '01-JUN-17 00:00:00' does not match format '%d-%b-%y %H.%M.%S' (match) This is my code : df['dayofservice'] = pd.to_datetime(df['dayofservice'], format = '%d-%b-%y %H.%M.%S') I have read this documentation to ensure my format is correct : https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior It's still not working for me.

computer-vision
tags question: http://stackoverflow.com/q/51036169
tags question: http://stackoverflow.com/q/51133545
tags question: http://stackoverflow.com/q/51084825
tags question: http://stackoverflow.com/q/51133962
tags question: http://stackoverflow.com/q/51077912
tags question: http://stackoverflow.com/q/51097659
tags question: http://stackoverflow.com/q/51128826
tags question: http://stackoverflow.com/q/51127257
tags question: http://stackoverflow.com/q/51146638
tags question: http://stackoverflow.com/q/51022381
tags question: http://stackoverflow.com/q/51054627
tags question: http://stackoverflow.com/q/51089781
tags question: http://stackoverflow.com/q/51073309
tags question: http://stackoverflow.com/q/51100191
tags question: http://stackoverflow.com/q/51084289
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/51028456

http://stackoverflow.com/comment/89184928
comment on: http://stackoverflow.com/a/51098418
has text: OK, there are also some more typos in setExistingDirectory like "return folder" vs. "return Folder".
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51088796
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51098856
type: Question
answer count: 2
downvote count: 5
accepted answer: http://stackoverflow.com/a/51088905
has comment: http://stackoverflow.com/comment/89166038
has comment: http://stackoverflow.com/comment/89166016
has answer: http://stackoverflow.com/a/51098856
has answer: http://stackoverflow.com/a/51088905
favorite count: 0
score: -4
upvote count: 1
tagged with: python
has body: I am hoping someone can explain this to me. Given the following dictionary: users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27} The following for loop: for k in users: print(k, '=&gt;', users[k]) firstname =&gt; John lastname =&gt; Smith age =&gt; 27 results in the same output as the one below: for k, v in users.items(): print(k, '=&gt;', v) firstname =&gt; John lastname =&gt; Smith age =&gt; 27 I understand the 2nd loop syntax and how it works, but the 1st one is confusing for me. Dictionaries have key/value pairs but it looks like the top one is only looping through the keys, how does it output the values? Just looking at it I'd expect it to print: firstname =&gt; firstname lastname =&gt; lastname age =&gt; age But clearly it doesn't
tagged with: dictionary
has title: Python Dictionary output
has comment: http://stackoverflow.com/comment/89166056

http://stackoverflow.com/a/51053979
answers question: http://stackoverflow.com/q/51044941
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: It's hard to tell, but that is not part of the grid or axis, but part of the view. You can hide it using configure_view(strokeOpacity=0): import pandas as pd import altair as alt budget = pd.read_csv("https://github.com/chris1610/pbpython/raw/master/data/mn-budget-detail-2014.csv") budget_top_10 = budget.sort_values(by='amount',ascending=False)[:10] alt.Chart(budget_top_10).mark_bar().encode( x='detail', y='amount' ).configure_view( strokeOpacity=0 )
type: Answer
accepted answer of: http://stackoverflow.com/q/51044941

http://stackoverflow.com/q/51101432
linked to: http://stackoverflow.com/q/44741587
has answer: http://stackoverflow.com/a/71358486
score: 9
has answer: http://stackoverflow.com/a/52772591
has answer: http://stackoverflow.com/a/51102245
tagged with: python
has answer: http://stackoverflow.com/a/51102096
has comment: http://stackoverflow.com/comment/89191024
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51102096
type: Question
linked to: http://stackoverflow.com/q/2413391
upvote count: 9
has answer: http://stackoverflow.com/a/58400241
linked to: http://stackoverflow.com/q/538666
has title: timedelta to string type in pandas dataframe
has answer: http://stackoverflow.com/a/62443664
has body: I have a dataframe df and its first column is timedelta64 df.info(): &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 686 entries, 0 to 685 Data columns (total 6 columns): 0 686 non-null timedelta64[ns] 1 686 non-null object 2 686 non-null object 3 686 non-null object 4 686 non-null object 5 686 non-null object If I print(df[0][2]), for example, it will give me 0 days 05:01:11. However, I don't want the 0 days filed. I only want 05:01:11 to be printed. Could someone teaches me how to do this? Thanks so much!
tagged with: pandas
downvote count: 0
tagged with: timedelta
answer count: 7
has comment: http://stackoverflow.com/comment/89190930
has answer: http://stackoverflow.com/a/64801834
favorite count: 0
possible better answer: http://stackoverflow.com/a/52772591

http://stackoverflow.com/q/51046034
tagged with: numba
tagged with: python
has title: Jupyter notebook (Python 3.6): ImportError: cannot import name 'prange'
type: Question
has answer: http://stackoverflow.com/a/51046667
upvote count: 0
score: -2
answer count: 1
has body: I am using numba to speedup my code. It runs fine in the terminal. But when I try to run it inside jupyter notebook, it gives error for import numba prange. I am using Numba 0.38.1. When I try import prange from the temrinal of jupyter, the import works fine. Can someone please guide me what could be the issue. Thanks From the terminal created from Jupyter From the notebook
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/89107236
type: Comment
type: QuestionComment
score: 0
has text: How do you expect the answer to look please?
comment on: http://stackoverflow.com/q/51056148

http://stackoverflow.com/q/51162129
has comment: http://stackoverflow.com/comment/89307694
tagged with: python
has comment: http://stackoverflow.com/comment/89307851
has answer: http://stackoverflow.com/a/51164456
has comment: http://stackoverflow.com/comment/89307747
has body: Is it possible to access class from inside function that was called inside its definition expression? def called_inside_definition(): # I want to access 'Foo' here class Foo: called_inside_definition() *The goal here is to provide alternative syntax for class decorator: @decorate class Foo: pass Update: Why I ask this in the first place I wanted to provide a decorator for defining delegated methods/attributes. class Bar: def grok(self): return 'grok' @delegate('bar', 'grok') class Foo: def __init__(self): self.bar = Bar() foo.grok() # 'grok' This works fine (gist here) but it gets a bit ugly if I'm delegating more than a couple of attributes: @delegate('bar', 'first, 'second', 'third', 'fourth') class Foo: ... So, I was wondering if it's possible do to it inside class definition itself. Something similar to Ruby syntax: class Foo def_delegators :bar :grok Doing it after the class is unoptimal because the reader than miss it. Full delegate definition: class Delegated(object): def __init__(self, delegated_name, attr): self.attr_name = attr self.delegated_name = delegated_name def __get__(self, instance, owner): if instance is None: return self else: return getattr(self.delegate(instance), self.attr_name) def __set__(self, instance, value): setattr(self.delegate(instance), self.attr_name, value) def __delete__(self, instance): delattr(self.delegate(instance), self.attr_name) def delegate(self, instance): return getattr(instance, self.delegated_name) class delegate(object): def __init__(self, src, *attrs): self.src = src self.attrs = attrs def __call__(this, cls): for attr in this.attrs: setattr(cls, attr, Delegated(this.src, attr)) return cls
upvote count: 1
possible better answer: http://stackoverflow.com/a/51162200
downvote count: 1
has comment: http://stackoverflow.com/comment/89307989
has comment: http://stackoverflow.com/comment/89307714
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51162200
has comment: http://stackoverflow.com/comment/89308049
has comment: http://stackoverflow.com/comment/89307773
has comment: http://stackoverflow.com/comment/89307806
has comment: http://stackoverflow.com/comment/89307675
accepted answer: http://stackoverflow.com/a/51164456
has comment: http://stackoverflow.com/comment/89307709
has title: Access class inside function that was called inside class definition expression
type: Question
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/89311619
score: 0
has comment: http://stackoverflow.com/comment/89307719

http://stackoverflow.com/comment/89149264
has text: I will accept it as when there will be no other answers to evaluate no pressure, please!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51077781
type: Comment

http://stackoverflow.com/comment/89171497
score: 0
type: Comment
type: QuestionComment
has text: So it's 13 + 1.5 + 2 + (3.75 X 2) yes?
comment on: http://stackoverflow.com/q/51091558

http://stackoverflow.com/q/51107587
type: Question
has title: Matplotlib Draw Polygons of different color
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51110072
type: UnansweredQuestion
tagged with: python
has body: I want to draw polygons using fill(). How can I draw polygons of different color? It seems to me that I can only use one color. I tried a list with three color values per polygon but I keep getting this error: length of rgba sequence should be either 3 or 4. The only thing that worked is an array with three color values. But this leads to polygons of the same color. Why does something simple as color=np.random.rand(3,num_polygons) not work? import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_axes([0.,0.,1.,1.]) num_polygons = 2 x = np.random.randn(3,num_polygons) y = np.random.randn(3,num_polygons) ax.fill(x,y,color=[0.8,0.3,0.2]) # &lt;--- ?? plt.show() What did I miss?
score: 1
upvote count: 1

http://stackoverflow.com/q/51047829
tagged with: hex
linked to: http://stackoverflow.com/q/4057475
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89133850
tagged with: javascript
tagged with: rgb
has title: How to deduce the relative percentage value of a color using a color gradient
type: Question
score: 0
has body: I'm need to write something that will take a color (via any format, hex, rgb, etc), and based on where that color would be found on a specific color gradient, a percentage value can be calculated. Color Scale % HEX R G B HUE SATURATION VALUE 0% #FFFFFF 255 255 255 0° 0.0% 100.0% 10% #FFE98E 255 233 142 48° 44.3% 100.0% 25% #FFD072 255 208 114 40° 55.3% 100.0% 50% #FCB119 252 177 25 40° 90.1% 98.8% 75% #FA7E21 250 126 33 26° 86.8% 98.0% 100% #E75800 231 88 0 23° 100.0% 90.6% (An actual image of the colors can be found in this gist) For example, if the color ends up being #FFE8BA, then that would land somewhere between 0% and 10%. Its not so much the specific code I'm asking help for (I haven't even decided what language to use, but it'll likely be either JS or Python), it's more about the specifics on how to analyze a color and compare it to a specific color gradient to return a color. If anyone has any experience doing something like this, any advice would be appreciated. Thanks!
answer count: 1
tagged with: colors
has answer: http://stackoverflow.com/a/51051020
accepted answer: http://stackoverflow.com/a/51051020
has comment: http://stackoverflow.com/comment/89086920
tagged with: python
has comment: http://stackoverflow.com/comment/89086880

http://stackoverflow.com/a/51093351
has comment: http://stackoverflow.com/comment/89174974
answers question: http://stackoverflow.com/q/51093175
type: Answer
has comment: http://stackoverflow.com/comment/89194048
has body: Setup df = pd.DataFrame() df['ID'] =[ np.nan, 2,4, np.nan,8, np.nan ,'16-18',25, '30-31'] Then first build your "ID" for the ranges s = df.ID.str.split("-") s2 = s[s.notna()].apply(lambda x: ("ID "+pd.Series(list(range(int(x[0]), int(x[1])+1))).astype(str)).tolist()) and then for the regular cases (except NaNs and ranges) non_na = df.ID[df.ID.notna()] non_na_range = non_na[~non_na.index.isin(s2.index)] s3 = "ID " + non_na_range.astype(str) Then assign df.loc[s2.index, "ID"] = s2 df.loc[s3.index, "ID"] = s3 Output ID 0 NaN 1 ID 2 2 ID 4 3 NaN 4 ID 8 5 NaN 6 [ID 16, ID 17, ID 18] 7 ID 25 8 [ID 30, ID 31]
score: 0

http://stackoverflow.com/comment/89113816
comment on: http://stackoverflow.com/a/51048069
has text: Thank you very much this is exactly what I was looking for very helpful!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51072046
type: Answer
score: 1
upvote count: 1
has body: You can simply use the groupby function available in pandas with restriction to the concerned columns : ptid_ages_noshow'PatientId','Ages'.groupby('PatientId').mean()
downvote count: 0
answers question: http://stackoverflow.com/q/51071927

http://stackoverflow.com/a/51083023
type: Answer
has comment: http://stackoverflow.com/comment/89154545
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89154488
accepted answer of: http://stackoverflow.com/q/51082922
answers question: http://stackoverflow.com/q/51082922
type: AcceptedAnswer
downvote count: 0
has body: IIUC, use idxmin in apply with rolling: df'L','H' = (df.reindex(df['Open'].rolling(5) .apply(lambda x: x.idxmin(), raw=False))'Low','High'.values) Output: Date Open High Low L H 5303 2018-06-11 1681.51 1694.24 1680.59 NaN NaN 5304 2018-06-12 1693.00 1699.51 1691.52 NaN NaN 5305 2018-06-13 1702.81 1713.75 1700.12 NaN NaN 5306 2018-06-14 1713.48 1724.80 1708.87 NaN NaN 5307 2018-06-15 1714.00 1720.87 1708.52 1680.59 1694.24 5308 2018-06-18 1706.26 1726.74 1702.56 1691.52 1699.51 5309 2018-06-19 1709.04 1736.11 1700.39 1700.12 1713.75 5310 2018-06-20 1742.50 1762.93 1741.36 1702.56 1726.74 5311 2018-06-21 1760.00 1763.10 1717.56 1702.56 1726.74 5312 2018-06-22 1742.62 1743.00 1711.90 1702.56 1726.74

http://stackoverflow.com/comment/89038047
has text: Please refer to `code_for_2` and `code_for_3`. But it seems that it's really hard to say what happens under the hood in `list(map(...))`.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51022553

http://stackoverflow.com/a/51014994
type: Answer
has comment: http://stackoverflow.com/comment/89023424
has comment: http://stackoverflow.com/comment/89047498
score: 2
has comment: http://stackoverflow.com/comment/89047545
accepted answer of: http://stackoverflow.com/q/51014463
has body: You can do all this! Assigning the same tag to multiple texts has almost the same effect as would combining those texts into one larger text, and assigning it that tag. The slight differences would be for Doc2Vec modes where there's a context-window – PV-DM (dm=1). With separate texts, there'd never be contexts stretching across the end/beginning of sentences. In fact, as gensim's optimized code paths have a 10,000-token limit to text sizes, splitting larger documents into subdocuments, but repeating their tags is sometimes necessary as a workaround. What you've specifically proposed, training both the full-doc, and the doc-fragments, would work, but also have the effect of doubling the amount of text (and thus training-attention/individual-prediction-examples) for the 'doc1' tags, compared to the narrower per-sentence tags. You might want that, or not - it could affect the relative quality of each. What's best is unclear - it depends on your corpus, and end goals, so should be determined through experimentation, with a clear end-evaluation so that you can automate/systematize a rigorous search for what's best. A few relevant notes, though: Doc2Vec tends to works better with docs of at least a dozen or more words per document. The 'words' need to be tokenized - a list-of-strings, not a string. It benefits from a lot of varied data, and in particular if you're training a larger model – more unique tags (including overlapping ones), and many-dimension vectors – you'll need more data to avoid overfitting.
has comment: http://stackoverflow.com/comment/89262772
has comment: http://stackoverflow.com/comment/89047077
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89047199
has comment: http://stackoverflow.com/comment/89262948
upvote count: 2
answers question: http://stackoverflow.com/q/51014463

keras
tags question: http://stackoverflow.com/q/51015928
tags question: http://stackoverflow.com/q/51078007
tags question: http://stackoverflow.com/q/51101655
tags question: http://stackoverflow.com/q/51029779
tags question: http://stackoverflow.com/q/51066299
tags question: http://stackoverflow.com/q/51100042
tags question: http://stackoverflow.com/q/51117351
tags question: http://stackoverflow.com/q/51053396
tags question: http://stackoverflow.com/q/51145007
tags question: http://stackoverflow.com/q/51072469
tags question: http://stackoverflow.com/q/51073614
tags question: http://stackoverflow.com/q/51089334
tags question: http://stackoverflow.com/q/51032625
tags question: http://stackoverflow.com/q/51054329
tags question: http://stackoverflow.com/q/51030922
tags question: http://stackoverflow.com/q/51132467
tags question: http://stackoverflow.com/q/51093896
tags question: http://stackoverflow.com/q/51032845
tags question: http://stackoverflow.com/q/51017096
tags question: http://stackoverflow.com/q/51091553
tags question: http://stackoverflow.com/q/51139888
tags question: http://stackoverflow.com/q/51109215
tags question: http://stackoverflow.com/q/51119874
tags question: http://stackoverflow.com/q/51141408
tags question: http://stackoverflow.com/q/51060627
tags question: http://stackoverflow.com/q/51038878
tags question: http://stackoverflow.com/q/51049890
tags question: http://stackoverflow.com/q/51075666
tags question: http://stackoverflow.com/q/51126531
tags question: http://stackoverflow.com/q/51031519
tags question: http://stackoverflow.com/q/51034355
tags question: http://stackoverflow.com/q/51025335
tags question: http://stackoverflow.com/q/51151941
tags question: http://stackoverflow.com/q/51059382
tags question: http://stackoverflow.com/q/51014044
tags question: http://stackoverflow.com/q/51083523
tags question: http://stackoverflow.com/q/51117763
tags question: http://stackoverflow.com/q/51030924
tags question: http://stackoverflow.com/q/51067176
tags question: http://stackoverflow.com/q/51047676
tags question: http://stackoverflow.com/q/51161990
tags question: http://stackoverflow.com/q/51105703
tags question: http://stackoverflow.com/q/51020482
tags question: http://stackoverflow.com/q/51140276
tags question: http://stackoverflow.com/q/51063969
tags question: http://stackoverflow.com/q/51150468
tags question: http://stackoverflow.com/q/51047041
tags question: http://stackoverflow.com/q/51156885
tags question: http://stackoverflow.com/q/51132991
tags question: http://stackoverflow.com/q/51046867
tags question: http://stackoverflow.com/q/51042721
tags question: http://stackoverflow.com/q/51100054
tags question: http://stackoverflow.com/q/51127344
tags question: http://stackoverflow.com/q/51016220
tags question: http://stackoverflow.com/q/51064649
tags question: http://stackoverflow.com/q/51152582
tags question: http://stackoverflow.com/q/51137299
tags question: http://stackoverflow.com/q/51123517
tags question: http://stackoverflow.com/q/51124307
tags question: http://stackoverflow.com/q/51096667
tags question: http://stackoverflow.com/q/51091596
tags question: http://stackoverflow.com/q/51076211
tags question: http://stackoverflow.com/q/51132802
tags question: http://stackoverflow.com/q/51118784
tags question: http://stackoverflow.com/q/51075071
tags question: http://stackoverflow.com/q/51118032
tags question: http://stackoverflow.com/q/51166806
tags question: http://stackoverflow.com/q/51053565
tags question: http://stackoverflow.com/q/51099500
tags question: http://stackoverflow.com/q/51110834
tags question: http://stackoverflow.com/q/51159010
tags question: http://stackoverflow.com/q/51148876
tags question: http://stackoverflow.com/q/51148385
tags question: http://stackoverflow.com/q/51140950
tags question: http://stackoverflow.com/q/51109639
tags question: http://stackoverflow.com/q/51081439
tags question: http://stackoverflow.com/q/51114771
tags question: http://stackoverflow.com/q/51039800
tags question: http://stackoverflow.com/q/51141572
tags question: http://stackoverflow.com/q/51110110

http://stackoverflow.com/comment/89257508
type: Comment
score: 0
has text: Don't know Flask-Restful, but in pure Flask, you can use routes with variables, see flask docs: http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules
type: QuestionComment
comment on: http://stackoverflow.com/q/51136621

http://stackoverflow.com/comment/89283155
comment on: http://stackoverflow.com/q/51143201
score: 0
type: Comment
type: QuestionComment
has text: it should work with your static value. your snippet is too simplified, show more code

http://stackoverflow.com/comment/89312394
comment on: http://stackoverflow.com/q/51151664
score: 0
type: Comment
type: QuestionComment
has text: I'm really sorry, I'm new to this page. I've edited it to be a little clearer now. Thanks for the feedback.

http://stackoverflow.com/comment/89208247
comment on: http://stackoverflow.com/q/51110318
has text: What flags are shown for the name?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51083091
downvote count: 0
has comment: http://stackoverflow.com/comment/89154740
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51082969
answers question: http://stackoverflow.com/q/51082969
has body: You can use aggregate() and F expressions for that: from django.db.models import Avg, F Model.objects.aggregate(average_delta=Avg(F('done_at') - F('created_at')))
upvote count: 5
has comment: http://stackoverflow.com/comment/89156531
type: AcceptedAnswer

http://stackoverflow.com/q/51032737
favorite count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/89058379
has comment: http://stackoverflow.com/comment/89058700
has body: i have tried to receive data form my connection by this code on python 2.7 : server = socket(AF_INET, SOCK_STREAM) server.bind(('0.0.0.0', 21)) server.listen(1) client , addr = server.accept() data = client.recv(2048) When i have to print or send to another connection my data it's working , however i want to add those lines : if(data == "/disconnect") : &lt;disconnect blha blha... you know &gt; else : &lt;print the data and send it back blha blha... &gt; ( i have checked without that if statement and " disconnect blha blha .. " works nicely ) it's just pass the code so when my client requests to disconnect the request is sent to the server as the "original" messages .. (the sever don't kick him) what should i do ? Thanks !
has title: How to receive data and use it on if () statement?
has comment: http://stackoverflow.com/comment/89057769
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/89124786
upvote count: 0
has comment: http://stackoverflow.com/comment/89113036
has comment: http://stackoverflow.com/comment/89057802
answer count: 1
has comment: http://stackoverflow.com/comment/89057840
has answer: http://stackoverflow.com/a/51068092
linked to: http://stackoverflow.com/q/17664544

http://stackoverflow.com/comment/89202491
type: QuestionComment
score: 0
has text: what exactly is the issue here? Question seems unclear.
type: Comment
comment on: http://stackoverflow.com/q/51107699

http://stackoverflow.com/comment/89023578
has text: No i mean i also post the code but it just can't and i don't know how to add more details
comment on: http://stackoverflow.com/q/51015273
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89166852
comment on: http://stackoverflow.com/a/51088708
type: Comment
has text: `df.loc[pd.IndexSlice[data.index, 'GOOG'], 'MSFT']` gives me an error `TypeError: unhashable type: 'DatetimeIndex'`
type: AnswerComment
score: 0

http://stackoverflow.com/q/51072549
tagged with: matrix
accepted answer: http://stackoverflow.com/a/51072742
tagged with: multidimensional-array
tagged with: python
type: AnsweredQuestion
tagged with: oop
score: 0
type: Question
has answer: http://stackoverflow.com/a/51072742
has answer: http://stackoverflow.com/a/51072692
has comment: http://stackoverflow.com/comment/89134910
has title: multidimensional python list element assignment error
possible better answer: http://stackoverflow.com/a/51072692
has body: I am defining a class game with dimensions n,m. The init method creates creates two boards, one for each player class game: def __init__(self, n, m): rows = [0 for _ in range m] self.board1 = [rows for _ in range n] self.board2 = [rows for _ in range n] when i assign an value to board1[0][0] it also assigns the same value to board1[1][0], board1[2][0], ...board1[n][0] as well as board2[0-n][0] for example, game(3,4) game.board1[0][0] = 1 print("board 1: {}\nboard 2: {}).format(self.board1, self.board2)) returns board 1: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] board 2: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
answer count: 2

http://stackoverflow.com/q/51149247
has comment: http://stackoverflow.com/comment/89283051
downvote count: 3
has comment: http://stackoverflow.com/comment/89282371
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has title: Trying to simplify yet another if-else ladder in python
score: -3
tagged with: python
tagged with: if-statement
has body: I tried implementing the same logic as "Simplify a if - if ladder - python" which i had requested earlier to simplify a if else ladder. But for the life of me, i am not able to simplify this one. for each_component in component_objects: if each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'pe' and each_component['name'] == 'PE1': env_data['PE1_HOSTNAME'] = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'pe' and each_component['name'] == 'PE2': env_data['PE2_HOSTNAME'] = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'versadirector' and each_component['name'] == 'VersaDirector': env_data['VD_HOSTNAME'] = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'jump' and each_component['name'] == 'Jump': jump_ips = json.loads(each_component['ip_addr']) elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'versaanalytics' and each_component['name'] == 'VersaAnalytics1': analytics_1 = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'versaanalytics' and each_component['name'] == 'VersaAnalytics2': analytics_2 = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'versaanalytics' and each_component['name'] == 'VersaAnalytics3': analytics_3 = each_component['hostname'].split('.')[0] elif each_component['region_type'] == deploy_json['env_type'].upper() and each_component['component_type'] == 'versaanalytics' and each_component['name'] == 'VersaAnalytics4': analytics_4 …
type: Question
has answer: http://stackoverflow.com/a/51149487
linked to: http://stackoverflow.com/q/49421449
answer count: 1

http://stackoverflow.com/q/51080681
answer count: 1
linked to: http://stackoverflow.com/q/50355598
has comment: http://stackoverflow.com/comment/89156786
has answer: http://stackoverflow.com/a/51085292
tagged with: dataframe
has body: Just out of curiosity, if dask enables both len() and size, why is there not shape as well?
has comment: http://stackoverflow.com/comment/89149864
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51085292
has title: Why doesn't Dask dataframe have a shape attribute?
tagged with: dask
type: Question
has comment: http://stackoverflow.com/comment/89158777
tagged with: python
has comment: http://stackoverflow.com/comment/89153957
score: 0

http://stackoverflow.com/q/51020105
score: 0
has comment: http://stackoverflow.com/comment/89036840
has answer: http://stackoverflow.com/a/51020255
answer count: 1
tagged with: python
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51020255
tagged with: image-processing
has title: Explanation of 'elif' in Mouse as paint brush code
has body: OpenCV-Python 3.4.1 IDE - PyCharm My code: import numpy as np import cv2 as cv events = [i for i in dir(cv) if 'EVENT' in i] print(events) drawing = False # true if mouse is pressed mode = True # if True, draw rectangle. Press 'm' to toggle to curve ix,iy = -1,-1 # mouse callback function def draw_circle(event,x,y,flags,param): global ix,iy,drawing,mode if event == cv.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y elif event == cv.EVENT_MOUSEMOVE: if drawing == True: if mode == True: cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),5,(0,0,255),-1) elif event == cv.EVENT_LBUTTONUP: drawing = False if mode == True: # this part start cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),5,(0,0,255),-1) # this part end img = np.zeros((512,512,3), np.uint8) cv.namedWindow('image') cv.setMouseCallback('image',draw_circle) while(1): cv.imshow('image',img) k = cv.waitKey(1) &amp; 0xFF if k == ord('m'): mode = not mode elif k == 27: break cv.destroyAllWindows() I am trying to understand the OpenCV-Python code for using Mouse as paint brush. Link: https://docs.opencv.org/3.4.1/db/d5b/tutorial_py_mouse_handling.html Now, I have the following questions: What is the need of elif in function elif event == cv.EVENT_MOUSEMOVE: ? I mean why can't we use if instead of elif? I don't get why we use elif. What is the use of if mode == True: cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),5,(0,0,255),-1) I mean the 'this part' in the code? I tried to understand it but I couldn't. Please help.
type: Question
has comment: http://stackoverflow.com/comment/89036961
has comment: http://stackoverflow.com/comment/89036741

http://stackoverflow.com/q/51022870
has comment: http://stackoverflow.com/comment/89038344
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: row
tagged with: col
type: Question
answer count: 2
has title: Searching columns in a csv file
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51023171
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89038188
has comment: http://stackoverflow.com/comment/89042268
possible better answer: http://stackoverflow.com/a/51023029
accepted answer: http://stackoverflow.com/a/51023171
has answer: http://stackoverflow.com/a/51023029
has body: I have a program which generates a random name and a random question (both independent from eachother). I have created a function called QuestionGenerator() , and it should search through the second column of a csv file and write all the values to the array. def QuestionGenerator(): questionlist_file = open('StudentNames&amp;Questions.csv') reader = csv.reader(questionlist_file) rownum=0 array=[] for row in reader: array.append(row) rownum=rownum+1 i = random.randint(0,3) question = array[0,1] return question Currently it writes all the values in the file to the array, and not only the second column (question column). So the array should contain the following values array = ["Consequences of Devolution", "Sources of the Constitution"...."Reasons for a democratic deficit"] Please note the csv file is an excel spreadsheet saves as a .csv
upvote count: 2

http://stackoverflow.com/q/51069029
tagged with: exp
has answer: http://stackoverflow.com/a/51085715
has body: I am using scipy.optimize.basinhopping in order to fit a simple exponential function (aexp(-btime)) to real data. I try to have appropriate initial guesses (for a and b) but in some iterations (for some values basinhopping guesses) "overflow in exp" occurs. I know that it is because of a very large answer to be calculated by exp. By the way the result is something absolutely wrong. Is there anyway to ask the code to ignore those error containing guesses in order to prevent wrong results in output? + time goes from 0 to something around e+06 Thanks for your care and help
has comment: http://stackoverflow.com/comment/89159820
score: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89128380
tagged with: overflow
type: UnansweredQuestion
has title: overflow in exp using python scipy.optimize.basinhopping
type: Question

http://stackoverflow.com/a/51127226
answers question: http://stackoverflow.com/q/51127209
score: 25
has body: First of all, index is a list method. Here v is a numpy array and you need to do the following: v = np.random.randn(10) print(v) maximum = np.max(v) minimum = np.min(v) print(maximum, minimum) index_of_maximum = np.where(v == maximum) index_of_minimum = np.where(v == minimum) Get the elements using these indices: v[index_of_minimum] v[index_of_maximum] Verify using assert: assert(v[index_of_maximum] == v.max()) assert(v[index_of_minimum] == v.min())
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51127209
upvote count: 25

http://stackoverflow.com/comment/89193202
comment on: http://stackoverflow.com/q/51102896
has text: You need to define `__rmul__`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51114301
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51114313
has body: I need to change directory to my local working directory in windows and then open a file for processing. Its just a 3 lines code, as below: import csv import os os.chdir('D:\Projects\Initiatives\machine learning\programs\assertion') The error is as follows: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'D:\Projects\Initiatives\machine learning\programs\x07ssertion' Notice x07 character that has replaced character x07. I have a similar code but that goes through fine: import csv import os os.chdir('D:\Projects\Initiatives\machine learning\programs') with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') The only difference is directory assertion in the problematic code. I have tried single quoting, double quoting etc. for the chdir directive but nothing helps. I have also tried escaping as \assertion but that is not the issue
type: AnsweredQuestion
has title: error changing directory in Python
accepted answer: http://stackoverflow.com/a/51114313
type: Question
answer count: 1

http://stackoverflow.com/a/51055791
has body: Try manually setting the proxy pass URL to the port gunicorn is running the project on the server like: location / { proxy_pass http://localhost:8000; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 500; proxy_read_timeout 600; }
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51054061
type: Answer

http://stackoverflow.com/comment/89158165
has text: I see. Hypothetically - would `command = foo(x)` work if `foo(x)` itself created a function? Like with a function template?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51059104

http://stackoverflow.com/comment/89129619
comment on: http://stackoverflow.com/q/51064409
score: 0
type: Comment
type: QuestionComment
has text: Did you try with `.exe` extension?

http://stackoverflow.com/comment/89188217
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51096566
has text: It will help if you show a simple example.

http://stackoverflow.com/q/51125769
type: UnansweredQuestion
has body: I am trying to use a list that holds the column names for my groupby notation. My end goal is to loop through multiple columns and run the calculation without having to re-write the same line multiple times. Is this possible? a_list = list(['','BTC_','ETH_']) a_variable = ('{}ClosePrice'.format(a_list[0])) proccessing_data['RSI'] = proccessing_data.groupby('Symbol').**a_variable**.transform(lambda x: talib.RSI(x, timeperiod=14)) this is the error I currently get because it thinks I want the column 'a_variable' which doesn't exist. AttributeError: 'DataFrameGroupBy' object has no attribute 'a_variable'
tagged with: group-by
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89236513
score: 0
has title: Python pd using a variable with column name in groupby dot notation
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89236710
has answer: http://stackoverflow.com/a/51125786
tagged with: list

http://stackoverflow.com/comment/89106399
type: QuestionComment
comment on: http://stackoverflow.com/q/51057324
score: 0
type: Comment
has text: @jezrael Is there a way around this?

http://stackoverflow.com/q/51142365
tagged with: pyodbc
score: 3
answer count: 0
upvote count: 3
tagged with: unit-testing
type: Question
downvote count: 0
has title: Mock pyodbc objects for Python testing
has body: Disclaimer* I'm not asking how to inject my mock into my unit test with unittest.mock. This is about to how to model a mock of pyodbc. I need to get a mock of some pyodbc objects going so I can test various functions of my Python app, but i'm finding it exceptionally hard to do. Traditionally the way to do this is just to inherit from the object I want to mock and then override any troublesome methods or properties with static values to test against. However, when I try to inherit from pyodbc.Connection or pyodbc.Row i get the error: TypeError: type 'pyodbc.Connection' is not an acceptable base type I can grab the class objects themselves and pass them around, but that's not a good idea for a number of reasons, nor will the functionality of my tests be very representative of the deployment context. Anyone have an idea on how to do this in Python?
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51052765
answers question: http://stackoverflow.com/q/51052364
has comment: http://stackoverflow.com/comment/89113231
has body: okay..you changed the question. I leave my answer to your previous question. I Hope its helpful. You can use PyQt5. I've a folder with this: |-Project/ |--- images/ |----- 1.png |------2.png |--- app.py There are two buttons for example "cam" icon and "user" icon: from PyQt5 import QtCore, QtGui, QtWidgets import os class Ui_Example(QtWidgets.QMainWindow): def __init__(self, parent=None): super(Ui_Example, self).__init__(parent) width = 350 height = 180 self.resize(width,height) self.setMaximumSize(width,height) self.setMinimumSize(width,height) self.setWindowTitle("Example") self.path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'images') #icons path ### icons usericon = QtGui.QIcon() usericon.addPixmap(QtGui.QPixmap(os.path.join(self.path, '2.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off) camicon = QtGui.QIcon() camicon.addPixmap(QtGui.QPixmap(os.path.join(self.path, '1.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Button user self.btnuser = QtWidgets.QPushButton(self) self.btnuser.setGeometry(QtCore.QRect(20,20,150,100)) self.btnuser.setIcon(usericon) self.btnuser.setStyleSheet("background-color:transparent;") self.btnuser.clicked.connect(self.ExecUserCode) # Button cam self.btncam = QtWidgets.QPushButton(self) self.btncam.setGeometry(QtCore.QRect(180, 20, 150, 100)) self.btncam.setIcon(camicon) self.btncam.setStyleSheet("background-color:transparent;") self.btncam.clicked.connect(self.ExecCamCode) # Button.. # ... def ExecUserCode(self): print("User Code here") def ExecCamCode(self): print("Cam Code here") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MW = Ui_Example() MW.show() sys.exit(app.exec_()) The result is:
has comment: http://stackoverflow.com/comment/89107677
score: 0
has comment: http://stackoverflow.com/comment/89108324
type: Answer

http://stackoverflow.com/q/51161025
has body: I've tried to install python adb. With pip and legacy install I get the same error. Writing C:\Users\ARAJO~1\AppData\Local\Temp\easy_install-q9rc0j_2\M2Crypto- 0.26.4\setup.cfg Running M2Crypto-0.26.4\setup.py -q bdist_egg --dist-dir C:\Users\ARAJO~1\AppData\Local\Temp\easy_install-q9rc0j_2\M2Crypto-0.26.4\egg-dist-tmp-tf0svopa _m2crypto_wrap.c SWIG/_m2crypto_wrap.c(3550): warning C4068: unknown pragma SWIG/_m2crypto_wrap.c(3551): warning C4068: unknown pragma SWIG/_m2crypto_wrap.c(3554): fatal error C1083: Cannot open include file: 'openssl/err.h': No such file or directory error: Setup script exited with error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 EDIT: After cryptography install and config: I got this errors, what can be the origin of this? C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\stdio.h(2448): note: see declaration of 'fdopen' SWIG/_m2crypto_wrap.c(7653): error C2332: 'struct': missing tag name SWIG/_m2crypto_wrap.c(7653): error C2143: syntax error: missing ')' before '*' SWIG/_m2crypto_wrap.c(7653): error C2143: syntax error: missing '{' before '*' SWIG/_m2crypto_wrap.c(7653): error C2059: syntax error: ')' SWIG/_m2crypto_wrap.c(7654): error C2054: expected '(' to follow 'tzp' SWIG/_m2crypto_wrap.c(7681): warning C4013: 'gettimeofday' undefined; assuming extern returning int SWIG/_m2crypto_wrap.c(9489): error C2037: left of 'num' specifies undefined struct/union 'stack_st' SWIG/_m2crypto_wrap.c(9509): error C2037: left of 'num' specifies undefined struct/union 'stack_st' SWIG/_m2crypto_wrap.c(9538): error C2037: left of 'data' specifies undefined struct/union 'stack_st' SWIG/_m2crypto_wrap.c(9558): error C2037: left of 'data' specifies undefined struct/union 'stack_st' SWIG/_m2crypto_wrap.c(9587): error C2037: left of 'sorted' specifies undefined struct/union 'stack_st' SWIG/_m2crypto_wrap.c(9607): error C2037: left of 'sorted' specifies undefined struct/union 'stack_…
favorite count: 0
has answer: http://stackoverflow.com/a/51162588
upvote count: 2
type: UnansweredQuestion
tagged with: pip
downvote count: 1
type: Question
has title: Can't install python adb - M2Crypto Error
score: 1
answer count: 1
tagged with: python
tagged with: cmd

http://stackoverflow.com/a/51134468
has body: Another approach: (My dataframe name is test) Step 1: add a constant: test['constant'] =1 pd.pivot_table(test, index=['uid', 'date'], columns='interaction', values='constant', aggfunc='sum').fillna(0) interaction comment like uid date 1 2016-12-04 0.0 1.0 2016-12-05 1.0 2.0 2 2016-12-04 0.0 1.0 2016-12-05 1.0 2.0
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51134179

http://stackoverflow.com/a/51111436
answers question: http://stackoverflow.com/q/51111104
type: Answer
has body: Determine what is "polygon center" as central point C of expanding. Perhaps it is centroid (or some point with another properties?). Make a segment from your point P to C. Find intersection point I between PC and polygon edges. If polygon is concave and there are some intersection points, choose the closest one to P. Calculate coefficient of expanding: E = Length(PC) / Length(CI) Calculate new vertex coordinates. For i-th vertex of polygon: V'[i].X = C.X + (V[i].X - C.X) * E V'[i].Y = C.Y + (V[i].Y - C.Y) * E
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51034737
has comment: http://stackoverflow.com/comment/89061709
tagged with: python
has comment: http://stackoverflow.com/comment/89062030
linked to: http://stackoverflow.com/q/11011756
has comment: http://stackoverflow.com/comment/89061719
score: 2
has answer: http://stackoverflow.com/a/51035084
type: Question
has answer: http://stackoverflow.com/a/51035262
has comment: http://stackoverflow.com/comment/89061563
has comment: http://stackoverflow.com/comment/89061718
answer count: 2
has title: How to combine a dictionary formatted excel file with dictionary in Python
has body: If I have an excel file that has no row/column labels that looks like this: and I have a dictionary that looks like this: dict = {a:1, b:2, c:3} How can I combine them into a dictionary that combines the values and that looks like this: dict_result = {a:2, b:3, c:4}
has comment: http://stackoverflow.com/comment/89061827
downvote count: 0
has comment: http://stackoverflow.com/comment/89061575
favorite count: 0
upvote count: 2
type: UnansweredQuestion

executable
tags question: http://stackoverflow.com/q/51132467
tag name: executable
tags question: http://stackoverflow.com/q/51066637
type: Tag
tags question: http://stackoverflow.com/q/51064409

http://stackoverflow.com/a/51145514
has comment: http://stackoverflow.com/comment/89275442
upvote count: 2
has body: The CPython code for str.count is in PyUnicode_Count. In modern versions of Python, this dispatches to one of asciilib_count, ucs1lib_count, ucs2lib_count, or ucs4lib_count depending on how the haystrack string is stored, but ultimately they all come down to the generic STRINGLIB(count) code, which just calls FASTSEARCH. If you look at the top of that last source file: /* fast search/count implementation, based on a mix between boyer- moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbot.org/zone/stringlib.htm */ For single-character needles, it's basically just doing a strchr. For non-tiny needles, it does, as implied, build a Boyer-Moore delta table, which involves a bloom filter and some other stuff that's linearly proportional to the size of the needle, plus some other stuff that's constant. But there's nothing proportional to the size of the haystack. So, whether you call that constant or linear depends on whether you consider the size of the needle an input or a constant.
has comment: http://stackoverflow.com/comment/89275440
type: Answer
has comment: http://stackoverflow.com/comment/89275487
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89275769
answers question: http://stackoverflow.com/q/51145376

http://stackoverflow.com/a/51125521
has body: This is because your testprocess.communicate() for the wc -l command already consumes all of the output of userdataprocess.stdout and closes it in fact, so there's nothing left for dnslineprocess.communicate() to read. You should instead read the output of userdataprocess.stdout into a variable and then use it as an input to both testprocess.communicate() and dnslineprocess.communicate(). Also, as @pyb pointed out, you are unnecessarily quoting DNS= in your grep command, which, without a shell, will be passed to grep with double quotes included as part of the string to filter with. You should simply remove them as there are no special characters in your filter string. import subprocess user = "testuser" getuserdata = 'cat /var/cpanel/users/' + user getdnsline = 'grep DNS=' test = 'wc -l' userdataprocess = subprocess.Popen(getuserdata.split(), stdout=subprocess.PIPE) userdata = userdataprocess.stdout.read() testprocess = subprocess.Popen(test.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) test, error = testprocess.communicate(userdata) print(test) dnslineprocess = subprocess.Popen(getdnsline.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) website, error = dnslineprocess.communicate(userdata) print(website.decode('utf-8').splitlines())
has comment: http://stackoverflow.com/comment/89236117
has comment: http://stackoverflow.com/comment/89236030
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51125388
score: 1
upvote count: 1

http://stackoverflow.com/a/51112901
has body: Function random.randint generates a random number inside the range defined by low and high values, both included: low &lt;= x &lt;= high. Since you set high to len(fruits), and the last list index is actually len(fruits) - 1, you can get a list index out of range error in case random.randint produces the high value. Instead, modify the code by changing the definition of high. import random fruits = ['Apple','Mango','Banana','Grapes','Guava'] random.seed(500) low = 0 high = len(fruits) - 1 random_fruits = [fruits[random.randint(low,high)] for i in range(1000)]
upvote count: 2
answers question: http://stackoverflow.com/q/51112867
has comment: http://stackoverflow.com/comment/89215876
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89216139

http://stackoverflow.com/comment/108389542
type: Comment
comment on: http://stackoverflow.com/a/60189988
score: 5
has text: actually the virtualenv is not necessary. `pyenv` lets you manage python versions without the need of using a venv
type: AnswerComment

http://stackoverflow.com/q/51015897
tagged with: pip
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89044855
has comment: http://stackoverflow.com/comment/89044353
has comment: http://stackoverflow.com/comment/89044440
has comment: http://stackoverflow.com/comment/89025377
has title: Setting Path of TensorFlow
has comment: http://stackoverflow.com/comment/89044825
has comment: http://stackoverflow.com/comment/89044617
type: Question
has body: MacOS High Sierra 10.13.2 Early 2016 Rose Gold MacBook I have done a LOT to get TensorFlow installed (REALLY should have just used pip3 from the start...) and now need to set the path of it so I can import it. Currently, I know it is installed; pip3 show tensorflow gets Name: tensorflow Version: 1.8.0 Summary: TensorFlow helps the tensors flow Home-page: https://www.tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com License: Apache 2.0 Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requires: numpy, absl-py, gast, termcolor, astor, protobuf, grpcio, wheel, six, tensorboard This is great, but importing tensorflow still doesn't work. I figured out that I need to set the path from some googling and found this command: PYTHONPATH=/your/tensorflow/path:$PYTHONPATH. However, what am I supposed to do with it? Should I replace 'PYTHONPATH' with something? How do I tell it that that points to tensorflow? Should it be like this: PYTHONPATH=/Users/rose/tensorflow/path:$tensorflow
has comment: http://stackoverflow.com/comment/89044867
has comment: http://stackoverflow.com/comment/89044089
downvote count: 0
has comment: http://stackoverflow.com/comment/89044282
has comment: http://stackoverflow.com/comment/89044773
favorite count: 0
has comment: http://stackoverflow.com/comment/89044482
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89044987
answer count: 0
has comment: http://stackoverflow.com/comment/89045176
has comment: http://stackoverflow.com/comment/89044317
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/89061582
score: 0
comment on: http://stackoverflow.com/a/51029925
type: Comment
has text: I have tried your solution. But still, it is showing the same error.
type: AnswerComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/51148947
tags question: http://stackoverflow.com/q/51014757
tags question: http://stackoverflow.com/q/51050791
tags question: http://stackoverflow.com/q/51061219
tags question: http://stackoverflow.com/q/51110593
tags question: http://stackoverflow.com/q/51040835
tags question: http://stackoverflow.com/q/51102307
tags question: http://stackoverflow.com/q/51107657
tags question: http://stackoverflow.com/q/51015108
tags question: http://stackoverflow.com/q/51028096
tags question: http://stackoverflow.com/q/51113799
tags question: http://stackoverflow.com/q/51085303
tags question: http://stackoverflow.com/q/51054489
tags question: http://stackoverflow.com/q/51052244
tags question: http://stackoverflow.com/q/51076355
tags question: http://stackoverflow.com/q/51054397
tags question: http://stackoverflow.com/q/51122141
tags question: http://stackoverflow.com/q/51092139
type: Tag
tags question: http://stackoverflow.com/q/51135849
tags question: http://stackoverflow.com/q/51076418
tags question: http://stackoverflow.com/q/51051610
tags question: http://stackoverflow.com/q/51145637
tags question: http://stackoverflow.com/q/51041562
tags question: http://stackoverflow.com/q/51139256
tags question: http://stackoverflow.com/q/51156994
tags question: http://stackoverflow.com/q/51030164
tags question: http://stackoverflow.com/q/51030122
tags question: http://stackoverflow.com/q/51150819
tags question: http://stackoverflow.com/q/51148583
tags question: http://stackoverflow.com/q/51066880
tags question: http://stackoverflow.com/q/51027339
tags question: http://stackoverflow.com/q/51120802
tags question: http://stackoverflow.com/q/51071343
tags question: http://stackoverflow.com/q/51055694
tags question: http://stackoverflow.com/q/51064844
tags question: http://stackoverflow.com/q/51119896
tags question: http://stackoverflow.com/q/51129628
tags question: http://stackoverflow.com/q/51071206
tags question: http://stackoverflow.com/q/51062507
tags question: http://stackoverflow.com/q/51049546
tags question: http://stackoverflow.com/q/51106207
tags question: http://stackoverflow.com/q/51034706
tags question: http://stackoverflow.com/q/51158769
tags question: http://stackoverflow.com/q/51109345
tags question: http://stackoverflow.com/q/51160247
tags question: http://stackoverflow.com/q/51087942
tags question: http://stackoverflow.com/q/51159277
tags question: http://stackoverflow.com/q/51012787
tags question: http://stackoverflow.com/q/51107632
tags question: http://stackoverflow.com/q/51100005
tags question: http://stackoverflow.com/q/51092076
tags question: http://stackoverflow.com/q/51054294
tags question: http://stackoverflow.com/q/51048725
tag name: html
tags question: http://stackoverflow.com/q/51099710
tags question: http://stackoverflow.com/q/51053492
tags question: http://stackoverflow.com/q/51126621
tags question: http://stackoverflow.com/q/51091451
tags question: http://stackoverflow.com/q/51090505
tags question: http://stackoverflow.com/q/51127307
tags question: http://stackoverflow.com/q/51052422
tags question: http://stackoverflow.com/q/51165060
tags question: http://stackoverflow.com/q/51035611
tags question: http://stackoverflow.com/q/51106916

http://stackoverflow.com/q/51128203
has comment: http://stackoverflow.com/comment/89242288
has comment: http://stackoverflow.com/comment/89241597
has comment: http://stackoverflow.com/comment/89243360
downvote count: 3
has answer: http://stackoverflow.com/a/51128736
type: Question
has title: dot product of two vectors python3
upvote count: 0
has comment: http://stackoverflow.com/comment/89242110
has comment: http://stackoverflow.com/comment/89241578
has body: I'm having trouble computing the dot product of two vectors in my code for the QR(matrix) portion. I'm trying to dot the result of q[i] with vector01 I don't know where my code is incorrect. Any help would be great thank you. My expected output should be sqrt(2) def twoNorm(vector): ''' twoNorm takes a vector as it's argument. It then computes the sum of the squares of each element of the vector. It then returns the square root of this sum. ''' # This variable will keep track of the validity of our input. inputStatus = True # This for loop will check each element of the vector to see if it's a number. for i in range(len(vector)): if ((type(vector[i]) != int) and (type(vector[i]) != float) and (type(vector[i]) != complex)): inputStatus = False print("Invalid Input") # If the input is valid the function continues to compute the 2-norm if inputStatus == True: result = 0 # This for loop will compute the sum of the squares of the elements of the vector. for i in range(len(vector)): result = result + (vector[i]**2) result = result**(1/2) return result vector = [1, 0, 1] print(twoNorm(vector)) def QR(matrix): if len(matrix) != len(vector): print('Invalid') else: qi = [] for i in vector: qi.append(i/scalar) return qi if len(qi) != len(vector01): print('invalid input') else: total = 0 for j in range(len(qi)): total += qi[j] * vector01[j] return total vector01 = [2, 1, 0] scalar = twoNorm(vector) vector = [1, 0, 1] matrix = [[1, 2], [0, 1], [1, 0]] print(QR(matrix))
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/q/51078742
has answer: http://stackoverflow.com/a/51087603
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: numpy
downvote count: 0
has body: I have a dataset with an ID column for each sample as in this example: id score1 score2 score3 1 0.41 0.37 0.04 2 0.19 0.33 0.277 3 0.21 0.33 0.037 4 0.49 0.23 0.378 5 0.51 0.78 0.041 To fit and predict a ML classifier on this data, I have to remove the ID column from the data X = np.array(df.drop(['id'], 1)) X_train, X_test = model_selection.train_test_split(X, test_size=0.2)` clf.fit(X_train) pred = clf.predict(X_test) I am wondering how can I recover the ID in prediction results, so I can identify each sample if it was correctly classified or not ? because I already know the correct label of samples. Or, if there is a way to keep the ID (could be numeric or non-numeric) in the training ? I found this related question, but I can't understand what to do because they are talking about other things like Census Estimator, etc. and I'm running a very simple Python script with numpy and scikit-learn libraries.
accepted answer: http://stackoverflow.com/a/51087603
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/44381879
has title: Recovering instances' IDs after training and prediction

http://stackoverflow.com/comment/89171049
score: 2
comment on: http://stackoverflow.com/a/51091396
type: AnswerComment
type: Comment
has text: While this is a great example of some fancy python features, for a beginner I think this is a much less readable solution than a simple counter.

http://stackoverflow.com/q/51050329
downvote count: 1
type: Question
tagged with: odoo
tagged with: odoo-8
tagged with: odoo-9
score: -1
upvote count: 0
answer count: 1
has body: class SaleOrderLine(self) inherit = 'sale.order.line' def check_lowest_qty(self): for line in self: #print line product_uom_qty with least or biggest negative quantity Updated question with better grammar. I want to compare the quantity of each line and to print line which has the least quantity or biggest negative quantity. For example. If there are 2 lines and first lines quantity is 5 and second lines quantity is -2 I want to print line with -2.
has comment: http://stackoverflow.com/comment/89155683
has title: Count line qty and check witch has less qty
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51061868
accepted answer: http://stackoverflow.com/a/51061868
type: AnsweredQuestion

http://stackoverflow.com/a/51165838
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51165779
has body: We get list of keys or users from ip (list 2) and iterate on another list to check if the key is present in list 2 already, if not present add to the list. ip = [('user1', '1.1.1.1'), ('user2', '1.1.1.2'), ('user4', '1.1.1.4')] dyndns = [('user1', 'dyndns1'), ('user2', 'dyddns2'), ('user3', 'dyndns3'), ('user4', 'dyddns4')] ip_keys = list(map (lambda x:x[0], ip)) for i in dyndns: if (not i[0] in ip_keys): ip.append(i)

http://stackoverflow.com/q/51142996
score: 1
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/89365175
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52270692
has comment: http://stackoverflow.com/comment/89279361
has body: I have pip installed both Flask-SQLAlchemy and SQLAlchemy itself, and have checked that they are both up to date. However, when I try to run my python code: from flask import Flask, request, render_template from flask_sqlalchemy import SQLAlchemy # from tables import Score, ScoreTable import sqlite3 as sql app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' I continue to receive this error: [pylint] E0401:Unable to import 'flask_sqlalchemy' Can anyone help with this? Maybe I am missing something simple.
has answer: http://stackoverflow.com/a/66757095
tagged with: python
has comment: http://stackoverflow.com/comment/89271267
has comment: http://stackoverflow.com/comment/108982424
has answer: http://stackoverflow.com/a/66732400
has title: E0401: "Unable to import 'flask_sqlalchemy'"
upvote count: 2
has answer: http://stackoverflow.com/a/61465906
downvote count: 1
has answer: http://stackoverflow.com/a/58681571
has answer: http://stackoverflow.com/a/66614950
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73735085
has answer: http://stackoverflow.com/a/51826263
has answer: http://stackoverflow.com/a/53387617
tagged with: sqlalchemy
answer count: 10
has answer: http://stackoverflow.com/a/61610522

http://stackoverflow.com/comment/89131653
type: Comment
has text: should `Calc_2` stay in ascending/sorted order even if the `list_2` would be `list_2 = [321, 654, 212]` ?
comment on: http://stackoverflow.com/q/51070781
score: 0
type: QuestionComment

http://stackoverflow.com/q/51067854
favorite count: 0
tagged with: python-3.x
has body: My dataframe is a single row with N columns: col1 col2 col3 col4 col5 col6 col7 col8 col9 0 NBA Mens Sports LAL Lakers BOS Celtics SAS Spurs Output that I'm looking for is a new dataframe as shown below, Here the first three column value is same for all the rows. However the col4 and col5 values in this new dataframe is replaced by the above DF column values col4,col5 and col6,col 7 and col8,col9 and so on for each row in new dataframe col1 col2 col3 col4 col5 0 NBA Mens Sports LAL Lakers 1 NBA Mens Sports BOS Celtics 2 NBA Mens Sports SAS Spurs My Code: Convert the single row to ndarray import pandas as pd df = pd.read_csv('df_info.txt', sep=",", header=0) vallist=df.as_matrix()[0] Create a Dict to store the values dict={} n=4 varlist1=[] for i in range(len(vallist)): if(n&lt;=9): dict[i]={} print(vallist[n],vallist[n+1]) dict[i]['col1']=vallist[0] dict[i]['col2']=vallist[1] dict[i]['col3']=vallist[2] dict[i]['col4']=vallist[n] dict[i]['col5']=vallist[n+1] n+=2 Import the dict to Dataframe df2=pd.DataFrame.from_dict(dict) df2.transpose() I'm getting the required result but I'm not convinced, looking for more pythonic and panda ways to achieve this.
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/51067965
accepted answer: http://stackoverflow.com/a/51067965
possible better answer: http://stackoverflow.com/a/51068009
answer count: 2
tagged with: pandas
has title: Create multirow dataframe from Single row dataframe
has comment: http://stackoverflow.com/comment/89125949
has answer: http://stackoverflow.com/a/51068009

http://stackoverflow.com/comment/89303845
type: Comment
has text: @Abrar Don't use this code directly; this is just for illustration.
type: AnswerComment
comment on: http://stackoverflow.com/a/51160178
score: 0

beautifulsoup
tags question: http://stackoverflow.com/q/51162422
tags question: http://stackoverflow.com/q/51017610
tags question: http://stackoverflow.com/q/51055644
tags question: http://stackoverflow.com/q/51072792
tags question: http://stackoverflow.com/q/51083689
tags question: http://stackoverflow.com/q/51100224
tags question: http://stackoverflow.com/q/51116797
tags question: http://stackoverflow.com/q/51126902
tags question: http://stackoverflow.com/q/51147457
tags question: http://stackoverflow.com/q/51019212
tags question: http://stackoverflow.com/q/51015047
tags question: http://stackoverflow.com/q/51048581
tags question: http://stackoverflow.com/q/51129410
tags question: http://stackoverflow.com/q/51069581
tags question: http://stackoverflow.com/q/51146452
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51014545
tags question: http://stackoverflow.com/q/51050202
tags question: http://stackoverflow.com/q/51069677
tags question: http://stackoverflow.com/q/51044486
tags question: http://stackoverflow.com/q/51060212
tags question: http://stackoverflow.com/q/51143201
tags question: http://stackoverflow.com/q/51040994
tags question: http://stackoverflow.com/q/51115590
tags question: http://stackoverflow.com/q/51087787
tags question: http://stackoverflow.com/q/51017998
tags question: http://stackoverflow.com/q/51145637
tags question: http://stackoverflow.com/q/51117692
tags question: http://stackoverflow.com/q/51116907
tags question: http://stackoverflow.com/q/51102307
tags question: http://stackoverflow.com/q/51139256
tags question: http://stackoverflow.com/q/51132582
tags question: http://stackoverflow.com/q/51112892
tags question: http://stackoverflow.com/q/51028077
tags question: http://stackoverflow.com/q/51111772
tags question: http://stackoverflow.com/q/51076355
tags question: http://stackoverflow.com/q/51152792
tags question: http://stackoverflow.com/q/51161740
tags question: http://stackoverflow.com/q/51120802
tags question: http://stackoverflow.com/q/51053551
tags question: http://stackoverflow.com/q/51058877
tags question: http://stackoverflow.com/q/51056542
tags question: http://stackoverflow.com/q/51106917
tags question: http://stackoverflow.com/q/51069366
type: Tag
tags question: http://stackoverflow.com/q/51116380
tags question: http://stackoverflow.com/q/51136244
tags question: http://stackoverflow.com/q/51112842
tags question: http://stackoverflow.com/q/51038633
tags question: http://stackoverflow.com/q/51143295
tags question: http://stackoverflow.com/q/51053474
tags question: http://stackoverflow.com/q/51041245
tags question: http://stackoverflow.com/q/51099959
tags question: http://stackoverflow.com/q/51166539
tags question: http://stackoverflow.com/q/51107486
tags question: http://stackoverflow.com/q/51094378
tags question: http://stackoverflow.com/q/51112644
tags question: http://stackoverflow.com/q/51044222
tags question: http://stackoverflow.com/q/51127873
tags question: http://stackoverflow.com/q/51150819
tags question: http://stackoverflow.com/q/51106832
tags question: http://stackoverflow.com/q/51159585
tags question: http://stackoverflow.com/q/51012787
tags question: http://stackoverflow.com/q/51083617
tags question: http://stackoverflow.com/q/51163995
tags question: http://stackoverflow.com/q/51155568
tags question: http://stackoverflow.com/q/51147540
tags question: http://stackoverflow.com/q/51138836
tags question: http://stackoverflow.com/q/51056176
tags question: http://stackoverflow.com/q/51104320
tags question: http://stackoverflow.com/q/51043406
tags question: http://stackoverflow.com/q/51069426
tags question: http://stackoverflow.com/q/51014804
tags question: http://stackoverflow.com/q/51053492
tags question: http://stackoverflow.com/q/51126621
tags question: http://stackoverflow.com/q/51041004
tags question: http://stackoverflow.com/q/51152430
tags question: http://stackoverflow.com/q/51141430
tags question: http://stackoverflow.com/q/51031318
tags question: http://stackoverflow.com/q/51051351

http://stackoverflow.com/comment/89088444
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51048266
score: 4
has text: Since the new error message is unrelated to PIL, it may be worthwhile to make a brand new question for it.

http://stackoverflow.com/comment/89889615
type: Comment
type: QuestionComment
has text: Yea I guess you could try filing a bug report. Just curious are both running the gpu version of tensorflow?
score: 0
comment on: http://stackoverflow.com/q/51123088

http://stackoverflow.com/a/51108543
has comment: http://stackoverflow.com/comment/89204298
type: Answer
has body: These are general things you might or might not have thought about: Pyinstaller need to have the same type of system to deploy to as the system you are building on. If you are building on a 64 bit platform then you can deploy to a 64 bit platform. A 32 bit platform build will deploy to 32 bit platforms. So you have path statements that are to the libraries on your computer but those don't exist then you have to bring them with you in the spec file. I would suggest doing a one directory install rather than a file install for the first attempt, it's slightly easier.
answers question: http://stackoverflow.com/q/51108155
has comment: http://stackoverflow.com/comment/89204441
score: 0

http://stackoverflow.com/a/51106799
type: Answer
has body: Check out Sympy and it's use of solve and matrix calculations. Here are the pages for both. http://docs.sympy.org/latest/tutorial/matrices.html http://docs.sympy.org/latest/tutorial/solvers.html
answers question: http://stackoverflow.com/q/51106747
score: 0

http://stackoverflow.com/a/51108463
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51108400
has body: Verify beforehand if there is a value inside the pw key, or any key of the dictionary for that matter and then call the command with the proper options. You could do it in lots of ways, one for instance is: if len(args['pw']) &gt; 0: # do stuff I leave it to the author decide how to do it best.

http://stackoverflow.com/q/51116241
tagged with: amazon-ec2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90107222
tagged with: python
tagged with: pycharm
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51342682
has body: I have a python docker container up and running on EC2-instance. How can I use this python as interpreter in my local IDE (PyCharm)?
has title: Accessing docker container in AWS from localhost
tagged with: docker
score: 0

pipeline
type: Tag
tags question: http://stackoverflow.com/q/51118565
tags question: http://stackoverflow.com/q/51087141
tags question: http://stackoverflow.com/q/51163974
tags question: http://stackoverflow.com/q/51062223
tag name: pipeline
tags question: http://stackoverflow.com/q/51083843

http://stackoverflow.com/a/51125701
has comment: http://stackoverflow.com/comment/91248566
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91250476
type: Answer
accepted answer of: http://stackoverflow.com/q/51111556
answers question: http://stackoverflow.com/q/51111556
has comment: http://stackoverflow.com/comment/91250464
has body: The eggs/source code at PyPI seems to be buggy. The code at Github repository seems to be better but lacks setup.py. A broken and abandoned package. You can try to clone https://github.com/Sterncat/opticspy and put it into site-packages/ directory manually. If you apply PR 21 yourself you get missed setup.py so you can run pip install . or python setup.py install.
has comment: http://stackoverflow.com/comment/89432960
has comment: http://stackoverflow.com/comment/89432223
score: 0

http://stackoverflow.com/q/51151521
has answer: http://stackoverflow.com/a/51153905
tagged with: list
score: 1
type: Question
downvote count: 0
tagged with: list-comprehension
answer count: 1
favorite count: 0
has title: Can you use AND in List comprehension conditional statements?
tagged with: python-3.x
has body: I am trying to use List Comprehension to perform the following. I want to make a new list (unique) that only has the common numbers from both lists. unique = [] for listcomp in range(len(list1)): if list1[listcomp] in list2 and list1[listcomp] not in unique: unique.append(list1[listcomp]) else: continue Above works fine but when I create the List comprehension below I get duplicates if list1 has duplicate numbers. i.e. list1 = [1, 1, 2], list2 = [1, 5]. I created my list comprehension as unique = [list1[listcomp] for listcomp in range(len(list1)) if list1[listcomp] in list2 and list1[listcomp] not in unique] If I'm getting duplicates I assume the "and" statement isn't being applied? I have read other queries about moving the if statement further up the comprehension statement but this didn't work. Can you use AND to extend your conditions? Many thanks My full code is:- import random as rnd # Randomly generate the size of your list list1size = rnd.randint(1,20) list2size = rnd.randint(1,20) # Declare your list variables list1 = [] list2 = [] # Fill your lists with randomly generated numbers upto the listsize generated above for x in range(list1size): list1.append(rnd.randint(1,15)) for y in range(list2size): list2.append(rnd.randint(1,15)) # Not required but easier to read lists once sorted list1.sort() list2.sort() print(list1) print(list2) # Now to compare old school unique = [] # for listcomp in range(len(list1)): # if list1[listcomp] in list2 and list1[listcomp] not in unique: # unique.append(list1[listcomp]) # else: # continue # Now to compare with list comprehension unique = [list1[listcomp] for listcomp in range(len(list1)) if list1[listcomp] in list2 and list1[listcomp] not in unique] # Above doesn't stop duplicates if they are in List1 so I assume you can't use AND print(f"The common numbers in both lists are {unique}")
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89061030
comment on: http://stackoverflow.com/a/51034466
has text: @Punter345 Okay, I think I get it. Try it now.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89209312
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51111104
has text: If I understand your description (not your code) correctly, you're growing a polygon by moving the polygon vertices away from the center of the polygon. According to your title, you want to do that _until_ one (or more) border(s) hit a specific point, but your text description then says you multiply all points by a factor. Can you explain why you think that implementation would do what your title suggests you want it to do?

http://stackoverflow.com/a/51117045
score: 1
has body: this has desired property: def foo(n, bar = []): if n == 0: bar[:] = [] print("list empty") else: bar.append(n) for y in bar: print(y, end=', ') print()
has comment: http://stackoverflow.com/comment/89220256
answers question: http://stackoverflow.com/q/51116967
type: Answer
upvote count: 2
downvote count: 1

http://stackoverflow.com/q/51155345
tagged with: communication
has body: I'm trying to run a command that emits Unicode output, and print that output to the shell. My code is similar to the following (CP850 because that's the codepage used by my Windows terminal, as returned by chcp): command = 'echo Тестирование всегда необходимо!' p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) out, err = p.communicate() out = out.decode('CP850') err = err.decode('CP850') print(out) I get: ?????????? ?????? ??????????! How can I cause the correct text to be passed through?
tagged with: shell
score: 1
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/75833969
answer count: 2
has answer: http://stackoverflow.com/a/51160183
tagged with: python
has comment: http://stackoverflow.com/comment/89303801
downvote count: 1
has title: Printing Unicode output from a subprocess to the terminal on Windows
linked to: http://stackoverflow.com/q/23827412
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89295822
has comment: http://stackoverflow.com/comment/89294242

http://stackoverflow.com/a/51119543
type: Answer
has body: Not aware of a non-loopy method, but you could probably speed this up a bit with roll and column_stack. v = np.array([1, 2, 3, 4, 5]) t = np.pad(v[::-1], (0, 4), mode='constant') np.column_stack([np.roll(t, i) for i in range(len(v))]) array([[5, 0, 0, 0, 0], [4, 5, 0, 0, 0], [3, 4, 5, 0, 0], [2, 3, 4, 5, 0], [1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [0, 0, 1, 2, 3], [0, 0, 0, 1, 2], [0, 0, 0, 0, 1]])
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51119459
upvote count: 1

http://stackoverflow.com/a/51125163
type: AcceptedAnswer
has body: pass does nothing by definition. That's what it's for: as a no-op, a placeholder for when the syntax requires a statement but you don't want to do anything. I suspect what you want here is continue, which will loop.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51125119
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51125119

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/51165579
type: Tag

http://stackoverflow.com/a/51144238
type: Answer
score: 2
downvote count: 0
has body: One way to do this is using numpy.where, which lets us select between two arrays depending on a condition. We first build a mask array that is True where both A1 &amp; A2 are non-zero, and False otherwise. I'll call your selected value val. Your condition of using val wherever the A1 value is greater than val can be done by taking the minimum of A1 and val. Here's the procedure, step by step, so we can see what's going on. import numpy as np A1 = np.array([[5, 3], [4, 6]]) A2 = np.array([[7, 9], [5, 0]]) print(A1, '\n') print(A2, '\n') # Selected indices of A1 row, col = 1, 0 val = A1[row, col] print(val) # Find where both A1 &amp; A2 are nonzero mask = (A1 != 0) &amp; (A2 != 0) print(mask, '\n') # Replace values in A1 that are greater than val A1a = np.minimum(A1, val) print(A1a, '\n') # Only do the subtraction where both A1 &amp; A2 are nonzero, # otherwise copy the A2 value A3 = np.where(mask, A2 - A1a, A2) print(A3, '\n') output [[5 3] [4 6]] [[7 9] [5 0]] 4 [[ True True] [ True False]] [[4 3] [4 4]] [[3 6] [1 0]] And in one line: A3 = np.where((A1 != 0) &amp; (A2 != 0), A2 - np.minimum(A1, val), A2) A closely related version is: A3 = A2 - np.where((A1 != 0) &amp; (A2 != 0), np.minimum(A1, val), 0) Here's yet another version, courtesy of Andras Deak, which is similar to np.where, but should be faster when mask has a large number of False entries: A3 = A2.copy() A3[mask] -= np.minimum(A1, val)[mask]
accepted answer of: http://stackoverflow.com/q/51143682
upvote count: 2
answers question: http://stackoverflow.com/q/51143682
type: AcceptedAnswer

http://stackoverflow.com/q/51135150
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/11707586
tagged with: python
has answer: http://stackoverflow.com/a/51135210
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51135210
has body: I imported my file using pandas and now I want a description of the data-set. I used describe() function but It is showing 4 features first two and last two what should I do for seeing complete description. here is a part of my code- import pandas as pd header_names = ['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal','num'] dataset = pd.read_csv('E:/HCU proj doc/EHR dataset/cleveland_data.csv', names= header_names) print(dataset.describe()) output- [Command: python -u 'E:\HCU proj doc\heart_disease_data.py'] age sex ... slope num count 303.000000 303.000000 ... 303.000000 303.000000 mean 54.438944 0.679868 ... 1.600660 0.937294 std 9.038662 0.467299 ... 0.616226 1.228536 min 29.000000 0.000000 ... 1.000000 0.000000 25% 48.000000 0.000000 ... 1.000000 0.000000 50% 56.000000 1.000000 ... 2.000000 0.000000 75% 61.000000 1.000000 ... 2.000000 2.000000 max 77.000000 1.000000 ... 3.000000 4.000000 [8 rows x 12 columns] [Finished in 5.809s]
type: Question
has comment: http://stackoverflow.com/comment/89254349
has title: why cant I see complete output of describe function in atom editor?
score: 0
has comment: http://stackoverflow.com/comment/89254526

http://stackoverflow.com/comment/89174557
type: QuestionComment
comment on: http://stackoverflow.com/q/51092894
score: 0
type: Comment
has text: Because `symbols` is just one long string... you actually need to parse this into separate arguments. I looked at the docs and my previous assumption was wrong - you need a sequence with all of the args, which you had in the first place but you currently have a list of `1` string. And you need a list with `12` items.

http://stackoverflow.com/q/51115651
tagged with: python
has comment: http://stackoverflow.com/comment/89217901
tagged with: uwsgi
type: Question
tagged with: nginx
score: 0
has title: nginx cant't serve files correctly when deploy a django project with nginx and uwsgi on ubuntu 16.04
has answer: http://stackoverflow.com/a/51115754
answer count: 3
has answer: http://stackoverflow.com/a/51119963
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51117708
has body: When I deploy a django project follow this tutorial:[http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html?highlight=django when I done the step Basic nginx test, after i type taopinpin.cn/media/media.png, the page response denied like this: enter image description here and my project like this: enter image description here mysite_nginx.conf file is : upstream django { server 127.0.0.1:8001; } server { listen 8000; server_name taopinpin.cn; charset utf-8; client_max_body_size 75M; location /media { alias /root/mysite/media; } location /static { alias /root/mysite/static; } location / { uwsgi_pass django; inlcude /root/mysite/mysite/uwsgi_params; } } I don't know where get an error, can you help me debug it ? Thank you a lot.
tagged with: django

gremlin-server
tags question: http://stackoverflow.com/q/51135611
type: Tag
tag name: gremlin-server

http://stackoverflow.com/q/51143602
has answer: http://stackoverflow.com/a/51143661
tagged with: python
has comment: http://stackoverflow.com/comment/89271757
favorite count: 0
accepted answer: http://stackoverflow.com/a/51143661
possible better answer: http://stackoverflow.com/a/51143677
has answer: http://stackoverflow.com/a/51143677
has comment: http://stackoverflow.com/comment/89271871
has title: Struggling with Class Inheritance & super().__init__
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89271654
type: Question
answer count: 2
downvote count: 0
tagged with: inheritance
has body: Very new to Python, trying to create a game in which any number of armies can be created, but each army will pre-render the names of the soldiers. I think I need to be using super init to really cut down on duplicate code, but I cannot for the life of me figure out how to make it work. From what I understand my class Army should be the Parent class, with RedArmy and Scout as subclasses. I'm just struggling to understand where the super().__init__() should come in? class Army: def __init__(self): self.color = None self.scoutname = None self.demomanname = None self.medicname = None def train_scout(self, weapon): return Scout(self.color, self.scoutname, weapon) class RedArmy(Army): def __init__(self): self.color = "Red" self.scoutname = "Yankee" self.demomanname = "Irish" self.medicname = "Dutch" class BlueArmy(Army): pass class Scout: specialization = "fast captures" def __init__(self, color, scoutname, weapon): self.color = color self.scoutname = scoutname self.weapon = weapon def introduce(self): return (f'Hi I\'m {self.scoutname}, I do {self.specialization} and I wield a {self.weapon}') my_army = RedArmy() soldier_1 = my_army.train_scout("baseball bat") print(soldier_1.introduce())

http://stackoverflow.com/q/51069263
linked to: http://stackoverflow.com/q/1720421
type: Question
has body: lst1 = [ {'mem': '20.0', 'name': 'p1', 'cpu': '20.0'}, {'mem': '20.0', 'name': 'p2', 'cpu': '20.0'}, {'mem': '20.0', 'name': 'p3', 'cpu': '20.0'}, {'mem': '20.0', 'name': 'p4', 'cpu': '20.0'} ] lst2 = [ {'pid': 814, 'name': 'p1'}, {'pid': 999, 'name': 'p2'}, {'pid': 1006, 'name': 'p3'}, {'pid': 1152, 'name': 'p4'} ] I need to merge above two list into single list i.e. lst3 = [ {'mem': '20.0', 'name': 'p1', 'cpu': '20.0', 'pid':814}, {'mem': '20.0', 'name': 'p2', 'cpu': '20.0','pid':999}, {'pid': 1006, 'mem': '20.0', 'name': 'p3', 'cpu': '20.0'}, {'pid': 1152,'mem': '20.0', 'name': 'p4', 'cpu': '20.0'} ] I have tried doing it in below way lst3 = list() test = dict() for f,b in zip(lst1,lst2): test = f.copy() test.update(b) #print test lst3.append(test) print lst3 Please let me know is there any easy method or more pythonic way to do this
has answer: http://stackoverflow.com/a/74832954
has comment: http://stackoverflow.com/comment/89128708
answer count: 2
linked to: http://stackoverflow.com/q/5501810
has title: Merging two list of dictionary in python
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/89128452
tagged with: python
has comment: http://stackoverflow.com/comment/89128385
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51069339

http://stackoverflow.com/comment/89318347
type: AnswerComment
type: Comment
has text: The link you posted refers to builtins that are *always* available in Python, without any imports required. Adding functions that *do* require inputs would quickly muddle that list.
score: 0
comment on: http://stackoverflow.com/a/51167401

http://stackoverflow.com/comment/89057629
score: 0
type: QuestionComment
type: Comment
has text: @girlvsdata I am just going to write a formula over the keyword. Once I can figure out how to return the range of the keyword the rest is cake!
comment on: http://stackoverflow.com/q/51032411

http://stackoverflow.com/q/51166266
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/89315817
type: UnansweredQuestion
has title: What is the most Pythonic way to sort a dictionary with string number keys numerically?
score: -4
has answer: http://stackoverflow.com/a/51166304
has comment: http://stackoverflow.com/comment/89315693
has comment: http://stackoverflow.com/comment/89315682
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89315742
downvote count: 4
answer count: 1
tagged with: sorting
has body: Here is my format, dict: { "server" : { "2" : { name : "Chris", text : "Hello!" }, "1" : { name : "David", text : "Hey!" } } } How can I sort dict['server'] numerically, although the keys are strings? All ways that I can come up with require multiple names and don't feel very Pythonic at all.
tagged with: python
has comment: http://stackoverflow.com/comment/89315672
tagged with: dictionary

http://stackoverflow.com/comment/89020007
type: QuestionComment
has text: `X` is NumPy array, not a list. `X[:, 0]` simply slices the second axis. Try `X.shape` / `X.ndim` to check the shape of your array.
comment on: http://stackoverflow.com/q/51013667
score: 4
type: Comment

http://stackoverflow.com/comment/89133361
has text: Instead of `float(results.Solution.Objective.__default_objective__['value'])`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51064820
type: Comment

http://stackoverflow.com/comment/89296884
has text: There must be something else going on here if it takes multiple seconds to decode just a few thousand entries. Can you post a link to sample data so we may reproduce this ourselves? [mcve]
comment on: http://stackoverflow.com/a/51156376
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/51034552
has comment: http://stackoverflow.com/comment/89061404
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89071330
upvote count: 2
answers question: http://stackoverflow.com/q/51034291
accepted answer of: http://stackoverflow.com/q/51034291
has body: You can use df.unstack('continent') to place continent as columns, then this dataframe becomes a 2D table where the 1st column is the X, and other columns are Y. You can directly call plot function or control the plot yourself by raw matplotlib operations. Thanks for your data, here is the complete code sample for your request: # imports import pandas as pd import matplotlib.pyplot as plt # prepare dataframe df = pd.read_csv('gapminder.tsv', sep='\t') df = df.groupby(['year','continent']).lifeExp.mean() # unstack the `continent` index, to place it as columns df = df.unstack(level='continent') # The name of columns would become the name of legend # when using dataframe plot df.columns.name = 'Life Expectation' # Now, we have a 2d talbe, 1st column become to X # and other columns become to Y # In [14]: df.head() # Out[14]: # Life Expectation Africa Americas Asia Europe Oceania # year # 1952 39.135500 53.27984 46.314394 64.408500 69.255 # 1957 41.266346 55.96028 49.318544 66.703067 70.295 # 1962 43.319442 58.39876 51.563223 68.539233 71.085 # 1967 45.334538 60.41092 54.663640 69.737600 71.310 # 1972 47.450942 62.39492 57.319269 70.775033 71.910 # matplotlib operations # Here we use dataframe plot function # You could also use raw matplotlib plot one column each to do fine control # Please polish the figure with more configurations fig, ax = plt.subplots(figsize=(6, 4.5)) df.plot() There are several tricks in the data processing, please check the comments in the code. The rough plot looks like Please polish your figure with more matplotlib operations. For example: Set y-label Heigh of the two large, set legend to two columns to reduce it Colors of the line, or shapes of the line Line with markers? Here are some tweaks # set axis labels ax.set_xlabel('Year') ax.set_ylabel('Life Expection') # set markers markers = ['o', 's', 'd', '^', 'v'] for i, line in enumerate(ax.get_lines()): line.set_marker(markers[i]) # update legend ax.legend(ax.get_lines(), df.columns, loc='best'…
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89017867
has text: Open it in 'w' mode.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51012429

pandas
tags question: http://stackoverflow.com/q/51150059
tags question: http://stackoverflow.com/q/51059678
tags question: http://stackoverflow.com/q/51059053
tags question: http://stackoverflow.com/q/51164414
tags question: http://stackoverflow.com/q/51059958
tags question: http://stackoverflow.com/q/51069117
tags question: http://stackoverflow.com/q/51022484
tags question: http://stackoverflow.com/q/51133759
tags question: http://stackoverflow.com/q/51043135
tags question: http://stackoverflow.com/q/51049364
tags question: http://stackoverflow.com/q/51082855
tags question: http://stackoverflow.com/q/51119308
tags question: http://stackoverflow.com/q/51011961
tags question: http://stackoverflow.com/q/51046733
tags question: http://stackoverflow.com/q/51105220
tags question: http://stackoverflow.com/q/51105648
tags question: http://stackoverflow.com/q/51099939
tags question: http://stackoverflow.com/q/51115365
tags question: http://stackoverflow.com/q/51155624
tags question: http://stackoverflow.com/q/51060031
tags question: http://stackoverflow.com/q/51067854
tags question: http://stackoverflow.com/q/51065979
tags question: http://stackoverflow.com/q/51163175
tags question: http://stackoverflow.com/q/51060309
tags question: http://stackoverflow.com/q/51057324
tags question: http://stackoverflow.com/q/51130389
tags question: http://stackoverflow.com/q/51045533
tags question: http://stackoverflow.com/q/51039541
tags question: http://stackoverflow.com/q/51044704
tags question: http://stackoverflow.com/q/51139280
tags question: http://stackoverflow.com/q/51078183
tags question: http://stackoverflow.com/q/51115262
tags question: http://stackoverflow.com/q/51063597
tags question: http://stackoverflow.com/q/51081451
tags question: http://stackoverflow.com/q/51141635
tags question: http://stackoverflow.com/q/51128185
tags question: http://stackoverflow.com/q/51148821
tags question: http://stackoverflow.com/q/51157472
tags question: http://stackoverflow.com/q/51106520
tags question: http://stackoverflow.com/q/51164157
tags question: http://stackoverflow.com/q/51108064
tags question: http://stackoverflow.com/q/51142294
tags question: http://stackoverflow.com/q/51137522
tags question: http://stackoverflow.com/q/51145916
tags question: http://stackoverflow.com/q/51084137
tags question: http://stackoverflow.com/q/51156775
tags question: http://stackoverflow.com/q/51132161
tags question: http://stackoverflow.com/q/51031669
tags question: http://stackoverflow.com/q/51030465
tags question: http://stackoverflow.com/q/51079983
tags question: http://stackoverflow.com/q/51080137
tags question: http://stackoverflow.com/q/51143498
tags question: http://stackoverflow.com/q/51128226
tags question: http://stackoverflow.com/q/51121170
tags question: http://stackoverflow.com/q/51086372
tags question: http://stackoverflow.com/q/51092267
tags question: http://stackoverflow.com/q/51138799
tags question: http://stackoverflow.com/q/51088107
tags question: http://stackoverflow.com/q/51144340
tags question: http://stackoverflow.com/q/51082752
tags question: http://stackoverflow.com/q/51135289
tags question: http://stackoverflow.com/q/51051777
tags question: http://stackoverflow.com/q/51083795
tags question: http://stackoverflow.com/q/51062176
tags question: http://stackoverflow.com/q/51058378
tags question: http://stackoverflow.com/q/51023364
tags question: http://stackoverflow.com/q/51042113
tags question: http://stackoverflow.com/q/51067932
tags question: http://stackoverflow.com/q/51125029
tags question: http://stackoverflow.com/q/51074466
tags question: http://stackoverflow.com/q/51055000
tags question: http://stackoverflow.com/q/51064427
tags question: http://stackoverflow.com/q/51129944
tags question: http://stackoverflow.com/q/51100921
tags question: http://stackoverflow.com/q/51103686
tags question: http://stackoverflow.com/q/51130278
tags question: http://stackoverflow.com/q/51157288
tags question: http://stackoverflow.com/q/51146012
tags question: http://stackoverflow.com/q/51122262
tags question: http://stackoverflow.com/q/51135309

http://stackoverflow.com/a/51164477
accepted answer of: http://stackoverflow.com/q/51164291
score: 3
has body: The following code produces similar results, but you'll want to play around with some of the parameters (colormap, normalization range (vmin, vmax), view angle, axis tick locations) to get exactly what you want: import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection def patch(ax, x, y, z, v, vmin=0, vmax=100, cmap_name='viridis'): cmap = mpl.cm.get_cmap(cmap_name) # Get colormap by name c = cmap(mpl.colors.Normalize(vmin, vmax)(v)) # Normalize value and get color pc = Poly3DCollection([list(zip(x,y,z))]) # Create PolyCollection from coords pc.set_facecolor(c) # Set facecolor to mapped value pc.set_edgecolor('k') # Set edgecolor to black ax.add_collection3d(pc) # Add PolyCollection to axes return pc def view(ax, code): if code == 2: #view(2) sets the default two-dimensional view, az = 0, el = 90. ax.view_init(90, 0) # (args are reversed from MATLAB) if code == 3: #view(3) sets the default three-dimensional view, az = –37.5, el = 30. ax.view_init(30, -37.5) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = [0.0, 1.0, 0.0]; y = [0.0, 0.0, 1.0]; z = [0.0, 1.0, 1.0]; v = 100.0; patch(ax, x, y, z, v) x = [1.0, 1.0, 0.0]; y = [0.0, 1.0, 1.0]; z = [1.0, 0.0, 1.0]; v = 50.0; patch(ax, x, y, z, v) view(ax, 3) plt.show() Produces: (The image at the top of the answer is rotated to get a similar view to yours in the question, because something seems off).
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51164291
upvote count: 3
type: Answer

http://stackoverflow.com/comment/89149880
type: QuestionComment
has text: Does `df['day-hour'] = ['Day{:02} - {}'.format(*x) for x in zip((df.hour//24).add(1), df.hour%24)]` work?
score: 0
comment on: http://stackoverflow.com/q/51080695
type: Comment

http://stackoverflow.com/comment/89343951
has text: @J.Doe Can you clarify what you mean by shifting, specifically how `board[value]` factors into the shift?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51159560
type: AnswerComment

http://stackoverflow.com/a/51032904
answers question: http://stackoverflow.com/q/51031139
has comment: http://stackoverflow.com/comment/89058211
accepted answer of: http://stackoverflow.com/q/51031139
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89058182
score: 1
has comment: http://stackoverflow.com/comment/89058118
type: AcceptedAnswer
downvote count: 0
has body: Without having any sample URLs to test with, the simplest solution I could find is this: ^https:\/\/www.indiegogo.com\/explore\/[a-z\-?_=]+&amp;project_timing=[a-z_]+&amp;tags=&amp;sort=trending$ So here's a breakdown of what I did differently: Instead of [a-z]+-?[a-z]+\?project_type=[a-z]+, I simplified it with [a-z\-?_=]+ Instead of [a-z]+_?[a-z]+ I used [a-z_]+ The only issue I saw was that you aren't taking full advantage of your character classes. If you would like to provide a few sample URLs I'd be able to fix any issues you might run into. But as far as I can tell, it does what you need it to. You can also use ^https:\/\/www.indiegogo.com\/explore\/[\w\-]+&amp;project_timing=[\w]+&amp;tags=&amp;sort=trending$ if you really want to simplify, but that might not be restrictive enough.
has comment: http://stackoverflow.com/comment/89058205

http://stackoverflow.com/q/51049993
favorite count: 0
has body: How do I create a datetime field in a cython struct: cdef struct Purchase: int purchase_id datetime purchase_timestamp str free_text What should I use to represent the "datetime" identifier above? What about for a string? Would I just use a "char*" Is there something more flexible? If I delete an instance of the Purchase class, do I have to do any memory cleanup? Thanks!
has answer: http://stackoverflow.com/a/51059318
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: cython
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/55534938
has title: How do I create a datetime field in a cython struct? How about a string field?
accepted answer: http://stackoverflow.com/a/55534938
answer count: 2
possible better answer: http://stackoverflow.com/a/51059318
tagged with: python

http://stackoverflow.com/comment/89098312
comment on: http://stackoverflow.com/a/51053508
has text: Yes, I have solved it by making a function and checking each number one by one
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89095029
has text: @user2357112 judging by the example given later, he probably meant `r'\x26hl\x3den'` - notice the `r`.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51051619

http://stackoverflow.com/comment/89281625
has text: Possible duplicate of [Print the file name, line number and function name of a calling function - C Prog](https://stackoverflow.com/questions/8884335/print-the-file-name-line-number-and-function-name-of-a-calling-function-c-pro)
comment on: http://stackoverflow.com/q/51148129
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51021468
tagged with: dataframe
score: 12
has answer: http://stackoverflow.com/a/65520208
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89035599
has body: Data frame I am working with a data frame in Jupyter Notebooks and I am having some difficulty with it. The data frame consists of locations and these are represented by coordinates. These points represent a route taken by a driver on a given day. There are 3 columns at the moment; Start, Intermediary or End. A driver begins the day at the Start point, visits 1 or more Intermediary points and returns to the End point at the end of the day. The Start point is like a base location so the End point is identical to the Start point. It's very basic but I am having trouble visualising this data. I was thinking something like this below to help improve my situation: | Start | Intermediary | End | | | | | | | | _________________________________________________________________ | s_lat | s_lng | i_lat | i_lng | e_lat | e_lng | Or would it be best if I scrap the top 3 columns (Start, Intermediary, End)? I am keen not to start a discussion here as per the Guidelines so I am keen to learn something new about Python Pandas and if there is a way I can improve my current method.
has comment: http://stackoverflow.com/comment/89035533
favorite count: 0
possible better answer: http://stackoverflow.com/a/65520208
has title: Can sub-columns be created in a pandas data frame?
tagged with: python
has comment: http://stackoverflow.com/comment/89035509
upvote count: 12
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51021613
type: Question
has answer: http://stackoverflow.com/a/51021604
has comment: http://stackoverflow.com/comment/89035450
has answer: http://stackoverflow.com/a/51021613

http://stackoverflow.com/comment/89170894
has text: switched it to single slash and seems to be having the same error.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51091297
type: Comment

http://stackoverflow.com/comment/89141532
type: Comment
comment on: http://stackoverflow.com/q/51076211
score: 0
has text: And the question is? Also include the output of model.summary()
type: QuestionComment

http://stackoverflow.com/comment/89119798
has text: First thing you need to figure out is whether you want the program to be executed on the server, or on the user's own computer. If it is the former, then you need to set up django on the web server, and have it act as an API which will receive requests and run your program. Then make a webpage using HTML/CSS/JS (or PHP) and make it send requests to the django API. If it is the latter, then you will have to give them the program in an executable format. This means you can either give them an .exe, or just the python source code. Either way, they have to download some sort of file and run it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51064844
score: 1

http://stackoverflow.com/comment/89238549
comment on: http://stackoverflow.com/q/51126737
score: 0
has text: How come you're writing a new package for Python 2?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51022411
has answer: http://stackoverflow.com/a/51022553
tagged with: python
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/1247486
upvote count: 3
linked to: http://stackoverflow.com/q/31343643
accepted answer: http://stackoverflow.com/a/51022553
type: Question
tagged with: benchmarking
tagged with: performance
downvote count: 0
has title: Performance of loops, list comprehensions and maps in Python 3
has body: How is it possible to properly compare performance of for loops, list comprehensions and maps in Python 3.6? In the code below, plain old for loops perform quite well (I used list() to get values from generators). Am I doing something wrong here? The results are in stark contrast to the discussion on Python 2. import timeit code_for = """ for i in range(1000): hex(i) """ code_map = """ list(map(hex, range(1000))) """ code_map_lambda = """ list(map(lambda x: hex(x), range(1000))) """ code_list_comprehension = """ [hex(x) for x in range(1000)] """ print(timeit.timeit(code_for, number=10000)) # 1.1155821208376437 print(timeit.timeit(code_map, number=10000)) # 0.8820606248918921 print(timeit.timeit(code_map_lambda, number=10000)) # 1.7510833400301635 print(timeit.timeit(code_list_comprehension, number=10000)) # 1.1798800542019308 UPDATE: Adding elements to a list in code_for code_for_2 = """ a = [0] * 1000 for i in range(1000): a[i] = hex(i) """ # 1.243549756007269 code_for_3 = """ a = [] for i in range(1000): a.append(hex(i)) """ # 1.5462996119167656
linked to: http://stackoverflow.com/q/22108488
linked to: http://stackoverflow.com/q/30245397
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/11616599

http://stackoverflow.com/comment/89073169
has text: Yeah! It worked! I changed the form. I put the letters and numbers manually for all and looks like it worked. Thanks, man (or girl)!
comment on: http://stackoverflow.com/q/51037937
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51064746
answer count: 1
tagged with: r-markdown
has answer: http://stackoverflow.com/a/51098273
has body: Variable are not retained from one chunk to the next in notebook mode, but they are retained when knitting the markdown document to html. I made a sample document available as a gist called pythonvariables.Rmd, the content of this file is: --- title: "R Notebook" output: html_document: df_print: paged --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) library(reticulate) ``` ```{python} x = 1 ``` ```{python} print(x) ``` ```{r} print(py$x) ``` In Rstudio version 1.1.453, in notebook mode, when running one chunk after the other, the output of the print(x) python chunk is: Traceback (most recent call last): File "C:\Users\rougipa\AppData\Local\Temp\2\RtmpQFW3Rj\chunk-code-1d44920f50.txt", line 1, in &lt;module&gt; print(x) NameError: name 'x' is not defined However the issue doesn't appear when the Rmd is compiled to html. The output of the print(x) python chunk is 1 as expected.
score: 6
tagged with: reticulate
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
has title: How to make a python variable persist between chunks in a markdown notebook?
accepted answer: http://stackoverflow.com/a/51098273
tagged with: knitr
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/89160499
has comment: http://stackoverflow.com/comment/89120811
has comment: http://stackoverflow.com/comment/89119849

http://stackoverflow.com/comment/89323844
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51163730
type: Comment
has text: sorry i idn't get, can you please explain wat u did

http://stackoverflow.com/q/51125119
has comment: http://stackoverflow.com/comment/89235165
type: Question
has answer: http://stackoverflow.com/a/51125163
has comment: http://stackoverflow.com/comment/89235241
score: 0
has comment: http://stackoverflow.com/comment/89235256
answer count: 1
has comment: http://stackoverflow.com/comment/89235247
accepted answer: http://stackoverflow.com/a/51125163
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89235272
tagged with: python
has comment: http://stackoverflow.com/comment/89235227
has title: pass not skipping the rest of the loop
has body: i'm making a small program where user creates an account but for some reason in this part of the code pass does nothing can somebody please explain this? def create_password(): while True: password = '#' not_allowed_characters = '!#¤%&amp;/()=?^\'.,&lt;&gt;' for c in list(password): 0 + 0 if c in not_allowed_characters: print(c + ' is not allowed') pass #pass does nothing how can i fix this if 0 is 0: print(1) create_password()
type: AnsweredQuestion

http://stackoverflow.com/a/51117557
has body: In Python input always returns a string. If you want to consider it as an int you have to convert it. num = int(input('Choose a number: ')) print(num, type(num)) If you aren't sure of the type you can do: num = input('Choose a number: ') try: num = int(num) except: pass print(num, type(num))
has comment: http://stackoverflow.com/comment/89221892
has comment: http://stackoverflow.com/comment/89221859
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51117498
upvote count: 2

http://stackoverflow.com/q/51046917
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51062850
downvote count: 0
has title: Batched tensor multiplication with numpy
has body: I am trying to perform the following matrix and tensor multiplication, but batched. I have a list of x vectors: x = np.array([[2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [5.0, 5.0]]) and the following matrix and tensor: R = np.array( [ [1.0, 1.0], [0.0, 1.0], ] ) T = np.array( [ [ [2.0, 0.0], [0.0, 0.0], ], [ [0.0, 0.0], [0.0, 2.0], ] ] ) The batched matrix multiplication is relatively straightforward: x.dot(R.T) However I am struggling with the second part. I tried using tensordot but with no success so far. What am I missing?
has comment: http://stackoverflow.com/comment/89086999
possible better answer: http://stackoverflow.com/a/51048025
has answer: http://stackoverflow.com/a/51048168
answer count: 4
has comment: http://stackoverflow.com/comment/89090336
favorite count: 0
has comment: http://stackoverflow.com/comment/89090319
has answer: http://stackoverflow.com/a/51047506
has comment: http://stackoverflow.com/comment/89088069
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51062850
has answer: http://stackoverflow.com/a/51048025
tagged with: linear-algebra

http://stackoverflow.com/q/51063353
tagged with: resampling
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
has body: I have 15 min OHLC data coming in continuously from an API and I wish to resample it to 30 min 1H etc +----------------------+----------+----------+----------+----------+------------+ | time | open | high | low | close | volumeto | +----------------------+----------+----------+----------+----------+------------+ | | | | | | | | 2018-06-26 03:30:00 | 6244.56 | 6250.54 | 6243.55 | 6247.34 | 1801280.76 | | 2018-06-26 03:45:00 | 6247.34 | 6257.61 | 6246.43 | 6248.23 | 2551368.76 | | 2018-06-26 04:00:00 | 6248.53 | 6248.53 | 6238.11 | 6239.83 | 2148705.55 | | 2018-06-26 04:15:00 | 6239.83 | 6240.93 | 6232.14 | 6239.00 | 1906012.45 | | 2018-06-26 04:30:00 | 6239.78 | 6269.14 | 6239.67 | 6260.96 | 3869709.59 | | 2018-06-26 04:45:00 | 6261.16 | 6263.50 | 6249.46 | 6260.19 | 2236911.26 | | 2018-06-26 05:00:00 | 6260.19 | 6284.27 | 6257.97 | 6263.73 | 5131896.24 | | 2018-06-26 05:15:00 | 6263.73 | 6272.73 | 6263.59 | 6270.30 | 1589515.40 | | 2018-06-26 05:30:00 | 6270.30 | 6286.36 | 6268.78 | 6270.69 | 2859640.60 | | 2018-06-26 05:45:00 | 6271.75 | 6274.69 | 6259.29 | 6261.20 | 2448639.24 | +----------------------+----------+----------+----------+----------+------------+ As per my use case, I round 3:45 and 4:00 from 15 mins to 4:00 at 30 mins and so on agg = { 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volumeto': 'sum'} df.resample('30min', closed='right', label='right').agg(agg) Original 15 mins data 30 mins after rounding As you notice in the 30 mins timeframe, the first candle is generated from only 1 15 min candle instead of 2. How do I skip incomplete candles only at the beginning of my computation instead of the end? I would like to similary skip for 1 hr etc Thanks
accepted answer: http://stackoverflow.com/a/51063748
has title: Pandas resample skip incomplete groups at the start
type: Question
has comment: http://stackoverflow.com/comment/89116775
score: 0
has comment: http://stackoverflow.com/comment/89116762
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89116694
has comment: http://stackoverflow.com/comment/89116600
has answer: http://stackoverflow.com/a/51063748

http://stackoverflow.com/q/51091500
has body: I am using matplotlib and ffmpeg to do some animations. I usually code on a remote server because the code runs faster; we are having some issues making animations on the remote server. Here is an example of code that works perfectly on my local mac but does not work remotely. import matplotlib as mpl mpl.use('agg') import matplotlib as mpl from matplotlib import animation import pylab def init(): pylab.plot(pylab.arange(10), [0]*10) def redraw(frame): pylab.plot(pylab.arange(10), pylab.arange(10) * frame) fig = pylab.figure() ani = animation.FuncAnimation(fig, redraw, frames=10, interval=1000, init_func=init) ani.save('animation.mp4') I get the animation I want on my local machine (macOS Sierra). When I run it on the remote host (Debian GNU/Linux 8 (jessie)), I get the following error message after 5 frames Traceback (most recent call last): File "animation.py", line 14, in &lt;module&gt; ani.save('animation.mp4') File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1200, in save writer.grab_frame(**savefig_kwargs) File "/usr/lib/python2.7/contextlib.py", line 35, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 241, in saving self.finish() File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 367, in finish self.cleanup() File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 405, in cleanup out, err = self._proc.communicate() File "/usr/local/lib/python2.7/dist-packages/subprocess32.py", line 724, in communicate stdout, stderr = self._communicate(input, endtime, timeout) File "/usr/local/lib/python2.7/dist-packages/subprocess32.py", line 1535, in _communicate orig_timeout) File "/usr/local/lib/python2.7/dist-packages/subprocess32.py", line 1591, in _communicate_with_poll register_and_append(self.stdout, select_POLLIN_POLLPRI) File "/usr/local/lib/python2.7/dist-packages/subprocess32.py", line 1570, in register_and_append …
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89209429
tagged with: animation
linked to: http://stackoverflow.com/q/42133545
tagged with: python
has comment: http://stackoverflow.com/comment/89188853
answer count: 0
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/89250626
has title: ValueError: I/O operation on closed file when making animation
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/51073860
has comment: http://stackoverflow.com/comment/89150109
has comment: http://stackoverflow.com/comment/89137418
has answer: http://stackoverflow.com/a/51074184
has body: I have a txt file which contains lost of information,I do not want its head and tail, I need only numbers in the middle. which is a 1x11200 matrix. [txtpda] LT=5.6 DATE=21.06.2018 TIME=14:11 CNT=11200 RES=0.00854518 N=5 VB=350 VT=0.5 LS=0 MEASTIME=201806211412 PICKUP=BFW-2 LC=0.8 [PROFILE] 255 256 258 264 269 273 267 258 251 255 259 262 260 256 255 260 264 266 265 263 261 263 267 275 280 280 280 280 283 284 283 277 279 280 283 285 283 282 280 280 286 288 298 299 299 299 304 303 300 297 295 296 299 301 303 301 299 296 298 299 302 303 304 307 308 312 313 314 312 311 311 310 312 310 309 305 303 299 297 294 288 280 270 266 250 242 222 213 199 180 173 ... -1062 -1063 [VALUES] Ra;2;3;2;0.769;0;0;-1;0;-1;0 Rz;2;2;2;5.137;0;0;-1;0;-1;0 Pt;0;0;0;26.25;0;0;-1;0;-1;0 Wt;0;0;0;24.3;0;0;-1;0;-1;0 now I using the following method to extract numbers: def OpenFile(): name=askopenfilename(parent=root) f=open(name,'r') originalyvec1=[] yvec1=[] if f==0: print("fail to open the file") else: print("file successfully opened") data=f.readlines() for i in range(0,14): del data[0]//delete its head（string) del data[11204]//delete its tail（string) del data[11203]//delete its tail（string) del data[11202]//delete its tail（string) del data[11201]//delete its tail（string) del data[11200]//delete its tail（string) for line in data: for nbr in line.split(): //delete \n yvec1.append(int(nbr)) if f.close()==0: print("fail to close file") else: print("file closed") I want to use numpy to manage it in a easy way. Is that possible? like np.array or something like that.
answer count: 3
has comment: http://stackoverflow.com/comment/89145082
has answer: http://stackoverflow.com/a/51073981
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51074126
type: Question
tagged with: numpy
score: 0
has title: extract only integer from txt

http://stackoverflow.com/a/51080909
score: 3
accepted answer of: http://stackoverflow.com/q/51046660
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51046660
type: Answer
has body: It seems to me, that without adding pkg to my PATH it is impossible to import modules from sub2 in sub1. Here is explanation why: Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. Here is official python web site, where it is explained
upvote count: 3

web-crawler
tags question: http://stackoverflow.com/q/51147667
tags question: http://stackoverflow.com/q/51050262
tags question: http://stackoverflow.com/q/51062223
tag name: web-crawler
tags question: http://stackoverflow.com/q/51054489
type: Tag
tags question: http://stackoverflow.com/q/51132582
tags question: http://stackoverflow.com/q/51023512
tags question: http://stackoverflow.com/q/51074475
tags question: http://stackoverflow.com/q/51106832

http://stackoverflow.com/a/51118880
type: Answer
answers question: http://stackoverflow.com/q/51118801
downvote count: 0
score: 1
upvote count: 1
has body: each line starts with the very same string which i want to delete. The problem is you're passing a string "text_to_replace" rather than the variable text_to_replace. But, for this specific problem, you could just remove the first n characters from each line: text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |" n = len(text_to_replace) for each_line in siera_log: new_line = each_line[n:] print(new_line)

http://stackoverflow.com/a/51137393
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51136829
answers question: http://stackoverflow.com/q/51136829
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89259442
has body: I don't use notebooks very much, but presumably you have to turn off interactive plotting: from matplotlib import pyplot as plt; plt.ioff() Then show the figure after making the plot: def make_plot(self): x = np.linspace(0, 1) y = np.random.normal(loc=0, scale=1, size=len(x)) self.ax.scatter(x,y) plt.show()

http://stackoverflow.com/comment/89083533
comment on: http://stackoverflow.com/a/51045619
has text: @jezrael yes you are right , it is dup man :-) , thank you for find it out , also learn from the accepted answer
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89273210
has text: please do, thank you.
comment on: http://stackoverflow.com/q/51143682
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51025882
downvote count: 1
has answer: http://stackoverflow.com/a/51026046
has answer: http://stackoverflow.com/a/51026057
type: Question
has title: Which one is better for string reverse in Python 3?
upvote count: 9
has body: s="google" print("".join(reversed(s))) //elgoog print(s[::-1]) //elgoog In above the string is reverse using python 3 reversed method and slicing method both display the same output, but from this which one is most efficient in python programming language, why??
has comment: http://stackoverflow.com/comment/89044256
linked to: http://stackoverflow.com/q/931092
answer count: 2
has comment: http://stackoverflow.com/comment/89044606
tagged with: string
favorite count: 0
score: 8
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89044823
tagged with: performance
has comment: http://stackoverflow.com/comment/89044595

http://stackoverflow.com/q/51040994
tagged with: python
has answer: http://stackoverflow.com/a/51041480
has comment: http://stackoverflow.com/comment/89073699
type: UnansweredQuestion
tagged with: web-scraping
has title: From scraping to a CSV file
type: Question
tagged with: export-to-csv
score: 0
answer count: 1
has body: I am new to python and I am trying to turn scraping data to a CSV file but without success. Here is the code: from urllib.request import urlopen, Request from bs4 import BeautifulSoup import os import random import re from itertools import cycle def cleanhtml(raw_html): cleanr = re.compile('&lt;.*?&gt;') #cleaning the strings from these terms cleantext = re.sub(cleanr, '', raw_html) return cleantext def scrape(url, filename, number_id): """ This function scrapes a web page looking for text inside its html structure and saves it in .txt file. So it works only for static content, if you need text in a dynamic part of the web page (e.g. a banner) look at the other file. Pay attention that the retrieved text must be filtered out in order to keep only the part you need. url: url to scrape filename: name of file where to store text number_id: itis appended to the filename, to distinguish different filenames """ #here there is a list of possible user agents user_agent = random.choice(user_agent_list) req = Request(url, headers={'User-Agent': user_agent}) page = urlopen(req).read() # parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(page, "html.parser") row = soup.find_all(class_="row") for element in row: viaggio = element.find_all(class_="nowrap") Partenza = viaggio[0] Ritorno = viaggio[1] Viaggiatori = viaggio[2] Costo = viaggio[3] Title = element.find(class_="taglist bold") Content = element.find("p") Destination = Title.text Review = Content.text Departure = Partenza.text Arrival = Ritorno.text Travellers = Viaggiatori.text Cost = Costo.text TuristiPerCasoList = [Destination, Review, Departure, Arrival, Travellers, Cost] print(TuristiPerCasoList) Till here, everything works. Now I have to turn it into a CSV file. I tried with this: import csv with open('turistipercaso','w') as file: writer = csv.writer(file) writer.writerows(TuristiPerCasoList) but it doesn't return anything in the CSV file. Can someone help me understanding what to …
tagged with: beautifulsoup

http://stackoverflow.com/a/51085663
has body: Check the range of values in sig by printing sig.min() and sig.max(). The values are not scaled by wavfile.write, so it might be that you have a file with values so low that you can't hear them. Try scaling up the 32 bit integer values, or writing the data as normalized 32 bit floating point. For example, this converts sig to 32 bit floating point values in the range [-1, 1] before saving it: m = np.max(np.abs(sig)) sigf32 = (sig/m).astype(np.float32) sp.io.wavfile.write('sound.wav', int(fS), sigf32)
answers question: http://stackoverflow.com/q/51079048
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/89188938
type: Answer
accepted answer of: http://stackoverflow.com/q/51079048

http://stackoverflow.com/comment/89251422
type: Comment
comment on: http://stackoverflow.com/a/51024203
score: 0
type: AnswerComment
has text: How big is your dataset?

http://stackoverflow.com/comment/101207526
type: AnswerComment
comment on: http://stackoverflow.com/a/57360008
score: 0
type: Comment
has text: They're not using Anaconda

atom-editor
tags question: http://stackoverflow.com/q/51094384
tags question: http://stackoverflow.com/q/51162538
tags question: http://stackoverflow.com/q/51163513
tags question: http://stackoverflow.com/q/51072007
type: Tag
tags question: http://stackoverflow.com/q/51031002
tag name: atom-editor
tags question: http://stackoverflow.com/q/51159578

http://stackoverflow.com/q/51077293
accepted answer: http://stackoverflow.com/a/53464613
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/51078349
tagged with: python
downvote count: 0
has body: I am trying to change the ordering of the leaf nodes in the Scipy dendrogram plot function. Consider the following snippet: from scipy.cluster.hierarchy import linkage, dendrogram import matplotlib.pyplot as plt dists = [ 2., 10., 3.] lx = linkage(dists, 'complete') dendrogram(lx) plt.show() The resulting dendrogram plot is: I would like to change the ordering of the leaf nodes to 0, 1, 2 in this plot. Is there an easy way to achieve this? I tried all the possible settings of the arguments count_sort and distance_sort from dendrogram, but the ordering remains the same.
type: Question
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51078349
has title: Scipy dendrogram leaf node ordering
tagged with: scipy
answer count: 2
has answer: http://stackoverflow.com/a/53464613

http://stackoverflow.com/q/51166586
has answer: http://stackoverflow.com/a/51168868
upvote count: 6
has comment: http://stackoverflow.com/comment/89316321
has answer: http://stackoverflow.com/a/51167521
has title: What is the more elegant way of finding combinations in a list?
has answer: http://stackoverflow.com/a/51166925
type: Question
has answer: http://stackoverflow.com/a/51167329
answer count: 6
score: 4
has answer: http://stackoverflow.com/a/51166665
favorite count: 0
has answer: http://stackoverflow.com/a/51224906
has body: I came up with this algorithm to find triplets of pairs (I call them trairs), the criteria is that all 3 elements (coins), and only the 3, must be present in all 3 pairs. However, it is probably possible to solve the same problem in a more elegant way. For instance, I am indexing all the loops, which makes it look extra complicated. Also, there is a break there that makes me uncomfortable! The input data is pairs, it is a list of str: Eg. pairs = ['BCH/BTC','BCH/ETH','DASH/USD','BTC/USDT','ETH/BTC'] The wanted output is a list of list of strings: Eg. trair = 'BCH/BTC','BCH/ETH','ETH/BTC def find_trairs(exchange): ''' Find possible triplets of pairs (trairs) that can be traded for unbalance. Example of trairs: 'ETC/BTC' 'ETC/ETH' 'ETH/BTC' 'BCH/BTC' 'BCH/EUR' 'BTC/EUR' ''' exchange_pairs = exchange.symbols #loads all pairs from the exchange. pairs = list(filter(lambda x: not '.d' in x, exchange_pairs)) #filters off #the darkpool pairs. pair = ['', '', ''] coin = ['', '', ''] trair = [] #Semi-optimized loop to look for triplece of pairs. #Example:['BCH/BTC', 'BCH/EUR', 'BTC/EUR'] for i in range(len(pairs)-3): #not all coins are 3 digits long, we must find the slash that separetes #each coin in order to have a robust algorithm. slash_position = pairs[i].find('/') coin[0] = pairs[i][0:slash_position] coin[1] = pairs[i][slash_position+1:] for j in range(i+1, len(pairs)-2): if (coin[0] in pairs[j]): slash_position = pairs[j].find('/') coin[2] = pairs[j][slash_position+1:] for k in range(j+1, len(pairs)-1): if coin[1] in pairs[k] and coin[2] in pairs[k]: trair.append([pairs[i], pairs[j], pairs[k]]) break return trair Any hints or comments?
tagged with: combinatorics
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89316434
type: UnansweredQuestion
downvote count: 2
tagged with: python

http://stackoverflow.com/q/51043238
has title: How to fill an angle interval in a wind rose plot using PyPlot lib
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/51107985
score: 0
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51107985
tagged with: python
has body: I have angle interval such init angle=10º and end angle=20º, and would like to fill the area with some colour using a polar plot (wind rose) with PyPlot lib Wind rose plot Is that possible using this kind of subplot?

http://stackoverflow.com/q/51119621
score: -5
tagged with: file
has comment: http://stackoverflow.com/comment/89225061
has comment: http://stackoverflow.com/comment/89224998
upvote count: 1
type: Question
has title: How to read a file in Python
has answer: http://stackoverflow.com/a/51334789
answer count: 3
has body: I have a file on my computer called test. It's a .py file. I only have 2 things in the file. 'Is this working? "Probably not." When I try to read it I get this: &gt;&gt;&gt;t = open('test') &gt;&gt;&gt;t &lt;_io.TextIOWrapper name='test' mode='r' encoding='cp1252'&gt; &gt;&gt;&gt;t.read() '' Sorry if this is a stupid question, but I'm a pretty new at this. I have some ideas on what it could be, but I can't find any answers online. Thanks in advance. Thank you all for the answers! I just opened up a new file and printed "f.readlines" and it worked. I also think my problem was I was using IDLE, which I've come to notice doesn't really work that well with some commands, for some reason. Either way, thank you all for the help!
has comment: http://stackoverflow.com/comment/89225166
favorite count: 0
has answer: http://stackoverflow.com/a/51119747
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89224989
tagged with: python
has answer: http://stackoverflow.com/a/51119899
downvote count: 6

http://stackoverflow.com/comment/89088923
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51044923
has text: Can we provide private key as well in the input instead of file like we did for passphrase in the above command?
type: AnswerComment

http://stackoverflow.com/q/51163995
linked to: http://stackoverflow.com/q/38233838
score: 4
has title: How can I select every nth child in BeautifulSoup?
accepted answer: http://stackoverflow.com/a/51168577
has body: In my table below I have scraped Items 1-4 and stored them in a variable called headings. I would also like to select Values 1-4 and store them in a variable called columns, is there anyway to select every second . Something like columns = boxinfo.find_all("td").nthChild(2) Table structure I am scraping from Item1 Value1 Item2 Value2 Item3 Value3 Item4 Value4 Code #Find our information boxinfo = soup.find("div", {"id": "box1"}) headings = boxinfo.find_all("td", {"class": "label"}) columns = boxinfo.find_all("td").nthChild(2) #This does not work :(
answer count: 1
has comment: http://stackoverflow.com/comment/89312458
upvote count: 4
has comment: http://stackoverflow.com/comment/89312422
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51168577
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/98112481
tagged with: python
linked to: http://stackoverflow.com/q/55764574

http://stackoverflow.com/comment/89129349
type: AnswerComment
comment on: http://stackoverflow.com/a/51060631
has text: Ah yes. You need --runtime-version. Can you accept my answer?
type: Comment
score: 1

http://stackoverflow.com/a/72980995
downvote count: 1
upvote count: 4
score: 3
has comment: http://stackoverflow.com/comment/138378468
type: Answer
has body: In this approach you just need to set the name of column with Json content. No need to set up the schema. It makes everything automatically. json_col_name = 'data' keys = df.select(f"{json_col_name}.*").columns jsonFields= [f"{json_col_name}.{key} {key}" for key in keys] main_fields = [key for key in df.columns if key != json_col_name] df_new = df.selectExpr(main_fields + jsonFields)
answers question: http://stackoverflow.com/q/51070251

http://stackoverflow.com/comment/89274894
type: Comment
has text: Got AttributeError when attempting to get a value for field `video_details` on serializer `VideoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Video` instance. Original exception text was: 'Video' object has no attribute 'video_details'. Anything goes wrong?
comment on: http://stackoverflow.com/a/51143079
type: AnswerComment
score: 0

http://stackoverflow.com/a/51041480
has body: In each iteration, you are reassigning the TuristiPerCasoList value. What you actually want is a list of list of strings, where the string is the value for a specific cell, the second list contains the values of a row and the first list contains all the rows. To achieve this, you should append a list representing a row to the main list: # instead of TuristiPerCasoList = [Destination, Review, Departure, Arrival, Travellers, Cost] # use TuristiPerCasoList.append([Destination, Review, Departure, Arrival, Travellers, Cost])
answers question: http://stackoverflow.com/q/51040994
score: 0
type: Answer

http://stackoverflow.com/comment/89174309
type: AnswerComment
score: 0
type: Comment
has text: Column A represents an event, while Column B represents different functions for that event. So John could be assigned with with different functions for the same event
comment on: http://stackoverflow.com/a/51092734

http://stackoverflow.com/comment/89221395
type: Comment
has text: thanks a lot. The target df should be different as I posted in the question. the df that it produces have lots of multiple arrays of data. Can you check that?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51116992

http://stackoverflow.com/q/51056172
type: Question
has title: Python: Reading marks from a file then using marks to get class
has answer: http://stackoverflow.com/a/51057319
has answer: http://stackoverflow.com/a/51056624
answer count: 3
has answer: http://stackoverflow.com/a/51057510
upvote count: 0
tagged with: readfile
score: -6
favorite count: 0
possible better answer: http://stackoverflow.com/a/51056624
tagged with: python
tagged with: text-files
accepted answer: http://stackoverflow.com/a/51057510
downvote count: 6
type: AnsweredQuestion
tagged with: notepad
has body: I have gotten this sheet and I am having trouble with it. The Task This is my notepad txt: maths_mark I want to create it like if: mark => 90 = 10M1 mark => 80 = 10M2 mark => 70 = 10M3 mark => 60 = 10M4 mark => 50 = 10M5 mark => 40 = 10M6 mark => 30 = 10M7 mark => 20 = 10M8 mark => 10 = 10M9 I am stuck on how to read the marks from the file then creating a new text file with the names, marks and class. If anyone can be any help, it would be appreciated. Thanks, Noob Coder
tagged with: file

http://stackoverflow.com/a/51121106
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51121097
has body: Use isin for boolean mask and filter by boolean indexing with df_A.index: idx = df_A.index[df_A['Col1'].isin(list_B)] print (idx) Int64Index([0, 2, 4], dtype='int64') If need list: idx = df_A.index[df_A['Col1'].isin(list_B)].tolist() print (idx) [0, 2, 4] Detail: print (df_A['Col1'].isin(list_B)) 0 True 1 False 2 True 3 False 4 True Name: Col1, dtype: bool For filtering all rows by list: df1 = df_A[df_A['Col1'].isin(list_B)] print (df1) Col1 Col2 0 AA 1 2 CC 3 4 AA 5 And for filter out values by list invert booleanmask by ~: df2 = df_A[~df_A['Col1'].isin(list_B)] print (df2) Col1 Col2 1 BB 2 3 DD 4 Detail: print (~df_A['Col1'].isin(list_B)) 0 False 1 True 2 False 3 True 4 False Name: Col1, dtype: bool
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51121097

http://stackoverflow.com/a/51115168
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51104928
score: 1
type: AcceptedAnswer
has body: In the infomap parameter brackets you need to specify edge weights as follows: G = Graph.Read_Ncol('1.txt', names=('node1', 'node2', 'weights'), directed=True) comms = G.community_infomap(edge_weights = 'weights') You can verify this makes a difference by subsequently checking the modularity after adding the weights function: q = G.modularity(comms) print(q) My own data's differences in modularity after leaving the parameter blank, then adding edge_weights: comms = G.community_infomap() q = G.modularity(comms) print(q) 0.6460833771434323 comms = G.community_infomap(edge_weights = 'weight') q = G.modularity(comms) print(q) 0.6130915761568664 If this doesn't work, then convert your datafile to GML without titles, and read it in as follows: G = Graph.Read_GML('Only2001_15Removed.gml') comms = G.community_infomap(edge_weights = 'weight')
downvote count: 0
has comment: http://stackoverflow.com/comment/117380968
accepted answer of: http://stackoverflow.com/q/51104928

http://stackoverflow.com/q/51149744
tagged with: python
has body: How to combine this line into pandas dataframe to drop columns which its missing rate over 90%? this line will show all the column and its missing rate: percentage = (LoanStats_securev1_2018Q1.isnull().sum()/LoanStats_securev1_2018Q1.isnull().count()*100).sort_values(ascending = False) Someone familiar with pandas please kindly help.
type: AnsweredQuestion
has title: pandas:drop columns which its missing rate over 90%
score: 1
upvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51151776
has answer: http://stackoverflow.com/a/51149831
accepted answer: http://stackoverflow.com/a/51151776
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51149831
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51023798
has body: From C11, use DBL_DECIMAL_DIG which is defined exactly for this use: See https://en.cppreference.com/w/c/types/limits. It tells you the number of decimal digits of precision required such that a load of a saved double, followed by a save then a reload will mean that the two load steps will always return the same double. DBL_DECIMAL_DIG is normally 17.
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/89042557
answers question: http://stackoverflow.com/q/51023663
downvote count: 0
has comment: http://stackoverflow.com/comment/89042628
has comment: http://stackoverflow.com/comment/89042840
upvote count: 3
has comment: http://stackoverflow.com/comment/89042488

http://stackoverflow.com/comment/89226134
comment on: http://stackoverflow.com/q/51120275
has text: What does the comparison do? What happens when there are discrepancies found between the content of `server.txt` and the actual list of IP-address-named directories?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51049566
has body: If I have the following sequence of calculations origvals = [3, 9, 2, 8, 5, 9, 1, 6, 3, 2] updates = [2, 5, 9, 8] indices = [0, 0, 0, 0, 1, 1, 1, 1, 1, 2] updates_pb = [2, 2, 2, 2, 5, 5, 5, 5, 5, 9] # tf.gather(updates, indices) result = origvals + updates_pb Here I've shown updates_pb as a sort of piecewise broadcast of the values '2', '5', and '9', based on the updates values and the indices. In my use case, almost always, the indices vector will have long runs of repeated values. Is there a more efficient way to compute the final result value than through the intermediate construction of the highly repetitious updates_pb tensor? A wish-list function might be: result = tf.gather_add(origvals, updates, indices)
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89785066
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: tensorflow
has title: Is there a good way to do "partial broadcast" in tensorflow?
type: Question

http://stackoverflow.com/a/51028090
has comment: http://stackoverflow.com/comment/89063709
score: 0
has comment: http://stackoverflow.com/comment/89541523
has body: That error means that the redirect URL attached by CKAN is not the same as the one you have registered as callback URL when registering the application in the IDM. Ensure that the callback URL you have included in the IDM is: http://YOUR_CKAN_INSTANCE/oauth2/callback The URL must match exactly (so no trailing backslash)
type: Answer
has comment: http://stackoverflow.com/comment/89318160
has comment: http://stackoverflow.com/comment/89073076
answers question: http://stackoverflow.com/q/51018647

http://stackoverflow.com/q/51163500
has title: Python parameter using arguments
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51163923
has comment: http://stackoverflow.com/comment/89312414
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89310384
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89310841
type: Question
has body: So I am trying to write a Python code that will allow me to list all files in a given folder along with size and creation date. I have gotten this part down. Then I am trying to put in a parameter so it only shows me results over > 1000 in size. Here is what I have so far. I am getting IndexError: list index out of range EDITED CODE: import os, sys from datetime import datetime created = os.stat('.').st_ctime path = sys.argv[1] dirs = os.listdir(path) for file in dirs: if os.stat(file).st_size == int(sys.argv[2]): print(file, os.stat(file).st_size, datetime.fromtimestampcreated)

http://stackoverflow.com/q/51165060
has answer: http://stackoverflow.com/a/51179018
has answer: http://stackoverflow.com/a/51165136
score: 1
accepted answer: http://stackoverflow.com/a/51171002
tagged with: selenium
upvote count: 1
possible better answer: http://stackoverflow.com/a/51165136
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89313466
has comment: http://stackoverflow.com/comment/89313405
has title: How do I get an element in a web page whose name is dynamically generated
answer count: 3
has body: So I am making a sort of web scraper with python and selenium, and one of the drop down menus I want to interact with is named different things based on other interactions on the site. It is named like this: &lt;select id ="sel-abfj184h48cj" &gt; Always with the sel- prefix and the rest dynamically generated. What is the best way to access this element? I have tried selenium's find by id, name, and XPath methods , and am a bit stuck. Any ideas?
downvote count: 0
has comment: http://stackoverflow.com/comment/89313448
has answer: http://stackoverflow.com/a/51171002
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/q/51125160
has title: Downloading package punkt to /Users/macbook/nltk_data... freezes
score: 1
has comment: http://stackoverflow.com/comment/89235345
type: Question
tagged with: nltk
linked to: http://stackoverflow.com/q/21194895
duplicate of: http://stackoverflow.com/q/21194895
tagged with: textblob
downvote count: 0
has body: I am trying to install TextBlob on Python 3.6.5. Everything is going just fine until I used this command line: python3 -m textblob.download_corpora and it started downloading package brown and package punkt. While the package brown was done and unzipped, the punkt one has been freezing for over an hour now. How can I solve this problem guys? Macbooks-Air:~ macbook$ python3 -m textblob.download_corpora [nltk_data] Downloading package brown to /Users/macbook/nltk_data... [nltk_data] Unzipping corpora/brown.zip. [nltk_data] Downloading package punkt to /Users/macbook/nltk_data...
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: freeze
has comment: http://stackoverflow.com/comment/89235425
answer count: 0

http://stackoverflow.com/q/51029343
type: Question
upvote count: 2
answer count: 2
favorite count: 0
tagged with: time
tagged with: python
score: 2
has title: time data '2018-06-19 11:21:13.311' does not match format
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51029466
has answer: http://stackoverflow.com/a/51029369
has body: Using python, I am trying to read a date/time format ergo 2018-06-19 11:21:13.311, which returns an error: ValueError: time data '2018-06-19 11:21:13.311' does not match format '%Y-%m-%d %I:%M:%S.%%' I have tried removing the .%%, but the program returns an unconverted data error message. Does anyone know what the .311 is? And how I can read it?

http://stackoverflow.com/comment/89305653
has text: sorry, I am struggling to write the answer in python3 syntax, but i've only got python2. will update
comment on: http://stackoverflow.com/a/51160874
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51126007
has comment: http://stackoverflow.com/comment/89237118
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89254566
type: Question
tagged with: python
score: -1
tagged with: tkinter
has body: This is my practice from youtube, It's not showing button in window import tkinter as tk class Window(Frame): def _init_ (self, master =None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title('GUI') self.pack(fill = BOTH, expand = 1) quitButton = Button(self, text = "Quit") quitButton.place(x=0, y =.1) root = tk.Tk() root.title('GUI') root.geometry() app = Window(master=root) root.mainloop()
has comment: http://stackoverflow.com/comment/89256614
answer count: 1
downvote count: 1
has title: Tkinter code not showing button (v:3.6)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51126138

http://stackoverflow.com/q/51029033
has comment: http://stackoverflow.com/comment/89050657
has comment: http://stackoverflow.com/comment/89063283
has comment: http://stackoverflow.com/comment/89051883
has body: I am writing a python3 app, that I would like to run on different computers. The main obstacle I found, is the fact that Windows and OSX does use some API differently, but I can find out on which OS I am running, and handle these cases. Although one issue came up, as being problematic; which is the fact that to use my app, I need to install on every machine I want it to run, all the dependency packages. Manual install may work, but I would like to achieve a more self-contained approach. I did look into pyinstall, but it didn't work in my case, since I get missing dependency when I run the application (especially if I use PyQt5 for the UI). Then I discover pipenv; which from my understanding, create a virtualenv and install the required dependency, by just passing the 2 files created when I create my project and integrate it with pipenv; although it is not "self-contained from my understanding. Also virtualenv still has to be installed on the machine, or pipenv won't work. What is the common python way to generate something that is distributed to other machines, while minimizing and self-containing everything to the max? Thanks
upvote count: 1
tagged with: python
has title: virtualenv and self contained apps in Python
favorite count: 0
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89055267
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89063163
has comment: http://stackoverflow.com/comment/89050503
score: 1
type: Question
linked to: http://stackoverflow.com/q/41570359

deployment
tags question: http://stackoverflow.com/q/51143378
tag name: deployment
tags question: http://stackoverflow.com/q/51106329
tags question: http://stackoverflow.com/q/51054559
type: Tag
tags question: http://stackoverflow.com/q/51154452

http://stackoverflow.com/a/51165554
answers question: http://stackoverflow.com/q/51165504
score: 2
has comment: http://stackoverflow.com/comment/89314443
downvote count: 0
has body: I guess it is something related to new and old style classes in Python2: Old-style classes don't actually have a __new__ method because for them __init__ is the constructor, so basically if we would have: class A: def __new__(cls): print "A.__new__ is called" # -&gt; this is never called A() the body of __new__ will never be executed in this case because it is not the purpose for old-style classes. In Python3, the behavior is the same, doesn't matter if you explicitly inherit from the object or not: class Person1: def __new__(cls, *args, **kwargs): print("called") return super(Person1, cls).__new__(cls, *args, **kwargs) class Person2(object): def __new__(cls, *args, **kwargs): print("called") return super(Person2, cls).__new__(cls, *args, **kwargs) p1 = Person1() p2 = Person2() These should print "called" twice when invoked from 3.x.
has comment: http://stackoverflow.com/comment/89322782
has comment: http://stackoverflow.com/comment/89314409
type: Answer
upvote count: 2

http://stackoverflow.com/q/51075519
score: -4
type: Question
tagged with: combinations
has body: I am trying to generate 20! permutations and do some Logical operations on it. I switched to multiprocessing and as I increase the number of processes preportional to the number of cores the performance increases . I have managed a time of 25sec for 10! calculations on a 32 core system. My final task is to do 20! in less than 2 hrs, I am thinking of GPU programming. Give suggestions for the approach I should follow
tagged with: performance
answer count: 2
downvote count: 4
upvote count: 0
tagged with: permutation
favorite count: 0
tagged with: factorial
has answer: http://stackoverflow.com/a/51075833
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89140273
has title: Calculating permutations taking too much time
has comment: http://stackoverflow.com/comment/89140071
has answer: http://stackoverflow.com/a/51077236
has comment: http://stackoverflow.com/comment/89140175

http://stackoverflow.com/comment/97955576
type: Comment
has text: I tried setting the batch normalization layers to trainable without success as explained in [the update section of my question](https://stackoverflow.com/questions/55569181/why-is-accuracy-from-fit-generator-different-to-that-from-evaluate-generator-in). Did I do something wrong? Also could you provide en example for your second suggestion? (_2. Split the model in two parts_)
comment on: http://stackoverflow.com/a/51124511
type: AnswerComment
score: 0

http://stackoverflow.com/a/51070076
has body: The issue is your usage of resp.status.code. When using the Python requests module, you should use resp.status_code instead. It gets a dictionary as the response, and looks for status instead of status_code. Examining your code now after the response to my answer and it seems you are looking for a status_code on json.loads. Please try: req.status_code instead as that way you are looking for status_code on the actual request.
has comment: http://stackoverflow.com/comment/89130111
downvote count: 1
has comment: http://stackoverflow.com/comment/89130599
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/89130054
type: Answer
has comment: http://stackoverflow.com/comment/89130219
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51070029
answers question: http://stackoverflow.com/q/51070029

http://stackoverflow.com/a/51155460
type: Answer
has comment: http://stackoverflow.com/comment/89298490
has comment: http://stackoverflow.com/comment/89299486
answers question: http://stackoverflow.com/q/51148893
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89303254
has comment: http://stackoverflow.com/comment/89303364
downvote count: 0
has body: There is no issue with django you will have to create proper Django Model Form validation so that the empty string isn't ignored and it will raise an error for the blank field.

http://stackoverflow.com/a/51232738
has body: I also noticed some similar behaviors of this in Jupyter Notebook. I am using Python class to wrap all of these up, but this still cannot keep it 'clean'. As I observe, after the event file was created, as long as I do not delete it, this file still keeps being updated. After I delete it, no new event file is created. Up to now, I have three solutions: 1. restart Jupyter session, which is a bit of inconvenient. 2. keep using different directories. 3. keep the event file (which depends on your situation)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51033886
type: Answer
answers question: http://stackoverflow.com/q/51033886
score: 1

http://stackoverflow.com/q/51155045
tagged with: setuptools
has comment: http://stackoverflow.com/comment/89293773
tagged with: cython
score: 0
has comment: http://stackoverflow.com/comment/89295628
tagged with: pyinstaller
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: There is a MaxRecursionError when I try to convert a package to a encrypted binary file. But I package the source code to a binary without encryption, the result is successful. It's the content of my directory: directory/ run.py # as an entry to import package setup.py # import setuptools and cython my_pkg/ __init__.py module1.py module2.py ... It's the content of run.py, it just runs simple actions. import my_pkg app = my_pkg.module1.Module1() print(id(app)) To do that, firstly I use setuptools to convert the .py files into .so files, and the output is an .egg file $ python setup.py bdist_egg Then I package the .egg file and run.py to a binary file using pyinstaller $ pyinstaller run.py --onefile During the process, it occurred RecursionError: maximum recursion depth exceeded in comparison...
has title: There is a MaxRecursionError during the execution of pyinstaller
type: Question

http://stackoverflow.com/q/51037998
answer count: 1
downvote count: 1
tagged with: chaining
favorite count: 0
has title: python chaining modules execution
tagged with: python
has comment: http://stackoverflow.com/comment/89068737
tagged with: module
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/1060796
has answer: http://stackoverflow.com/a/51039862
accepted answer: http://stackoverflow.com/a/51039862
has body: I do have the situation as follows: main.py moduleA.py moduleB.py moduleA contains main() function moduleB contains main() function I do in main: import moduleA, moduleB def main(): moduleA.main() moduleB.main() if __name__ == '__main__': main() I wonder if I can chain modules execution: import moduleA, moduleB def main(): moduleA().moduleB() if __name__ == '__main__': main() is it achievable? I know the code above will not work because the modul is not callable.
type: Question
score: -1
has comment: http://stackoverflow.com/comment/89068139
has comment: http://stackoverflow.com/comment/89068379

http://stackoverflow.com/a/51134758
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89253821
has comment: http://stackoverflow.com/comment/89253708
has comment: http://stackoverflow.com/comment/89254347
upvote count: 1
answers question: http://stackoverflow.com/q/51134379
has comment: http://stackoverflow.com/comment/89253946
has comment: http://stackoverflow.com/comment/89253761
score: 0
has body: import tkinter as tk def f(): def save(): a = t.get() with open((a + '.txt'), 'w') as f: f.write(a) top = tk.Tk() t = tk.StringVar(top) tk.Entry(top, textvariable=t).pack() tk.Button(top, text = 'Save as a file', command=save).pack() root = tk.Tk() tk.Button(root, text="Button", command=f).pack() root.mainloop() The most important change is t = tk.StringVar() -> t = tk.StringVar(top), specifying the master widget. There are a few other changes (e.g. pack() returns None so don't set values based on it, use a context manager for your file closing)

http://stackoverflow.com/a/51014080
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51011601
has body: If p is small, you can save a lot of time by using numpy.random.geometric to provide a sample of distances between elements being altered. A simple pass over the array ary: from numpy.random import geometric index = -1 while True: index += geometric(0.01) if index &gt;= len(ary): break ary[ind] = # compute new value Numpy distribution functions can produce an array of return values, so as long as p is small, it's probably even faster to produce all the step values at once: from numpy import cumsum from numpy.random import geometric for index in cumsum(geometric(p, size=int(len(ary) * p * 1.1))): if index &lt; len(ary): ary[index] = # compute new value The 1.1 is a fudge factor to make sure enough samples are selected from the geometric distribution. For large arrays it should be fine, but it is not guaranteed. A better (albeit more complicated) solution would be to generate the samples in chunks of, say, 10000 and keep doing that until you manage to get to the end of the array.

http://stackoverflow.com/a/51147515
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51146967
has comment: http://stackoverflow.com/comment/89311532
answers question: http://stackoverflow.com/q/51146967
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89305532
has body: Here is a version using a single Counter, avoiding the use of another set as in @RoadRunner's solution by popping keys from the Counter as we pass them. This may be slightly slower than the OrderedDict solution if there are many duplicates, but will use less memory: from collections import Counter words = ["paper", "Plastic", "aluminum", "PAPer", "TIN", " paper", "glass", "tin", "PAPER", "Polypropylene Plastic"] counter = Counter(w.lower() for w in words) result = [] for word in words: key = word.lower() if key in counter: count = counter[key] if count == 1: result.append(word) else: result.append('{} ({})'.format(word, count)) counter.pop(key) Note You should use casefold instead of lower for Python >= 3.3
type: Answer

http://stackoverflow.com/comment/89162291
type: AnswerComment
has text: it'll be better to leave original behavior unchanged or at least add comment why you think returning `iterator` instead of a `list` is a better idea (also name `my_classes` is misleading, it should be `my_instances` or something like that)
score: 0
comment on: http://stackoverflow.com/a/51085746
type: Comment

pandas-groupby
tags question: http://stackoverflow.com/q/51132161
tags question: http://stackoverflow.com/q/51036566
tags question: http://stackoverflow.com/q/51015217
tags question: http://stackoverflow.com/q/51016188
tags question: http://stackoverflow.com/q/51016638
tags question: http://stackoverflow.com/q/51066152
tags question: http://stackoverflow.com/q/51077070
tags question: http://stackoverflow.com/q/51095006
tags question: http://stackoverflow.com/q/51109036
tags question: http://stackoverflow.com/q/51092842
tags question: http://stackoverflow.com/q/51046122
tags question: http://stackoverflow.com/q/51016265
tags question: http://stackoverflow.com/q/51087484
tags question: http://stackoverflow.com/q/51059862
tags question: http://stackoverflow.com/q/51109245
tags question: http://stackoverflow.com/q/51108261
tags question: http://stackoverflow.com/q/51165370
tags question: http://stackoverflow.com/q/51124296
tags question: http://stackoverflow.com/q/51026581
tags question: http://stackoverflow.com/q/51036438
tags question: http://stackoverflow.com/q/51087155
tags question: http://stackoverflow.com/q/51085184
tags question: http://stackoverflow.com/q/51163975
tags question: http://stackoverflow.com/q/51049326
tags question: http://stackoverflow.com/q/51091331
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/51090462
tags question: http://stackoverflow.com/q/51150011
tags question: http://stackoverflow.com/q/51105216
tags question: http://stackoverflow.com/q/51018739
type: Tag
tags question: http://stackoverflow.com/q/51074911
tags question: http://stackoverflow.com/q/51119567
tags question: http://stackoverflow.com/q/51053911
tags question: http://stackoverflow.com/q/51073813
tags question: http://stackoverflow.com/q/51162124
tags question: http://stackoverflow.com/q/51138165
tags question: http://stackoverflow.com/q/51150494
tags question: http://stackoverflow.com/q/51155624
tags question: http://stackoverflow.com/q/51163527
tags question: http://stackoverflow.com/q/51057324
tags question: http://stackoverflow.com/q/51047491
tags question: http://stackoverflow.com/q/51130278
tags question: http://stackoverflow.com/q/51094437
tags question: http://stackoverflow.com/q/51140916
tags question: http://stackoverflow.com/q/51052416
tags question: http://stackoverflow.com/q/51079543
tags question: http://stackoverflow.com/q/51159993
tags question: http://stackoverflow.com/q/51025252
tags question: http://stackoverflow.com/q/51057822
tags question: http://stackoverflow.com/q/51070127
tags question: http://stackoverflow.com/q/51023435
tags question: http://stackoverflow.com/q/51039541

http://stackoverflow.com/q/51025893
has answer: http://stackoverflow.com/a/78179114
tagged with: flask
has answer: http://stackoverflow.com/a/78425753
has answer: http://stackoverflow.com/a/68078296
has body: I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app: from flask import Flask app = Flask(__name__) @app.route('/') def index(): return ' Hello! ' if __name__ == "__main__": app.run(debug=True) And I get this message: WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead * Restarting with stat * Debugger is active! * Debugger PIN: 123-456-789 * Running on http://127.0.0.1:5000/ Why am I getting this error when I run Flask? A previous version of the message read "Do not use the development server in a production environment."
has answer: http://stackoverflow.com/a/51026060
favorite count: 0
has comment: http://stackoverflow.com/comment/138264116
accepted answer: http://stackoverflow.com/a/51026060
has answer: http://stackoverflow.com/a/78382063
answer count: 10
tagged with: python
upvote count: 240
possible better answer: http://stackoverflow.com/a/54381386
has answer: http://stackoverflow.com/a/78079192
has title: Flask at first run: Do not use the development server in a production environment
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54381386
score: 239
downvote count: 1
has answer: http://stackoverflow.com/a/65676528
has answer: http://stackoverflow.com/a/74061823
type: Question
has answer: http://stackoverflow.com/a/62180253

http://stackoverflow.com/comment/89192820
score: 0
comment on: http://stackoverflow.com/q/51099500
type: Comment
type: QuestionComment
has text: Hey @MaxU , I'm working on a confidential project, so I can't share It here. My email Id is nsvikas1998@gmail.com . Could you please mail me? I saw from your profile you have very good experience in Machine Learning. I really need your help.!

http://stackoverflow.com/q/51098984
tagged with: ftplib
tagged with: python
accepted answer: http://stackoverflow.com/a/51102129
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51102129
type: Question
score: 5
has body: My application needs to download all the directories from a remote FTP, I'm testing for the first time the Python's ftplib. When I try to list all the directories in the remote FTP with the command ftp.nlst() it return an empty list. I know for sure that the directory is not empty because this command: ftp.retrlines('list') returned an object displaying the names of the subfolders inside the directory. While I was testing I tried other commands like ftp.cwd('/other-dir/') or ftp.pwd(), but none of these seems to work. This is the code that I'm using to display the list of subdirectories: from ftplib import FTP def ftpConnection(): ftp = FTP('ftp-address') ftp.login('user', 'password') lista = ftp.nlst() return (lista) print(ftpConnection()) Output: [] As you can see the list is empty. This is my code for retrlines: def ftpConnection(): ftp = FTP('remoteFtp') ftp.login('user', 'password') ftp.retrlines('LIST') print (ftpConnection()) Output: drw-rw-rwx 1 512 Jun 29 09:23 . drw-rw-rwx 1 512 Jun 28 05:11 103367 drw-rw-rwx 1 512 Jun 29 02:01 121901 drw-rw-rwx 1 512 Sep 23 2016 123233 drw-rw-rwx 1 512 Jun 29 09:19 125183 drw-rw-rwx 1 512 Jun 29 02:34 133028 This is the output from command-line ftp: 230-Welcome clt_kantar_italy from remoteFtp. You are now logged in to the server. 230 User logged in, proceed. ftp&gt; dir 200 PORT command successful. 150 File status okay; about to open data connection. drw-rw-rwx 1 512 Jun 29 09:23 . drw-rw-rwx 1 512 Jun 28 05:11 103367 drw-rw-rwx 1 512 Jun 29 02:01 121901 drw-rw-rwx 1 512 Sep 23 2016 123233 drw-rw-rwx 1 512 Jun 29 09:19 125183 drw-rw-rwx 1 512 Jun 29 02:34 133028 226 Closing data connection. Transferred 481 bytes. ftp: 484 bytes received in 0.01secondi 37.23Kbyte/sec) ftp&gt; ls 200 PORT command successful. 150 File status okay; about to open data connection. 226 Closing data connection. Transferred 0 bytes.
has title: Python ftp.nlst() return empty list when where are (sub)directories on the server
answer count: 1
favorite count: 0
tagged with: ftp
tagged with: python-3.x
upvote count: 5

scipy
tags question: http://stackoverflow.com/q/51121265
tags question: http://stackoverflow.com/q/51109429
tags question: http://stackoverflow.com/q/51131742
tags question: http://stackoverflow.com/q/51156581
tags question: http://stackoverflow.com/q/51090121
tags question: http://stackoverflow.com/q/51051606
tags question: http://stackoverflow.com/q/51085455
tags question: http://stackoverflow.com/q/51024649
type: Tag
tags question: http://stackoverflow.com/q/51134939
tags question: http://stackoverflow.com/q/51040853
tags question: http://stackoverflow.com/q/51106679
tag name: scipy
tags question: http://stackoverflow.com/q/51107780
tags question: http://stackoverflow.com/q/51042870
tags question: http://stackoverflow.com/q/51086961
tags question: http://stackoverflow.com/q/51076695
tags question: http://stackoverflow.com/q/51153668
tags question: http://stackoverflow.com/q/51118114
tags question: http://stackoverflow.com/q/51132467
tags question: http://stackoverflow.com/q/51079048
tags question: http://stackoverflow.com/q/51093801
tags question: http://stackoverflow.com/q/51044251
tags question: http://stackoverflow.com/q/51058205
tags question: http://stackoverflow.com/q/51110925
tags question: http://stackoverflow.com/q/51144253
tags question: http://stackoverflow.com/q/51126008
tags question: http://stackoverflow.com/q/51125969
tags question: http://stackoverflow.com/q/51096373
tags question: http://stackoverflow.com/q/51022380
tags question: http://stackoverflow.com/q/51078471
tags question: http://stackoverflow.com/q/51095585
tags question: http://stackoverflow.com/q/51106981
tags question: http://stackoverflow.com/q/51050622
tags question: http://stackoverflow.com/q/51132161
tags question: http://stackoverflow.com/q/51051777
tags question: http://stackoverflow.com/q/51034985
tags question: http://stackoverflow.com/q/51127257
tags question: http://stackoverflow.com/q/51059863
tags question: http://stackoverflow.com/q/51110277
tags question: http://stackoverflow.com/q/51070397
tags question: http://stackoverflow.com/q/51077293
tags question: http://stackoverflow.com/q/51149887
tags question: http://stackoverflow.com/q/51127470
tags question: http://stackoverflow.com/q/51105965

inheritance
tags question: http://stackoverflow.com/q/51093387
tags question: http://stackoverflow.com/q/51080326
tags question: http://stackoverflow.com/q/51143602
tag name: inheritance
tags question: http://stackoverflow.com/q/51164663
type: Tag
tags question: http://stackoverflow.com/q/51146341
tags question: http://stackoverflow.com/q/51043969
tags question: http://stackoverflow.com/q/51031235
tags question: http://stackoverflow.com/q/51108063
tags question: http://stackoverflow.com/q/51084582
tags question: http://stackoverflow.com/q/51161935
tags question: http://stackoverflow.com/q/51038351

http://stackoverflow.com/a/51019878
downvote count: 0
type: Answer
upvote count: 9
has body: I think there is problem your csv have no header, so is possible create default range columns names: df_degree = pd.read_csv(file, header=None) Or is possible define custom columns names: df_degree = pd.read_csv(file, names=['col1','col2'])
answers question: http://stackoverflow.com/q/51019813
score: 9

http://stackoverflow.com/comment/89193117
score: 0
has text: I doesn't have any idea about this. Because I put whole code in question. Why browser redirect second time?How to stop this from redirect second time?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51102135

http://stackoverflow.com/a/51053035
score: 1
upvote count: 1
has body: I think there is a better solution to your problem and that you shouldnt need exceptions etc as real errors/exceptions arent occurring. First: Create more modularity. I personally prefer to make a lot of functions that make sense. Ill do a quick conversion for ya. def main(): data = get_data() if data['num_results'] &gt; 1000: cont = input("Warning Over 1000 results, Continue?") if cont == 'y': results = process_data(data) if results is not None: #do things. def get_data(): r = request.get('someRestAPI') return r.json() def process_data(data): results = [] endpoint = data['next_page'] while endpoint: # request the next page r = request.get(endpoint ) data = r.json() results.append(data['result']) endpoint = data['next_page'] return results if __name__ == "__main__": main() Now this doesnt answer the question, but reorganizes your code as to allow it to be more smooth and no exceptions are needed.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51052921

http://stackoverflow.com/a/51022214
accepted answer of: http://stackoverflow.com/q/51021537
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51021537
has body: Don’t specify the field names. Pull out the ones you want from the full records: with open(csvfile, "r", encoding="utf-8") as infile: reader = csv.DictReader(infile) with open(jsonfile, "w", encoding="utf-8") as outfile: outfile.write(json.dumps([{"ID": row["ID"], "summary": row["summary"]} for row in reader], indent=2)) Gives: [ { "ID": "3", "summary": "Take it with a grain of salt" }, { "ID": "19", "summary": "Incredible growth opportunity with downsides" } ]

http://stackoverflow.com/comment/89313735
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51165164
has text: @juanpa.arrivillaga I was expecting `yton`, not `ython`. I deliberately didn't shift the indices and instead replaced them with spaces. For clarification, I'm doing the snakify.org exercises, and there are limitations, based on lesson, as to what functions and language features can be used at certain stages.
score: 0

http://stackoverflow.com/q/51122371
score: 5
has answer: http://stackoverflow.com/a/51122659
upvote count: 5
tagged with: docker
has answer: http://stackoverflow.com/a/56055885
answer count: 3
has title: Docker mongodb connection refused on mac os when loading http://0.0.0.0:27017
downvote count: 0
tagged with: macos
favorite count: 0
accepted answer: http://stackoverflow.com/a/51122659
has body: Browser Screenshot I have 2 docker containers running mongo:3.0.3 and python:2.7. And I have an app.py which connects to mongodb instance. In my app.py I have used port 5000 to map 27017. The app.py runs fine but when I visit http://0.0.0.0:5000 this connection refused error comes on terminal. 172.17.0.1 - - [01/Jul/2018 10:01:32] "GET / HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/pythonApp/app.py", line 16, in form if posts.count()!=0: File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 1023, in count return self._count(cmd) File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 985, in _count with self._socket_for_reads() as (sock_info, slave_ok): File "/usr/local/lib/python2.7/contextlib.py", line 17, in __enter__ return self.gen.next() File "/usr/local/lib/python2.7/site-packages/pymongo/mongo_client.py", line 699, in _socket_for_reads with self._get_socket(read_preference) as s…
tagged with: docker-for-mac
tagged with: python
possible better answer: http://stackoverflow.com/a/55977014
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55977014
has comment: http://stackoverflow.com/comment/89229860
type: Question
tagged with: mongodb

http://stackoverflow.com/a/51081616
has body: Check your first row in your .sav file If you want to read data as a dataframe into Pandas. The file has the following format a b c d 0 1 2 3 4 5 1 2 3 4 5 6 When you read it with Pandas you get the following dataframe a b c d 0 1 2 3 4 5 1 2 3 4 5 6 When I execute print df.columns I get something like : Index([u'a', u'b', u'c', u'd'], dtype='object') And when I execute print df.iloc[0] I get : a 2 b 3 c 4 d 5 Name: (0, 1) I guess you would like to have some dataframe like this a b c d col1 col2 0 1 2 3 4 5 1 2 3 4 5 6 Possible Solution is: One way to do this would be to read in the data twice. Once with the first row (the original columns) skipped and the second with only the column names read (and all the rows skipped) df = pd.read_csv(header=None, skiprows=1) columns = pd.read_csv(nrows=0).columns.tolist() columns Output ['a', 'b', 'c', 'd'] Now find number of missing columns and use a list comprehension to make new columns num_missing_cols = len(df.columns) - len(columns) new_cols = ['col' + str(i+1) for i in range(num_missing_cols)] df.columns = columns + new_cols df a b c d col1 col2 0 0 1 2 3 4 5 1 1 2 3 4 5 6
accepted answer of: http://stackoverflow.com/q/51081322
answers question: http://stackoverflow.com/q/51081322
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51053004
score: 0
possible better answer: http://stackoverflow.com/a/51053125
tagged with: pandas
favorite count: 0
has title: python pandas DataFrame cannot get the first column data
has body: I am using Pandas to do data processing, and I encounter a problem, it cannot get the first column data, but can get other columns data, why? how can I solve this problem, could anyone help? I just imported the data of the excel file, and wanted to get the Name data (first column)by data['Name'] Errors are shown as below KeyError Traceback (most recent call last) /Users/test/anaconda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2392 try: -&gt; 2393 return self._engine.get_loc(key) 2394 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5239)() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5085)() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20405)() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20359)() KeyError: 'Name' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-67-47e6fa66308a&gt; in &lt;module&gt;() ----&gt; 1 school_names = processing['Name'] /Users/test/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key) 2060 return self._getitem_multilevel(key) 2061 else: -&gt; 2062 return self._getitem_column(key) 2063 2064 def _getitem_column(self, key): /Users/test/anaconda/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_column(self, key) 2067 # get column 2068 if self.columns.is_unique: -&gt; 2069 return self._get_item_cache(key) 2070 2071 # duplicate columns &amp; possible reduce dimensionality /Users/test/anaconda/lib/python3.6/site-packages/pandas/core/generic.py in _get_item_cache(self, item) 1532 res = cache.get(item) 1533 if res is None: -&gt; 1534 values = self._data.get(item) 1535 res = self._box_item_values(item, values) 1536 cache[item] = res /User…
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51053094
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89097063
has answer: http://stackoverflow.com/a/51053125
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51053094

http://stackoverflow.com/q/51085516
score: 1
has comment: http://stackoverflow.com/comment/89164792
has comment: http://stackoverflow.com/comment/89162558
type: Question
linked to: http://stackoverflow.com/q/25981703
tagged with: ssl
upvote count: 1
has comment: http://stackoverflow.com/comment/89163414
has comment: http://stackoverflow.com/comment/89162890
favorite count: 0
has comment: http://stackoverflow.com/comment/89407430
tagged with: python-3.x
has body: Running Spyder under the Anaconda package 3.8 with python 3.6. Ever since April I have been receiving an error trying to install packages using pip with the error: Could not fetch URL https://pypi.python.org/simple/scrapy/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443) Does anyone have any way I can rectify this issue. This doesn't happen at my home PC. Thanks
type: UnansweredQuestion
tagged with: pip
tagged with: python
has title: SSL Certificate Failure
has comment: http://stackoverflow.com/comment/89163497
answer count: 0
downvote count: 0

http://stackoverflow.com/q/51127344
tagged with: python
has answer: http://stackoverflow.com/a/54862854
has answer: http://stackoverflow.com/a/54783311
downvote count: 0
has answer: http://stackoverflow.com/a/52023152
tagged with: tensorflow
upvote count: 28
type: Question
has comment: http://stackoverflow.com/comment/96857079
has body: Im deploying a keras model and sending the test data to the model via a flask api. I have two files: First: My Flask App: # Let's startup the Flask application app = Flask(__name__) # Model reload from jSON: print('Load model...') json_file = open('models/model_temp.json', 'r') loaded_model_json = json_file.read() json_file.close() keras_model_loaded = model_from_json(loaded_model_json) print('Model loaded...') # Weights reloaded from .h5 inside the model print('Load weights...') keras_model_loaded.load_weights("models/Model_temp.h5") print('Weights loaded...') # URL that we'll use to make predictions using get and post @app.route('/predict',methods=['GET','POST']) def predict(): data = request.get_json(force=True) predict_request = [data["month"],data["day"],data["hour"]] predict_request = np.array(predict_request) predict_request = predict_request.reshape(1,-1) y_hat = keras_model_loaded.predict(predict_request, batch_size=1, verbose=1) return jsonify({'prediction': str(y_hat)}) if __name__ == "__main__": # Choose the port port = int(os.environ.get('PORT', 9000)) # Run locally app.run(host='127.0.0.1', port=port) Second: The file Im using to send the json data sending to the api endpoint: response = rq.get('api url has been removed') data=response.json() currentDT = datetime.datetime.now() Month = currentDT.month Day = currentDT.day Hour = currentDT.hour url= "http://127.0.0.1:9000/predict" post_data = json.dumps({'month': month, 'day': day, 'hour': hour,}) r = rq.post(url,post_data) Im getting this response from Flask regarding Tensorflow: ValueError: Tensor Tensor("dense_6/BiasAdd:0", shape=(?, 1), dtype=float32) is not an element of this graph. My keras model is a simple 6 dense layer model and trains with no errors. Any ideas?
tagged with: flask
has title: Tensor is not an element of this graph; deploying Keras model
has comment: http://stackoverflow.com/comment/89240856
has answer: http://stackoverflow.com/a/61365815
answer count: 7
tagged with: keras
has answer: http://stackoverflow.com/a/56786144
score: 28
favorite count: 0
has answer: http://stackoverflow.com/a/53829131
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66015574

http://stackoverflow.com/comment/89070019
score: 0
has text: I meant to say that if you put this instead of the table it would be easier: `dictionary = {'SKU': {0: '2010', 1: '2010'}, 'Date': {0: '2017-01-01 0:00:00', 1: '2017-02-01 0:00:00'}, 'Inventory': {0: '85', 1: '382'}, 'Sales': {0: '126', 1: '143'}, 'Incoming': {0: '252', 1: '252'}}` and then one can just copy paste that dictionary and run `df = pd.DataFrame(dictionary)`. I meant that this would be easier to copy and reproduce. It's a small detail I guess
type: QuestionComment
comment on: http://stackoverflow.com/q/51038212
type: Comment

http://stackoverflow.com/comment/89270714
comment on: http://stackoverflow.com/a/51109446
type: Comment
has text: Also, if you were subtracting location a from b, would it be better to do before or after the above work? And what if you want to specify which location to subtract from which?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/120730208
comment on: http://stackoverflow.com/q/51062015
has text: How jumbled can the key be? For example, would the statement "Motice Devor 110" be accepted? Or should "Motor" and "101" maintain full integrity?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89212688
score: 0
has text: if you already use numpy, maybe you should open your wave files with scipy.io.wavfile. it's faster and bullet-proof
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51110764

http://stackoverflow.com/q/51032555
tagged with: mqtt
tagged with: python
type: AnsweredQuestion
has body: I'm pretty new to all of this, so it's possible I'm missing something obvious. I've searched all over, but I'm not seeing what I've gotten wrong. I'm trying to use Python to connect to a Mosquitto broker I have running on a Raspberry Pi 3. I have the broker running and tested with the Mosquitto-Client tool. When I try to run my Python script I get the following error: File "mqtt_sub.py", line 20 client = mqtt.Client() SyntaxError: invalid syntax Here is my mqtt_sub.py script: import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() - if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("Kastor/#") #client.subscribe("&lt;MainTopic/SubTopic&gt;") # Add additional subscriptions here. # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) if msg.topic == "Kastor/event/PrintDone": print(msg.payload["name"] + " has finsihed printing in " + int(msg.payload["time"] + "seconds.") # Create an MQTT client and attach our routines to it. client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(”myUsername”, ”myPassword”) client.connect("localhost", 1883, 60) client.loop_forever() I have Python 2.7.9 installed on the Pi where the script is being ran. If there is any additional info I can provide to help troubleshoot please let me know.
has title: SyntaxError when using client = mqtt.Client() in Python Paho-MQTT
type: Question
has answer: http://stackoverflow.com/a/51032581
tagged with: paho
score: 0
accepted answer: http://stackoverflow.com/a/51032581
answer count: 1

http://stackoverflow.com/a/62299655
upvote count: 4
answers question: http://stackoverflow.com/q/51072938
has comment: http://stackoverflow.com/comment/124288656
downvote count: 0
score: 4
has body: If you want to split a dataframe by all available years you can do this by finding the unique years in your dataframe, then loop through these unique years and then use boolean indexing for filtering out in a loop each single year. So this idea could be implemented in a function like: def split_years(dt): dt['year'] = dt['Date'].dt.year return [dt[dt['year'] == y] for y in dt['year'].unique()] The result of the function above will be a list of dataframes, each with a single year.
type: Answer

http://stackoverflow.com/comment/89283410
has text: Yes, the crash happens at reassignment of `self.vbox` and `self.session` so I enclosed the whole reassignment code in try-except with `traceback` in the except block.
score: 0
comment on: http://stackoverflow.com/q/51136288
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89100266
type: QuestionComment
comment on: http://stackoverflow.com/q/51052735
has text: @Andersson i'm not looking for a particular type of output, so to speak. i'm looking for a way to select an element, and then select children elements relative to the element which was selected initially, if that makes sense? i can def include some HTML, give me a moment tho
score: 0
type: Comment

http://stackoverflow.com/q/51045309
has comment: http://stackoverflow.com/comment/89082085
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has title: How to join a large number of data frames
score: -1
has answer: http://stackoverflow.com/a/51045482
type: Question
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89087792
has body: I have 35 table (stocks) in the same format which has 2 columns: ["Trading_date","volume"].How can I join ALL of them using Pandas python to have the joined table in this format: ["Trading_date","volume_1","volume_2",...,"volume_35"] and keep all but remove duplicate of "Trading_date". For example: table 1 has 5 rows, table 2 has 7 rows, two table share 4 rows on "Trading_date". The joined of two tables will have 8 rows, the missing values in row["volume"] will be assign 0 or null (prefer 0) Thank you very much for help.
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/51124943
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89305880
score: 0
has body: The file alien_invasion.py is the main file of the app. Why control mouse doesn't work? How make control keyboard to this example and control ship with left and right site? file in which is control mouse/keyboard file: game_functions.py import sys import pygame def check_events(ship): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.type == pygame.KEYUP : if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False settings for ship file: ship.py import pygame class Ship(): def __init__(self, ai_settings, screen): self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('images/ship.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom self.moving_right = False self.moving_left = False self.center = float(self.rect.centerx) def blitme(self): self.screen.blit(self.image, self.rect) def update(self): if self.moving_right and self.rect.right &lt; self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left &gt; 0: self.center -= self.ai_settings.ship_speed_factor self.rect.centerx = self.center the main file which run app file: alien_invasion.py import sys import pygame from settings import Settings from ship import Ship import game_functions as gf def run_game(): pygame.init() pygame.display.set_caption("Inwazja obcych") ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) ship = Ship(ai_settings, screen) gf.update_screen(ai_settings, screen, ship) gf.check_events(ship) ship.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(ai_setti…
has title: Why control keyboard doesn't work? Right and left mouse
has answer: http://stackoverflow.com/a/51137984
answer count: 1
tagged with: controls
tagged with: keyboard
accepted answer: http://stackoverflow.com/a/51137984
tagged with: python
tagged with: pygame
tagged with: mouse

http://stackoverflow.com/a/59284768
answers question: http://stackoverflow.com/q/51070985
has body: If there are multiple dataframe below is the function to calculate number of missing value in each column with percentage def miss_data(df): x = ['column_name','missing_data', 'missing_in_percentage'] missing_data = pd.DataFrame(columns=x) columns = df.columns for col in columns: icolumn_name = col imissing_data = df[col].isnull().sum() imissing_in_percentage = (df[col].isnull().sum()/df[col].shape[0])*100 missing_data.loc[len(missing_data)] = [icolumn_name, imissing_data, imissing_in_percentage] print(missing_data)
score: 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89138225
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51074201
has text: Thanks for the help. I have this `d = {'name': 'foo', 'age': 'bar'}` `a = Node("Person", **d)` `tx.merge(a)` This gives me error: ValueError: Primary label and primary key are required for MERGE operation

http://stackoverflow.com/a/51158232
has body: Using the SubnetworkLayer is one option. That would look like: trained_network_model_file = 'path/to/model_file' trained_network = { "conv_1" : {"class": "conv", "filter_size": (400,), "activation": "abs" , "padding": "valid", "strides": 10, "n_out": 64 }, "pad_conv_1_time_dim" : {"class": "pad", "axes": "time", "padding": 20, "from": ["conv_1"]}, "conv_2" : {"class": "conv", "input_add_feature_dim": True, "filter_size": (40, 64), "activation":"abs", "padding": "valid", "strides": 16, "n_out": 128, "from": ["pad_conv_1_time_dim"]}, "flatten_conv": {"class": "merge_dims", "axes": "except_time","n_out": 128, "from": ["conv_2"]} } network = { "conv_layers" : { "class" : "subnetwork", "subnetwork": trained_network, "load_on_init": trained_network_model_file, "n_out": 128}, "lstm1_fw" : { "class": "rec", "unit": "lstmp", "n_out" : rnnLayerNodes, "direction": 1, "from" : ['conv_layers'] }, "lstm1_bw" : { "class": "rec", "unit": "lstmp", "n_out" : rnnLayerNodes, "direction": -1, "from" : ['conv_layers'] }, "lin_1" : { "class" : "linear", "activation": None, "n_out": 512, "from" : ["lstm1_fw", "lstm1_bw"] }, "ff_2" : { "class" : "linear", "activation": "relu", "n_out": 2000, "from" : ["lin_1"] }, "ff_3" : { "class" : "linear", "activation": "relu", "n_out": 2000, "from" : ["ff_2"] }, "ff_4" : { "class" : "linear", "activation": "relu", "n_out": 2000, "from" : ["ff_3"] }, "output" : { "class" : "softmax", "loss" : "ce", "from" : ["ff_4"] } } I think this would be my preferred option in your case. Otherwise, there is the custom_param_importer option for every layer, and you might get it to work with that. Then, for many layers, you can define the initializer for the params, e.g. for ConvLayer, you can use forward_weights_init. There functions like load_txt_file_initializer could be used, or maybe a similar function should be added to load directly from a TF checkpoint file.
has comment: http://stackoverflow.com/comment/89305840
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89305912
score: 1
accepted answer of: http://stackoverflow.com/q/51157756
answers question: http://stackoverflow.com/q/51157756

http://stackoverflow.com/comment/89170288
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51090876
has text: @Moritz. Thanks for comment. I am also wondering what is wrong with this question!!!

http://stackoverflow.com/comment/89219060
comment on: http://stackoverflow.com/q/51116380
type: QuestionComment
type: Comment
has text: If the html you saved vs the html you get online is different you need to look at the html you get online and build your query off of that. First thing you should do is look at the full page.Maybe do print(soup.prettify()) as soon as you make the soup. Also, it's possible that javascript is creating or populating the price elements so they don't actually exist in the soup you get. If that's the case, you may not be able to get them this way. I ran into complicated javascript and ended up having to look at the selenium project (controlling a real browser) as a way to webscrape.
score: 0

http://stackoverflow.com/q/51079806
has title: Login issue with ftplib but not with Paramiko?
has body: I am trying to connect with a host with ftplib but every time it says- File "E:\NTUC\virtualenv\lib\ftplib.py", line 152, in connect source_address=self.source_address) File "E:\NTUC\virtualenv\lib\socket.py", line 724, in create_connection raise err File "E:\NTUC\virtualenv\lib\socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it But with the same credentials if I use Paramiko, it connects me successfully. My ftplib code: import ftplib f = ftplib.FTP() f.connect("HOST") f.login("USER_NAME", "PASSWORD") ls = [] f.retrlines('MLSD', ls.append) for entry in ls: print(entry) My Paramiko code: import paramiko transport = paramiko.Transport((HOST, PORT)) transport.connect(username=USER_NAME, password=PASSWORD) sftp = paramiko.SFTPClient.from_transport(transport)
has answer: http://stackoverflow.com/a/51080801
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51080801
tagged with: paramiko
tagged with: sftp
answer count: 1
downvote count: 0
favorite count: 0
tagged with: ftp
tagged with: ftplib

http://stackoverflow.com/comment/89211997
comment on: http://stackoverflow.com/q/51112394
type: QuestionComment
type: Comment
has text: Just a heads up, checking whether rowsums equal 45 is not really sufficient. You'd also have to check column sums and 3x3 block sums, and whether the values in each were unique and in [1..9]).
score: 0

http://stackoverflow.com/q/51051894
answer count: 4
has comment: http://stackoverflow.com/comment/89094926
has comment: http://stackoverflow.com/comment/89095190
type: AnsweredQuestion
tagged with: syntax
score: 1
has comment: http://stackoverflow.com/comment/89094894
has comment: http://stackoverflow.com/comment/89094973
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51051934
has comment: http://stackoverflow.com/comment/89096460
has title: Functions in dictionaries in python
accepted answer: http://stackoverflow.com/a/51052890
has body: I can store functions in dictionaries by saying MyDict = {} def func(): print("Hello, world!") MyDict["func"] = func I was wondering if there was a cleaner/neater way to write this - something along the lines of MyDict = {} def MyDict["func"](): print("Hello, world!") However this code throws a syntax error
tagged with: function
has answer: http://stackoverflow.com/a/51052660
possible better answer: http://stackoverflow.com/a/51051934
has comment: http://stackoverflow.com/comment/89094921
has answer: http://stackoverflow.com/a/51052102
favorite count: 0
has comment: http://stackoverflow.com/comment/89097103
has answer: http://stackoverflow.com/a/51052890
downvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/51146455
upvote count: 0
score: -1
has body: You should be using a queue where last element links to the first element. To implement this update your class with self.previous then your queue would look like (added third for clarity): first = Song("Hello") second = Song("Eye of the tiger") third = Song("We are the champions") first.next_song(second) first.prev_song(third) second.next_song(third) second.prev_song(first) third.next_song(first) third.prev_song(second)
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/51146399

http://stackoverflow.com/q/51011470
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51011509
score: 0
tagged with: pandas
has body: I'd like to be able to make rows selection and masking and slicing in one command. Currently I use two steps. df Out[126]: A B C D 2018-06-24 -2.198394 0.224622 0.990230 0.390609 2018-06-25 0.644388 -1.196015 1.859241 0.444789 2018-06-26 0.708848 0.780761 1.599977 -0.489875 2018-06-27 -0.465428 -1.540811 -2.384975 0.460398 2018-06-28 -1.061571 1.781373 -1.934853 0.895916 2018-06-29 0.613139 0.446043 -0.061014 -1.182526 2018-06-30 -0.579179 0.630916 0.689561 0.124637 2018-07-01 0.199385 1.230230 -2.075407 1.051498 2018-07-02 0.377676 0.343647 1.226058 0.182071 2018-07-03 0.478328 -0.791613 -2.247531 -1.213415 df03 = df.iloc[0:3] df03.loc[(df.C &gt; 0) &amp; (df.B &gt; 0), 'A':'C'] Out[128]: A B C 2018-06-24 -2.198394 0.224622 0.990230 2018-06-26 0.708848 0.780761 1.599977
answer count: 1
has title: row selection and loc masking and slicing in one command
tagged with: python
has answer: http://stackoverflow.com/a/51011509

http://stackoverflow.com/comment/89243532
type: Comment
score: 0
has text: A very simple approach to detect cars in the night time would be to detect their headlights, as they seem to be a very prominent feature, You can apply various filters such as size of contour, distance between two contours to confirm the given contours are of head light itself.
comment on: http://stackoverflow.com/q/51129269
type: QuestionComment

http://stackoverflow.com/comment/89290528
has text: Actually i have to apply these substitutions to a column of csv file that contains a high number of rows . So i want to do this in one pass for a given row ... also the regex number is not 2 but more than 20 ... so i cant do it individually for each regex
comment on: http://stackoverflow.com/a/51152908
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51054842
possible better answer: http://stackoverflow.com/a/51054856
has answer: http://stackoverflow.com/a/51054856
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51054870
accepted answer: http://stackoverflow.com/a/51054870
favorite count: 0
has answer: http://stackoverflow.com/a/51055013
type: Question
has body: For a routine programming question, I took input from the user for a list using a raw input mode, as many times as a variable suggested. now i have a list of strings, in which each element of the list has a set of whitespace separated strings as shown: ['2 5 4', '3 7 8 9', '5 5 7 8 9 10'] Now, I want to convert the strings to a list of integers. In effect, I want the final list to look like this: [ [2,5,3] , [3,7,8,9] , [5,5,7,8,9,10] ] Also, to take the inputs from the used, I use this: print 'Enter the number of lists and mod value:' a, b = map(int, sys.stdin.readline().split()) lst = [] for i in range(a): v = [] v = raw_input() lst.append(v) print lst Is there a way to do this? I'm using Python 2.7 with PyCharm as editor. Any help would be appreciated.
has title: Converting a list of individually white-space separated strings into integers
score: 0
answer count: 3
upvote count: 1
downvote count: 1

sql
tags question: http://stackoverflow.com/q/51056672
tags question: http://stackoverflow.com/q/51162522
tags question: http://stackoverflow.com/q/51099833
tags question: http://stackoverflow.com/q/51030253
tags question: http://stackoverflow.com/q/51048963
tags question: http://stackoverflow.com/q/51035435
tags question: http://stackoverflow.com/q/51150898
tags question: http://stackoverflow.com/q/51097678
tags question: http://stackoverflow.com/q/51018493
tags question: http://stackoverflow.com/q/51039738
tags question: http://stackoverflow.com/q/51088340
tags question: http://stackoverflow.com/q/51047718
tags question: http://stackoverflow.com/q/51034507
tags question: http://stackoverflow.com/q/51017139
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/51164849
tags question: http://stackoverflow.com/q/51160638
tags question: http://stackoverflow.com/q/51088116
tags question: http://stackoverflow.com/q/51113494
tags question: http://stackoverflow.com/q/51044784
tags question: http://stackoverflow.com/q/51055000
tags question: http://stackoverflow.com/q/51058587
tags question: http://stackoverflow.com/q/51160512
tags question: http://stackoverflow.com/q/51070954
tags question: http://stackoverflow.com/q/51014492
tags question: http://stackoverflow.com/q/51015379
tags question: http://stackoverflow.com/q/51067226
tags question: http://stackoverflow.com/q/51102643
tags question: http://stackoverflow.com/q/51145380
tags question: http://stackoverflow.com/q/51024428
tags question: http://stackoverflow.com/q/51016095
tags question: http://stackoverflow.com/q/51142643
tags question: http://stackoverflow.com/q/51081315
tags question: http://stackoverflow.com/q/51069567
tags question: http://stackoverflow.com/q/51157380
tags question: http://stackoverflow.com/q/51063711

http://stackoverflow.com/a/51177187
has body: The problem lies with the fact that pyinstaller does not package setuptools entry points which are required by APScheduler to look up the trigger classes. The workaround is to import and use the triggers manually.
has comment: http://stackoverflow.com/comment/89780786
downvote count: 0
answers question: http://stackoverflow.com/q/51124464
has comment: http://stackoverflow.com/comment/89702133
type: Answer
has comment: http://stackoverflow.com/comment/89692706
upvote count: 6
has comment: http://stackoverflow.com/comment/89659745
has comment: http://stackoverflow.com/comment/89762180
score: 6

http://stackoverflow.com/a/61191878
downvote count: 0
has comment: http://stackoverflow.com/comment/111949948
score: 19
has comment: http://stackoverflow.com/comment/121082433
has comment: http://stackoverflow.com/comment/108757049
has body: An @property is typically used to store a seemingly public argument (e.g. name) into a private attribute (e.g. _name) through getters and setters, while dataclasses generate the __init__() method for you. The problem is that this generated __init__() method should interface through the public argument name, while internally setting the private attribute _name. This is not done automatically by dataclasses. In order to have the same interface (through name) for setting values and creation of the object, the following strategy can be used (Based on this blogpost, which also provides more explanation): from dataclasses import dataclass, field @dataclass class Test: name: str _name: str = field(init=False, repr=False) @property def name(self) -&gt; str: return self._name @name.setter def name(self, name: str) -&gt; None: self._name = name This can now be used as one would expect from a dataclass with a data member name: my_test = Test(name='foo') my_test.name = 'bar' my_test.name('foobar') print(my_test.name) The above implementation does the following things: The name class member will be used as the public interface, but it actually does not really store anything The _name class member stores the actual content. The assignment with field(init=False, repr=False) makes sure that the @dataclass decorator ignores it when constructing the __init__() and __repr__() methods. The getter/setter for name actually returns/sets the content of _name The initializer generated through the @dataclass will use the setter that we just defined. It will not initialize _name explicitly, because we told it not to do so.
upvote count: 19
type: Answer
answers question: http://stackoverflow.com/q/51079503

http://stackoverflow.com/comment/89131335
type: QuestionComment
comment on: http://stackoverflow.com/q/51070622
has text: Post what `pos3` is
score: 0
type: Comment

http://stackoverflow.com/comment/89362183
comment on: http://stackoverflow.com/q/51132230
score: 0
has text: try after updating your windows system, I had the same issue before, it was resolved after installing visual studio redistribution c++.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89225667
score: 0
type: AnswerComment
type: Comment
has text: @gi.rajan Yep, same idea as that question/solution. Glad I could help :-)
comment on: http://stackoverflow.com/a/51120063

http://stackoverflow.com/comment/89208561
score: 0
type: AnswerComment
has text: I see, yeah, selenium is a poor choice then. Well, assuming that the entire process isn't handled in browser via js , have you tried using using the (or some of the) original cookies in the second request, along with the changed headers? Otherwise every time you re-query, it's possible that they send a new timing/user cookie, so all your requests appear to be from a new user/connection, regardless of how long you have been looping.
type: Comment
comment on: http://stackoverflow.com/a/51110680

http://stackoverflow.com/a/51411490
answers question: http://stackoverflow.com/q/51086846
accepted answer of: http://stackoverflow.com/q/51086846
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: There are a lot of ways you could get a different error message, but they all have weird caveats and side effects. Replacing the module's __class__ with a types.ModuleType subclass is probably the cleanest option, but it only works on Python 3.5+. Besides the 3.5+ limitation, the primary weird side effects I've thought of for this option are that the module will be reported callable by the callable function, and that reloading the module will replace its class again unless you're careful to avoid such double-replacement. Replacing the module object with a different object works on pre-3.5 Python versions, but it's very tricky to get completely right. Submodules, reloading, global variables, any module functionality besides the custom error message... all of those are likely to break if you miss some subtle aspect of the implementation. Also, the module will be reported callable by callable, just like with the __class__ replacement. Trying to modify the exception message after the exception is raised, for example in sys.excepthook, is possible, but there isn't a good way to tell that any particular TypeError came from trying to call your module as a function. Probably the best you could do would be to check for a TypeError with a 'module' object is not callable message in a namespace where it looks plausible that your module would have been called - for example, if the Bar name is bound to the Foo.Bar module in either the frame's locals or globals - but that's still going to have plenty of false negatives and false positives. Also, sys.excepthook replacement isn't compatible with IPython, and whatever mechanism you use would probably conflict with something. Right now, the problems you have are easy to understand and easy to explain. The problems you would have with any attempt to change the error message are likely to be much harder to understand and harder to explain. It's probably not a worthwhile tradeoff.

http://stackoverflow.com/comment/89136887
comment on: http://stackoverflow.com/q/51064784
type: Comment
type: QuestionComment
score: 0
has text: @Michael I already tried that... when I entered a wrong password, it goes to the eerror handler but when I enter the correct ones, instead of navigating to the page I specified in the success handler, it alerts 'undefined' but in the console, it returns a status code of 200

http://stackoverflow.com/a/51174043
upvote count: 1
has comment: http://stackoverflow.com/comment/103547433
score: 1
has body: The folder keras_text_summarization was outside the demo package. So as it appears the documentation is incorrect. I needed the either to: Install the keras_text_summarization by running setup.py on parent folder. Move keras_text_summarization inside the demo folder. I ran step 2 and it worked (moved keras_text_summarization inside the demo folder). This means no external modules were missing and condo installation was perfect.
answers question: http://stackoverflow.com/q/51157258
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51157258
downvote count: 0
type: Answer

tuples
tags question: http://stackoverflow.com/q/51071844
tags question: http://stackoverflow.com/q/51100891
tags question: http://stackoverflow.com/q/51107992
tags question: http://stackoverflow.com/q/51049629
tags question: http://stackoverflow.com/q/51154939
tags question: http://stackoverflow.com/q/51081841
tags question: http://stackoverflow.com/q/51039409
tags question: http://stackoverflow.com/q/51067197
tags question: http://stackoverflow.com/q/51162027
tags question: http://stackoverflow.com/q/51089872
tags question: http://stackoverflow.com/q/51030465
tags question: http://stackoverflow.com/q/51156465
tag name: tuples
tags question: http://stackoverflow.com/q/51108874
tags question: http://stackoverflow.com/q/51053267
tags question: http://stackoverflow.com/q/51093113
tags question: http://stackoverflow.com/q/51074197
tags question: http://stackoverflow.com/q/51088335
tags question: http://stackoverflow.com/q/51064068
type: Tag
tags question: http://stackoverflow.com/q/51065837

http://stackoverflow.com/comment/89076162
score: 0
has text: @MichaelO., `pd.factorize` does not reorder by default. What do you need for your sample `a`, e.g. `[1, 0, 2]` ?
type: Comment
comment on: http://stackoverflow.com/a/51042359
type: AnswerComment

http://stackoverflow.com/comment/89171261
has text: @RafaelC I'm sorry, but when I posted my answer then I saw you already gave something like that and also noticed that you didn't print the count and then edited. I hope it's clear to you now.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51091471

http://stackoverflow.com/comment/89318593
comment on: http://stackoverflow.com/q/51148933
score: 0
type: Comment
type: QuestionComment
has text: I did but it didn't work, sadly. :(

http://stackoverflow.com/comment/89194308
has text: Please clarify your specific problem or add additional details to highlight exactly what you need.
score: 0
comment on: http://stackoverflow.com/q/51103389
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89102037
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51055568
has text: Yes, my question is duplicated as you show. Thank you.

http://stackoverflow.com/q/51149822
has answer: http://stackoverflow.com/a/56121834
score: 0
accepted answer: http://stackoverflow.com/a/56121834
has comment: http://stackoverflow.com/comment/89283421
answer count: 3
has answer: http://stackoverflow.com/a/51226371
favorite count: 0
has answer: http://stackoverflow.com/a/51183775
tagged with: python
tagged with: dictionary
has body: mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}] i want it as myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
linked to: http://stackoverflow.com/q/41521431
has title: How to convert list of dictionaries to dictionary
type: AnsweredQuestion
tagged with: list
type: Question
possible better answer: http://stackoverflow.com/a/51183775
upvote count: 5
has comment: http://stackoverflow.com/comment/89283262
downvote count: 5

http://stackoverflow.com/q/51057822
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python pandas: groupby and devide by the first value of each group
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51057860
has body: I have a pandas dataframe like this. &gt;data ID Distance Speed 1 100 40 1 200 20 1 200 10 2 400 20 2 500 30 2 100 40 2 600 20 2 700 90 3 800 80 3 700 10 3 400 20 I want to groupby the table by ID, and create a new column time by dividing each value in the Distance column by the first row of the Speed column of each ID group. So the result should look like this. &gt;data ID Distance Speed Time 1 100 40 2.5 1 200 20 5 1 200 10 5 2 400 20 20 2 500 30 25 2 100 40 5 2 600 20 30 2 700 90 35 3 800 80 10 3 700 10 8.75 3 400 20 5 My attempt: data['Time'] = data['Distance'] / data.loc[data.groupby('ID')['Speed'].head(1).index, 'Speed'] But the result seems to be not good. How do you do it?
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51057860

http://stackoverflow.com/q/51090971
has body: I am trying to generate a large list of variables, but some of the variables may have subparts to them. The code below is where I am currently at. import string Num_Phases = 4 # Number of Phases Subphases = [2, 3] # Which Phases have Subphases Num_Subphases = [2, 2] # How Many Phases the respective Subphase have Phases = [] for i in range(1, Num_Phases + 1): if i &lt; 10: # Start with regular name Convention PhaseName = "Phase-0%s" %i # Check to see if phase has subphase for n in range(1, len(Num_Subphases) + 1): if Subphases[n - 1] == i: # If there is a Subphase, Check how many Subphases for m in range(1, Num_Subphases[n - 1] + 1): # for each subphase define a phase name PhaseName = ("Phase-0%s" %i) + ('').join(string.ascii_lowercase[m-1]) # Combine Phases into list Phases.append(PhaseName) Phases.append(PhaseName) I am currently getting a result of: ['Phase-01', 'Phase-02b', 'Phase-02b', 'Phase-03b', 'Phase-03b', 'Phase-04'] But I am wanting it to be: ['Phase-01', 'Phase-02a', 'Phase-02b', 'Phase-03a', 'Phase-03b', 'Phase-04'] This is going to be for a very large data set, but am using this as an example.
has comment: http://stackoverflow.com/comment/89170444
tagged with: list
upvote count: 3
answer count: 2
has title: Generate variable names in loop with name convention changing
tagged with: loops
has answer: http://stackoverflow.com/a/51091270
has answer: http://stackoverflow.com/a/51091015
possible better answer: http://stackoverflow.com/a/51091270
has comment: http://stackoverflow.com/comment/89170494
has comment: http://stackoverflow.com/comment/89170480
tagged with: ascii
has comment: http://stackoverflow.com/comment/89170553
type: AnsweredQuestion
downvote count: 0
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/51091015
type: Question
score: 3
tagged with: python

http://stackoverflow.com/comment/89252058
score: 0
comment on: http://stackoverflow.com/q/51130383
has text: I might have figured it out. MPLD3 starts its own web server at 127.0.0.1:8888 and my Flask application runs at 127.0.0.1:5000. Anyway to fix this?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89348355
comment on: http://stackoverflow.com/q/51166326
score: 0
type: Comment
type: QuestionComment
has text: I saw it, but I thought it was about stdlib library =(

http://stackoverflow.com/comment/89164083
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51087391
has text: Can you include the code for where the `gen_cert()` function is called? And possibly the code for the `User` class, if possible.

http://stackoverflow.com/a/72840331
has comment: http://stackoverflow.com/comment/138787323
downvote count: 1
has body: If you want to do the exact match and with strip the search on both sides with case ignore, df[df['Asset Name'].str.strip().str.match('searchstring'.strip(), case=False)]
has comment: http://stackoverflow.com/comment/138787303
type: Answer
answers question: http://stackoverflow.com/q/51026771
score: 2
upvote count: 3

http://stackoverflow.com/a/51062292
accepted answer of: http://stackoverflow.com/q/51062176
score: 14
upvote count: 14
has comment: http://stackoverflow.com/comment/114004752
has body: pandas.read_csv() accepts a file-like object. Paramiko is a library which handles SFTP and can provide file-like objects. Once you've set up the connection, it's simple as: with sftp.open("file.csv") as f: pd.read_csv(f)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51062176
type: Answer

http://stackoverflow.com/q/51164339
has comment: http://stackoverflow.com/comment/89312132
has comment: http://stackoverflow.com/comment/89311971
has comment: http://stackoverflow.com/comment/89312080
has answer: http://stackoverflow.com/a/51164438
has comment: http://stackoverflow.com/comment/89312315
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89312405
has comment: http://stackoverflow.com/comment/89312229
has body: In my code I am trying to print without a new line after the program exits and print again. I am printing with a comma after for example: type_d=dict.fromkeys(totals,[0,0]) for keysl in type_d.keys(): print type_d[keysl][0] , ",", type_d[keysl][1] , ",", print "HI" , But when the program exits and I call on another one there is a newline inputted after the last value in the file. How can I avoid this?
possible better answer: http://stackoverflow.com/a/51164418
has comment: http://stackoverflow.com/comment/89312327
has title: Python 2.6 print with no newline after program exits
accepted answer: http://stackoverflow.com/a/51164438
has answer: http://stackoverflow.com/a/51164418
answer count: 2
has comment: http://stackoverflow.com/comment/89312366
has comment: http://stackoverflow.com/comment/89312089
has comment: http://stackoverflow.com/comment/89312211
downvote count: 0
tagged with: python-2.x
linked to: http://stackoverflow.com/q/493386
has comment: http://stackoverflow.com/comment/89312082
favorite count: 0
has comment: http://stackoverflow.com/comment/89311991
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51046556
type: Answer
has comment: http://stackoverflow.com/comment/89084773
has comment: http://stackoverflow.com/comment/89085118
answers question: http://stackoverflow.com/q/51046460
has body: Python looks for suitable modules based on its PATH, and the first place it looks for them is in the folder you are when you launch the program. If you want the interpreter to ignore the original source files, move to the directory where the .pyc files are and launch the script with python caller.pyc
has comment: http://stackoverflow.com/comment/89084361
has comment: http://stackoverflow.com/comment/89084792
score: 0

http://stackoverflow.com/comment/89104003
score: 0
has text: Yes there is. And I haven't seen more than two yet, but I can't rule it out.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51042841

http://stackoverflow.com/comment/89241598
type: AnswerComment
comment on: http://stackoverflow.com/a/51086707
score: 0
type: Comment
has text: Thanks @Eugene. I also write some code for replace the takewhile. but I think your code is more shorter than mine. :)

http://stackoverflow.com/comment/89238192
type: Comment
comment on: http://stackoverflow.com/a/51103442
type: AnswerComment
has text: this is not an answer. please edit your question. and my answer was very wrong indeed. sorry. in python lists are 0-indexed. substract one from every column number. ie `time.append(row[2])` it should work
score: 0

http://stackoverflow.com/a/51102583
score: 2
has body: Yes it is actually a very basic error that everyone does in the beginning :) The = operator does not mean the same thing in code as it does in math. Here it means that you want to assign a value to a variable (you can also think of it as the := operator that you can see in maths or other coding languages). The operator you need to compare two elements is == which returns a boolean value: either True or False
answers question: http://stackoverflow.com/q/51102504
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/51150833
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/89285835
has comment: http://stackoverflow.com/comment/89285728
upvote count: 4
has title: AttributeError: 'numpy.ndarray' object has no attribute 'step'
accepted answer: http://stackoverflow.com/a/51151215
has comment: http://stackoverflow.com/comment/89285509
tagged with: python
has comment: http://stackoverflow.com/comment/89285696
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51151215
type: Question
tagged with: numpy
answer count: 1
has body: I want to get 3d grid and I use the following command: x = np.linspace(-10,10,100) y = np.linspace(-10,10,100) z = np.linspace(-10,10,100) X,Y,Z = np.mgrid[x, y, z] And such error emerges AttributeError Traceback (most recent call last) in () 6 7 ----> 8 X,Y,Z = np.mgrid[x, y, z] 9 10 #X,Y,Z = np.mgrid[-10:10, -10:10, -10:10] ~/Desktop/PyProjects/Phys/env/lib/python3.6/site-packages/numpy/lib/index_tricks.py in __getitem__(self, key) 165 typ = int 166 for k in range(len(key)): --> 167 step = key[k].step 168 start = key[k].start 169 if start is None: AttributeError: 'numpy.ndarray' object has no attribute 'step' I know I can use this form to generate the grid X,Y,Z = np.mgrid[-10:10, -10:10, -10:10] but it is not mobile for me

http://stackoverflow.com/a/51151891
answers question: http://stackoverflow.com/q/51151666
has comment: http://stackoverflow.com/comment/89311311
has comment: http://stackoverflow.com/comment/89309407
has comment: http://stackoverflow.com/comment/89309725
score: 0
has comment: http://stackoverflow.com/comment/89317248
has body: You haven't created a user in the test database. In the example in the docs, it uses a fixture 'user-data.json'. Another option would be to create the user in setUp function. class MySeleniumTests(StaticLiveServerTestCase): def setUp(self): # Set up data for the whole TestCase self.user = User.objects.create_user(username='username', password='password') ...
type: Answer
has comment: http://stackoverflow.com/comment/89310136

http://stackoverflow.com/q/51045155
downvote count: 1
has comment: http://stackoverflow.com/comment/89082597
type: Question
tagged with: plotly-dash
has comment: http://stackoverflow.com/comment/89081645
upvote count: 5
has title: Plot and Dash: Object of type 'Response' is not JSON serializable
answer count: 1
has comment: http://stackoverflow.com/comment/89084132
favorite count: 0
has comment: http://stackoverflow.com/comment/89508073
has comment: http://stackoverflow.com/comment/89082807
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51254292
has comment: http://stackoverflow.com/comment/89081794
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/89486873
tagged with: plotly
has body: I want to build a Dashboard where most of the content (headers, graphs, etc.) are dependent on a main input from the user. Therefore, I want to create many callbacks so that output is dependent on the user input. But this seems to cause many errors. The current one is: "Object of type 'Response' is not JSON serializable" But more generally, I am also looking for some inputs on my code. ################## APP LAYOUT ################## app.layout = html.Div( #style={'backgroundColor': colors['background']}, children=[ html.H1('Dashboard for Visualisation', style={ 'textAlign': 'center', 'color': colors['text_black'] }), # html.H3('Choose Analysis', # style={ # 'textAlign': 'center', # 'color': colors['text_black'] # }), html.Div([ dcc.Dropdown( id='main_dropdown', options=[ {'label':'PCA', 'value':'PCA'}, {'label':'t-SNE', 'value':'t-SNE'} ] )], style={'width': '28%', 'display': 'inline-block', 'textAlign': 'center'} ), html.Div(id='action_header'), html.Div(id='action'), html.Div(id='sub_action'), html.Div(id='output_graph'), dcc.Slider( id='slider', min=0, max=55, step=None, value=20, marks={ 5:'5', 10:'10', 15:'15', 20:'20', 25:'25', 30:'30', 35:'35', 40:'40', 45:'45', 50:'50' }, updatemode='drag' ) #html.Div(id='slider_div') ]) ################## CALLBACKS ################## @app.callback( Output(component_id='action_header', component_property='children'), [Input(component_id='main_dropdown', component_property='value')]) def update_action_header(input): if(input == 't-SNE'): return html.H3("Pick labels to identify clusters", id='action_header') @app.callback( Output(component_id='action', component_property='children'), [Input(component_id='main_dropdown', component_property='value')]) def update_action_options(input): if(input == 't-SNE'): return dcc.Dropdown(id='gene-Dropdown', options=[{'label': s, 'value': s} for s in temp.keys()], value=['IDH1','SomeGene1','SomeGene2'], multi=True ) @app.callback( Output(component_id='sub_action', component_property='childr…

http://stackoverflow.com/q/51023118
has answer: http://stackoverflow.com/a/51023417
has title: How to implement a matrix with classes
tagged with: matrix
linked to: http://stackoverflow.com/q/25456448
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I need to implement a matrix with N cells and these cells depend on K parameters, some fixed and other variables. I would like to do all this through the use of classes. could someone explain to me the basic procedure?
upvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51023417
score: -1
tagged with: class

http://stackoverflow.com/comment/89247086
score: 0
has text: And what would be the syntaxis for PSQL if I just wanted to add values from a list (not a list of dictionaries)?
type: AnswerComment
comment on: http://stackoverflow.com/a/51131008
type: Comment

http://stackoverflow.com/a/51012854
has comment: http://stackoverflow.com/comment/89020481
downvote count: 0
has body: one way could be by creating a temporary column 'ID_res' in df, incrementing number when you change ID or at the row after the gaps is over 0.86 such as: df.loc[(df['ID'] != df['ID'].shift())| (df['Gaps'].shift() &gt; 0.86),'ID_res'] = 1 df['ID_res'] = df['ID_res'].cumsum().ffill() so your df looks like: ID Value Gaps ID_res Time 2018-04-08 00:28:52.607 1 2 0.334754 1.0 2018-04-08 00:48:57.722 1 5 0.173467 1.0 2018-04-08 00:59:22.202 1 6 1.625283 1.0 2018-04-08 02:36:53.221 1 4 0.332900 2.0 2018-04-08 02:56:51.662 1 7 0.372258 2.0 2018-04-08 03:19:11.791 1 10 0.000000 2.0 2018-04-08 02:56:51.662 2 5 0.511591 3.0 2018-04-08 03:27:33.390 2 2 0.340553 3.0 2018-04-08 03:47:59.379 2 9 1.329548 3.0 2018-04-08 05:07:45.751 2 3 0.000000 4.0 Now you can use the method you gave doing the first groupby on 'ID_res', keeping both column 'ID' and 'Value', and droping the column 'ID_res' at the end as you don't need it anymore: df = (df.groupby('ID_res', axis=0)['ID','Value'].resample('10min').mean() .groupby(level=0).apply(lambda x: x.interpolate()) .reset_index().drop('ID_res',1)) The result looks like: Time ID Value 0 2018-04-08 00:20:00 1.0 2.0 1 2018-04-08 00:30:00 1.0 3.5 2 2018-04-08 00:40:00 1.0 5.0 3 2018-04-08 00:50:00 1.0 6.0 4 2018-04-08 02:30:00 1.0 4.0 5 2018-04-08 02:40:00 1.0 5.5 6 2018-04-08 02:50:00 1.0 7.0 ... In which you don't have resampling between the row 3 and 4 has the 'Gaps' was over 0.86 between these values in the original df
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51012189
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89020963
answers question: http://stackoverflow.com/q/51012189
type: Answer
score: 2

http://stackoverflow.com/comment/89029396
type: AnswerComment
score: 0
type: Comment
has text: @AbdulRehman that's the default behaviour, if for some reason it's not in your case try setting the config variable `UPLOADED_FILES_USE_URL` to `True` in **settings.py** file
comment on: http://stackoverflow.com/a/51017434

http://stackoverflow.com/comment/89208627
type: QuestionComment
comment on: http://stackoverflow.com/q/51110726
has text: My desired output is '['ATGCCTGAAGCATTCTAG', 'ATGACTGTAAAACCCTAG']'
score: 0
type: Comment

http://stackoverflow.com/comment/89260691
comment on: http://stackoverflow.com/q/51136862
type: QuestionComment
has text: Right, so scratch that, you _can_ do what you want (see answer). Graph operations still work at tensor level, but the dataset API does implement this functionality (I thought that the nesting behavior only worked for tuples).
score: 0
type: Comment

http://stackoverflow.com/comment/89023688
comment on: http://stackoverflow.com/a/51013957
has text: I replaced `python-dev python-pip` with `python3-dev python3-pip` but now it is giving error. I have updated question with error.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51166908
has comment: http://stackoverflow.com/comment/112990267
score: 1
has comment: http://stackoverflow.com/comment/89318838
has comment: http://stackoverflow.com/comment/89319152
has comment: http://stackoverflow.com/comment/89318293
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51166611
accepted answer of: http://stackoverflow.com/q/51166611
type: Answer
has comment: http://stackoverflow.com/comment/89317856
has comment: http://stackoverflow.com/comment/89319551
has comment: http://stackoverflow.com/comment/112974679
has body: Listing all blobs is very costly operation inside the Azure Storage infrastructure because it translates into a full scan. Find below an example to efficiently check if the blob (e.g. filename in your case) exists or not in a given container: from azure.storage.blob import BlockBlobService from datetime import datetime def check_if_blob_exists(container_name: str, blob_names: []): start_time = datetime.now() if not container_name or container_name.isspace(): raise ValueError("Container name cannot be none, empty or whitespace.") if not blob_names: raise ValueError("Block blob names cannot be none.") block_blob_service = BlockBlobService(account_name="{Storage Account Name}", account_key="{Storage Account Key}") for blob_name in blob_names: if block_blob_service.exists(container_name, blob_name): print("\nBlob '{0}' found!".format(blob_name)); else: print("\nBlob '{0}' NOT found!".format(blob_name)); end_time = datetime.now() print("\n***** Elapsed Time =&gt; {0} *****".format(end_time - start_time)) if __name__ == "__main__": blob_names = [] # Exists blob_names.append("eula.1028.txt") blob_names.append("eula.1031.txt") blob_names.append("eula.1033.txt") blob_names.append("eula.1036.txt") blob_names.append("eula.1040.txt") # Don't exist blob_names.append("blob1") blob_names.append("blob2") blob_names.append("blob3") blob_names.append("blob4") check_if_blob_exists("containername", blob_names) Find below a screenshot of a quick execution test from my laptop from West US (~150 Mbps of Download, ~3.22 Mbps of Upload, per Google Speed Test) checking if 9 blobs exists in a LRS Storage Account in West US as well.
upvote count: 1
has comment: http://stackoverflow.com/comment/89319341

http://stackoverflow.com/comment/89175838
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51091905
has text: I also went with SQLAlchemy Utils UUID, and I've been very happy.

http://stackoverflow.com/q/51108969
accepted answer: http://stackoverflow.com/a/51109046
tagged with: tortoisesvn
has body: I have some svn patches that unfortunately have mixed line endings. My Windows svn client (tortoise) saves its metadata with CRLF line endings. However, my colleagues use Cornerstone on MacOS to apply patches which needs the metadata to have LF line endings. I can't bulk change all the line endings in the file (working on that with management). I need to change the line endings of only the metadata. I am able to detect CRLF line endings in my patch file just fine but trying to replace them with LF is not working out. Can anyone help out? If there's a more efficient way to do this please let me know. I'm using python 2.7.15 import sys import os CRLF = '\r\n' LF = '\n' filePath = sys.argv[1] newFilePath = filePath.replace('.patch', '-converted.patch') newFile = open(newFilePath,'wb') oldFile = open(filePath, 'r+b') for idx,line in enumerate(oldFile.readlines()): line = str(line) if line.startswith("=====") or line.startswith("@@") or line.startswith("+++") or line.startswith("---") or line.startswith("Index:"): if line.endswith(CRLF): print ("detected CRLF at line " + str(idx)) line.replace(CRLF, LF) print ("converted line ending to LF at line " + str(idx)) if line.endswith(CRLF): print("hmm... line " + str(idx) + " still a crlf line!!!!!!!!") newFile.writelines(line) oldFile.close() newFile.close()
has title: Replacing line endings conditionally in python 2.7.15
type: AnsweredQuestion
type: Question
tagged with: cornerstone
tagged with: line-endings
has answer: http://stackoverflow.com/a/51109046
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python

python-2.7
tags question: http://stackoverflow.com/q/51089798
tags question: http://stackoverflow.com/q/51161676
tags question: http://stackoverflow.com/q/51086846
tags question: http://stackoverflow.com/q/51102539
tags question: http://stackoverflow.com/q/51039970
tags question: http://stackoverflow.com/q/51157742
tags question: http://stackoverflow.com/q/51164851
tags question: http://stackoverflow.com/q/51082728
tags question: http://stackoverflow.com/q/51048266
tags question: http://stackoverflow.com/q/51116288
tags question: http://stackoverflow.com/q/51112900
tags question: http://stackoverflow.com/q/51140791
tags question: http://stackoverflow.com/q/51112574
tags question: http://stackoverflow.com/q/51061816
tags question: http://stackoverflow.com/q/51021929
tags question: http://stackoverflow.com/q/51016470
tags question: http://stackoverflow.com/q/51091466
tags question: http://stackoverflow.com/q/51074335
tags question: http://stackoverflow.com/q/51108155
tags question: http://stackoverflow.com/q/51088481
tags question: http://stackoverflow.com/q/51024898
tags question: http://stackoverflow.com/q/51103947
tags question: http://stackoverflow.com/q/51155963
tags question: http://stackoverflow.com/q/51087634
tags question: http://stackoverflow.com/q/51076376
tags question: http://stackoverflow.com/q/51134530
tags question: http://stackoverflow.com/q/51049819
tags question: http://stackoverflow.com/q/51012350
tags question: http://stackoverflow.com/q/51028699
tags question: http://stackoverflow.com/q/51038351
tags question: http://stackoverflow.com/q/51024286
tags question: http://stackoverflow.com/q/51066152
tags question: http://stackoverflow.com/q/51157908
tags question: http://stackoverflow.com/q/51133767
tags question: http://stackoverflow.com/q/51157958
tags question: http://stackoverflow.com/q/51157042
tags question: http://stackoverflow.com/q/51053219
tags question: http://stackoverflow.com/q/51099609
tags question: http://stackoverflow.com/q/51024767
tags question: http://stackoverflow.com/q/51035619
tags question: http://stackoverflow.com/q/51011721
tags question: http://stackoverflow.com/q/51072977
tags question: http://stackoverflow.com/q/51060408
tags question: http://stackoverflow.com/q/51014632
tags question: http://stackoverflow.com/q/51144708
tags question: http://stackoverflow.com/q/51063124
tags question: http://stackoverflow.com/q/51039167
tags question: http://stackoverflow.com/q/51023652
tags question: http://stackoverflow.com/q/51132370
tags question: http://stackoverflow.com/q/51054844
tags question: http://stackoverflow.com/q/51057443
tags question: http://stackoverflow.com/q/51031822
tags question: http://stackoverflow.com/q/51145376
tags question: http://stackoverflow.com/q/51092416
tags question: http://stackoverflow.com/q/51100817
tags question: http://stackoverflow.com/q/51088676
tags question: http://stackoverflow.com/q/51045785
tags question: http://stackoverflow.com/q/51133753
tags question: http://stackoverflow.com/q/51153722
tags question: http://stackoverflow.com/q/51111017
tags question: http://stackoverflow.com/q/51063947
tags question: http://stackoverflow.com/q/51066916
tags question: http://stackoverflow.com/q/51054554
tags question: http://stackoverflow.com/q/51109245
tags question: http://stackoverflow.com/q/51014092
tags question: http://stackoverflow.com/q/51143777
tags question: http://stackoverflow.com/q/51155928
tags question: http://stackoverflow.com/q/51040853
tags question: http://stackoverflow.com/q/51126737
tags question: http://stackoverflow.com/q/51164980
tags question: http://stackoverflow.com/q/51103030
tags question: http://stackoverflow.com/q/51033612
tags question: http://stackoverflow.com/q/51020239
tags question: http://stackoverflow.com/q/51036137
tags question: http://stackoverflow.com/q/51160798
tags question: http://stackoverflow.com/q/51139975
tags question: http://stackoverflow.com/q/51144561
tags question: http://stackoverflow.com/q/51131742
tags question: http://stackoverflow.com/q/51114259
tags question: http://stackoverflow.com/q/51030047

http://stackoverflow.com/q/51112096
score: 1
type: Question
tagged with: environment-variables
answer count: 1
tagged with: pythonpath
downvote count: 0
has answer: http://stackoverflow.com/a/51112316
has body: I am using ubuntu 16.04. Now I am starting my first Django project. Please check this error: (unix-9PXH2taC) unix@unix:~/Desktop/django/test_project$** python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in &lt;module&gt; from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? What is going wrong?
tagged with: python
favorite count: 0
has title: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
tagged with: virtual
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46210934
upvote count: 1
tagged with: django
duplicate of: http://stackoverflow.com/q/46210934

http://stackoverflow.com/comment/89221099
has text: This is a side comment. If you are new to Python I would strongly recommend jumping on 3.x Python (3.6 is stable release) as 2.7 will be deprecated in a few years.
comment on: http://stackoverflow.com/q/51117445
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51135302
score: 0
has body: I wrote a client/server application. I receive data from a server that goes out as bool type. As you know the data that I am receiving in my client is in bytes, so I decode it to string and then to integer type. Depends on a data value I want to show some information in label. The program actually does what I want but after first message It doesn't show the information. After view iterations of sent data the label turns on and change its value as I want. What is happening? If program works, why with a few first iterations a loop doesn't work properly, but later it is? #!/usr/bin/env python import socket import tkinter as tk TCP_IP = '192.168.0.15' TCP_PORT = 62 BUFFER_SIZE = 4096 data = b'' def counter_label(label) def count(label): global data data = s.recv(BUFFER_SIZE) dane_str = data.decode("utf-8") dane_int = int(dane_str) if dane_int != 0: psa=15 else: psa = 22 label.config(text=str(psa)) label.after(1, count) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) root = tk.Tk() label = tk.Label(root, fg="green", font="Verdana 200 bold") label.pack() counter_label(label) root.mainloop()
has title: Tkinter delay for socket data
type: UnansweredQuestion
tagged with: sockets
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89259861
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89257804
has comment: http://stackoverflow.com/comment/89257929

http://stackoverflow.com/q/51143361
favorite count: 0
has comment: http://stackoverflow.com/comment/89513171
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51143553
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51143553
has title: Unable to create a test and training set using sklearn
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89513777
has body: Here's the code I've been working on. import pandas as pd import numpy as np from sklearn.datasets import load_boston housing_data = load_boston() from sklearn.model_selection import train_test_split train_set, test_set = train_test_split(housing_data, test_size = 0.2, random_state = 42) And I get this error. /anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_split.py in train_test_split(*arrays, **options) 2057 2058 return list(chain.from_iterable((safe_indexing(a, train), -&gt; 2059 safe_indexing(a, test)) for a in arrays)) 2060 2061 /anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_split.py in &lt;genexpr&gt;(.0) 2057 2058 return list(chain.from_iterable((safe_indexing(a, train), -&gt; 2059 safe_indexing(a, test)) for a in arrays)) 2060 2061 /anaconda3/lib/python3.6/site-packages/sklearn/utils/__init__.py in safe_indexing(X, indices) 162 return X[indices] 163 else: --&gt; 164 return [X[idx] for idx in indices] 165 166 /anaconda3/lib/python3.6/site-packages/sklearn/utils/__init__.py in &lt;listcomp&gt;(.0) 162 return X[indices] 163 else: --&gt; 164 return [X[idx] for idx in indices] 165 166 KeyError: 3
downvote count: 0
score: 1
tagged with: scikit-learn

http://stackoverflow.com/q/51130389
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51130504
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I'd like to split the data in the following DataFrame df = pd.DataFrame(data={'per': np.repeat([10,20,30], 32), 'r':12*range(8), 'cnt': np.random.randint(300, 400, 96)}); df cnt per r 0 355 10 0 1 359 10 1 2 347 10 2 3 390 10 3 4 304 10 4 5 306 10 5 .. ... ... .. 87 357 30 7 88 371 30 0 89 396 30 1 90 357 30 2 91 353 30 3 92 306 30 4 93 301 30 5 94 329 30 6 95 312 30 7 [96 rows x 3 columns] such that for each r value a new column cnt_r{r} exist in a DataFrame but also keeping the corresponding per column. The following piece of code almost does what I want except that it looses the per column: pd.DataFrame({'cnt_r{}'.format(i): df[df.r==i].reset_index()['cnt'] for i in range(8)}) cnt_r0 cnt_r1 cnt_r2 cnt_r3 cnt_r4 cnt_r5 cnt_r6 cnt_r7 0 355 359 347 390 304 306 366 310 1 394 331 384 312 380 350 318 396 2 340 336 360 389 352 370 353 319 ... 9 341 300 386 334 386 314 358 326 10 357 386 311 382 356 339 375 357 11 371 396 357 353 306 301 329 312 I need a way to build the follow DataFrame: per cnt_r0 cnt_r1 cnt_r2 cnt_r3 cnt_r4 cnt_r5 cnt_r6 cnt_r7 0 10 355 359 347 390 304 306 366 310 1 10 394 331 384 312 380 350 318 396 2 10 340 336 360 389 352 370 353 319 ... 7 20 384 385 376 323 345 339 339 347 9 30 341 300 386 334 386 314 358 326 10 30 357 386 311 382 356 339 375 357 11 30 371 396 357 353 306 301 329 312 Note that by construction my dataset has same number of values per per for each r. Obviously my dataset is much larger than the example one (about 800 million records). Many thanks for your time.
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51130504
score: 2
has title: How to split column data and create new DataFrame with multiple columns
downvote count: 0

http://stackoverflow.com/comment/89393163
comment on: http://stackoverflow.com/q/51156886
type: Comment
type: QuestionComment
has text: You don't need to convert your `seq` into a list `a`: if `seq` is a string, it behaves similarly to a list in the sense that you can directly do `b = seq[(0+3*i):(3+3*i)]`. Also, it would be better to use a more meaningful variable name than `b`, like `codon` or something like that.
score: 0

http://stackoverflow.com/comment/89386736
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51164091
has text: I have no idea. Maybe [transports and protocols](https://docs.python.org/3/library/asyncio-protocol.html) would be a better fit.
score: 0

http://stackoverflow.com/comment/89135681
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51072941
has text: @abarnert makes sense. It's interesting to see both are used in stdlib. I think the decorator pattern is appealing here. Just wanted to make sure I'm not violating some bad practice.

http://stackoverflow.com/comment/89143702
has text: You are showing what you are doing that is causing the error, but what we are not seeing is the code related to the error. What is `time_recorded` and where is it used?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51077280
score: 0

http://stackoverflow.com/q/51085780
has body: I am using 2d numpy matrices as adjacency matrices for various graph representations and traversals. These are unweighted graphs, and I only need to check for connectivity, nothing more. Therefore, I am using 1s to represent edges, and 0s to represent the lack of an edge. I acknowledge that the following question probably depends on many factors - most of which are outside of my understanding. What is the appropriate dtype to use when doing bitwise operations between two matrices of 1s and 0s (or trues and falses)? I also have a second question - is numpy even the correct choice for this scenario? I am wondering if maybe there is a python package I don't know about that is better than numpy if you are only doing bitwise operations (no arithmetic). Thank you.
score: 0
tagged with: matrix
tagged with: python
accepted answer: http://stackoverflow.com/a/51088777
has comment: http://stackoverflow.com/comment/89160284
type: AnsweredQuestion
tagged with: bitwise-operators
type: Question
tagged with: numpy
has title: Boolean matrices with numpy - bitwise operations questions
has comment: http://stackoverflow.com/comment/89160751
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/51088777

http://stackoverflow.com/comment/89309249
score: 0
type: AnswerComment
type: Comment
has text: This still fails on simple counter-examples.
comment on: http://stackoverflow.com/a/51160178

http://stackoverflow.com/a/51719735
answers question: http://stackoverflow.com/q/51156327
score: -1
has comment: http://stackoverflow.com/comment/93285618
has body: you have to set "Any" parameter when you're calling your service: client.service.storeExtResource(Any='value')
downvote count: 1
type: Answer
upvote count: 0

http://stackoverflow.com/a/51032412
has body: If you only want to get that title without using any hardcoded index then the following should work: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.youtube.com/watch?v=MBBtxuHoV_g") wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"h1.title yt-formatted-string"))).text print(element) driver.quit() Result: Bryan Cranston, Kanye West, Will Smith SHOCKED by Magician David Blaine
downvote count: 0
answers question: http://stackoverflow.com/q/51032139
accepted answer of: http://stackoverflow.com/q/51032139
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/a/51057190
has comment: http://stackoverflow.com/comment/89109200
has comment: http://stackoverflow.com/comment/89106364
has body: Have you placed your scrolledtext in the GUI? I added a pack() and open_command() call, and your code worked for me. import tkinter as tk from tkinter.scrolledtext import ScrolledText from tkinter import filedialog root = tk.Tk() textPad = ScrolledText(root) textPad.pack() def open_command(): file = filedialog.askopenfile(parent=root,mode='rt',title='Select a file') if file != None: contents = file.read() textPad.insert('1.0',contents) file.close() open_command() root.mainloop()
answers question: http://stackoverflow.com/q/51056793
type: Answer
score: 0

prediction
tags question: http://stackoverflow.com/q/51085853
tags question: http://stackoverflow.com/q/51023739
tag name: prediction
tags question: http://stackoverflow.com/q/51146933
type: Tag

http://stackoverflow.com/a/51164376
upvote count: 2
answers question: http://stackoverflow.com/q/51164356
score: 2
downvote count: 0
has body: Use sort and unique: import numpy as np a=np.array([[1,1,1],[1,2,3],[2,1,3],[2,2,2]]) np.unique(np.sort(a, axis=1), axis=0) array([[1, 1, 1], [1, 2, 3], [2, 2, 2]])
type: Answer

http://stackoverflow.com/comment/89145237
type: QuestionComment
has text: @ResetACK Ok I will edit it as a post now :)
comment on: http://stackoverflow.com/q/51078276
score: 0
type: Comment

http://stackoverflow.com/comment/89201575
has text: Yes I was actually looking at that. I think what the problem is the shape says it's only one dimension, but it is a array of 4000 X 1 arrays so it is actually more than one dimension. I guess I'm trying to figure out how to turn my array of arrays into the correct dimensions like it should be.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51106024

http://stackoverflow.com/comment/89277259
type: QuestionComment
comment on: http://stackoverflow.com/q/51125100
has text: Thanks, it worked also for me on the Jupyter notebook.
score: 0
type: Comment

http://stackoverflow.com/q/51059699
answer count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/51059893
has body: I would like to iterate over whole data list and create dict with increase value, where key will be userId. I have userId and I add 1 in the loop, but I recived an error: KeyError: 100 todos = {} data = [ { "userId": 100, "id": 1, "title": "delectus aut autem", "completed": True }, { "userId": 200, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": True }, { "userId": 300, "id": 3, "title": "fugiat veniam minus", "completed": True } ] for i in data: todos[i['userId']] += 1
score: 2
upvote count: 2
has title: KeyError when I want to increase object and put him to dict
possible better answer: http://stackoverflow.com/a/51060221
has answer: http://stackoverflow.com/a/51060221
tagged with: dictionary
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/51059893
has answer: http://stackoverflow.com/a/51059786
has answer: http://stackoverflow.com/a/51059909
has answer: http://stackoverflow.com/a/51060024
downvote count: 0
tagged with: key
favorite count: 0

http://stackoverflow.com/comment/89026101
score: 0
type: Comment
has text: https://stackoverflow.com/questions/35689671/how-to-do-a-column-sum-in-tensorflow
type: QuestionComment
comment on: http://stackoverflow.com/q/51016803

http://stackoverflow.com/q/51074956
has title: Remote desktop connection using pywinauto
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51079677
score: 3
upvote count: 3
type: Question
tagged with: remote-desktop
linked to: http://stackoverflow.com/q/50299472
downvote count: 0
has body: I want that my script will automate to remote desktop connection. My problem is how will i able to send text in a script in loggin in into the remote desktop connection in password area. Below is my script from pywinauto.application import Application import win32api import pywinauto from pywinauto import keyboard from pywinauto import timings import time from pywinauto.keyboard import SendKeys app = Application().Start(cmd_line=u'"C:\Windows\system32\mstsc.exe" ') pywinauto.mouse.move(coords=(1025, 430)) pywinauto.mouse.click(button='left', coords=(1025, 430)) pywinauto.mouse.move(coords=(900, 280)) pywinauto.mouse.click(button='left', coords=(900,280)) time.sleep(1) keyboard.SendKeys('test123') #app.WindowsSecurity.Edit.type_keys("pywinauto Works!", with_spaces = True) #notepad = app[u'Notepad++'] #notepad.Wait('ready') #menu_item = notepad.MenuItem(u'File-&gt;New') #menu_item.Click() My code works well when executed the remote desktop connection will execute. Only the input text in password is my problem. Can someone help me figured this thing out?. Any help is muchly appreciated. TIA
answer count: 1
tagged with: pywinauto
favorite count: 0

http://stackoverflow.com/comment/89048321
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51027045
has text: When you close a file as soon as possible, though, and you have to open it again (and repeat this process > 1mil times) then the time it takes to open the file takes up a lot of your processing time.
type: Comment

http://stackoverflow.com/q/51035431
has comment: http://stackoverflow.com/comment/89062918
has body: I have the foll. dictionary in python: OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0)), (43, ('A4', nan))]) Is there a way to remove the entries where any of the values is NaN? I tried this: {k: dict_cg[k] for k in dict_cg.values() if not np.isnan(k)} It would be great if the soln works for both python 2 and python 3
has title: remove entries with nan values in python dictionary
has answer: http://stackoverflow.com/a/51035535
linked to: http://stackoverflow.com/q/20320022
has comment: http://stackoverflow.com/comment/89062854
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89062814
downvote count: 0
has answer: http://stackoverflow.com/a/51035916
score: 7
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51035535
has comment: http://stackoverflow.com/comment/89062868
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89062784
has answer: http://stackoverflow.com/a/51035855
has comment: http://stackoverflow.com/comment/89062929
has answer: http://stackoverflow.com/a/51035623
has comment: http://stackoverflow.com/comment/89062720
upvote count: 7
has comment: http://stackoverflow.com/comment/89062755
has comment: http://stackoverflow.com/comment/89062923
possible better answer: http://stackoverflow.com/a/51035623
answer count: 4

http://stackoverflow.com/q/51094474
type: Question
accepted answer: http://stackoverflow.com/a/51095182
tagged with: time-series
has title: Forecasting Bimonthly data
tagged with: forecasting
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51095182
has body: I have a bimontly data for 2 years for sales and the data looks like this Date_time_index Customer exposure. 1/3/2015. 234. 15/3/2015. 560. 1/4/2016. 789. 15/4/2016. 678. 1/5/2017 222. 15/5/2017. 456. So basically I want to predict the bimontly sales for the 2018 data. Since python does not accept the date time index for the regression and if I convert the dates into the number of days, the data would looks like this Days. Customer_exposure. 15. 23. 14. 560. 15. 789. 14. 678. 15. 222. ce_lm3 = smf.ols(customer_exposure~ days', data=differenced_series).fit() The above conversion of the bimontly data into days does not seem very correct and wise to me , can anyone's suggest me how can I convert this time series index into days so that I can predict the exposure for customer for 2018. Note,,: I can't convert my dates time index to the month number since this is a bimonthly data and not monthly or at any other level.this strictly needs to be bimonthly. Thanks in advance
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89162242
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51086815
has text: According to picture, content in your file is not saved. Everythin should work, you just didn't save your code yet.
score: 3

http://stackoverflow.com/q/51069677
has body: I found this post and wanted to modify the script slightly to download the images to a specific folder. My edited file looks like this: import re import requests from bs4 import BeautifulSoup import os site = 'http://pixabay.com' directory = "pixabay/" #Relative to script location response = requests.get(site) soup = BeautifulSoup(response.text, 'html.parser') img_tags = soup.find_all('img') urls = [img['src'] for img in img_tags] for url in urls: #print(url) filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url) with open(os.path.join(directory, filename.group(1)), 'wb') as f: if 'http' not in url: url = '{}{}'.format(site, url) response = requests.get(url) f.write(response.content) This seems to work fine for pixabay, but if I try a different site like imgur or heroimages, it doesn't seem to work. If I replace the site declaration with site = 'http://heroimages.com/portfolio' nothing is downloaded. The print statement (when uncommented) doesn't print anything, so I'm guessing it's not finding any image tags? I'm not sure. On the other hand, if I replace site with site = 'http://imgur.com' I sometimes get a AttributeError: 'NoneType' object has no attribute 'group' or, if the images do download, I can't even open them because I get the following error: Also worth noting, right now the script requires the folder specified by directory to exist. I plan on changing it in the future so that the script creates the directory, if it does not exist already.
type: Question
type: AnsweredQuestion
score: 3
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51069874
has title: Python script to download all images from a website to a specified folder with BeautifulSoup
tagged with: python
tagged with: request
answer count: 1
upvote count: 3
tagged with: image
accepted answer: http://stackoverflow.com/a/51069874
downvote count: 0
linked to: http://stackoverflow.com/q/18408307

http://stackoverflow.com/comment/89297347
type: QuestionComment
comment on: http://stackoverflow.com/q/51156221
type: Comment
has text: Please include the exact command used to build the library (from Go source).
score: 0

http://stackoverflow.com/a/74947877
score: 0
type: Answer
has body: I recommend to use simple EMA calculation to achieve this. SMMA essentially is EMA but just with different length. For a SMMA(x) , I will do EMA(x*2-1) SMMA EMA 1 1 2 3 3 5 4 7 5 9 6 11 7 13 8 15 9 17 10 19 11 21 12 23 13 25 14 27 15 29 16 31 17 33
answers question: http://stackoverflow.com/q/51093446

http://stackoverflow.com/comment/89183514
type: QuestionComment
comment on: http://stackoverflow.com/q/51097419
has text: sure u need specify what u want back, self refer only to instance attribute but self without anything is not referring to any elements; if you notice before you did self.canvas.pack() and worked without problems
score: 0
type: Comment

http://stackoverflow.com/comment/89210478
comment on: http://stackoverflow.com/q/51111786
score: 1
type: Comment
has text: When you see this happen, and you don't have a `return None` somewhere, it means your function is finishing without an explicit `return` (all the loops are ending and you've never satisfied the `if` condition where you'd return).
type: QuestionComment

http://stackoverflow.com/q/51076717
tagged with: python
score: 0
answer count: 1
has body: I was attempting to write code using the csv, os, and PyPDF2 packages to extract text from numerous pdf files within a directory and then place the data in a csv. The following code illustrates my efforts (it runs but provides no output): import PyPDF2 import csv import os for filename in os.listdir(os.getcwd()): if filename endswith('.pdf'): pdfFileobject = open(filename, 'rb') pdfUnderstander = PyPDF2.PdfFileReader(pdfFileObject) numberpages = pdfUnderstander.getNumPages() increment = 0 text = "" while increment &lt; numberpages: pdfPage = pdfUnderstander.getPage(increment) increment += 1 text += pdfPage.extractText() print(text) I have not also quite gotten to the part yet for csv because of the failure of the part above to work, but would like some advice on how that could be stored as well.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89142427
has answer: http://stackoverflow.com/a/51078835
tagged with: python-3.x
has title: Issues with looping through files in directory to extract data in PDFs and placing them in CSV in Python
type: Question
has comment: http://stackoverflow.com/comment/89142855
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/q/51148685
has title: string manipulation : str ing = aaabbcccaa to a3b2c3a2 in python
linked to: http://stackoverflow.com/q/32855812
has answer: http://stackoverflow.com/a/51148843
has comment: http://stackoverflow.com/comment/89281419
upvote count: 0
duplicate of: http://stackoverflow.com/q/32855812
answer count: 1
favorite count: 0
has body: Can anyone help me in writing code in python for string manipulation string is string = aaabbcccaa output will be a3b2c3a2
has comment: http://stackoverflow.com/comment/89281316
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 3
score: -3
type: Question
has comment: http://stackoverflow.com/comment/89281314

http://stackoverflow.com/comment/89144472
type: QuestionComment
comment on: http://stackoverflow.com/q/51077458
has text: Thanks @asongtoruin !
score: 0
type: Comment

http://stackoverflow.com/comment/89123918
comment on: http://stackoverflow.com/a/51065103
score: 0
type: AnswerComment
has text: @edyvedy13 - Then need `mask = df['category'].str.contains('subsidy|e_commerce')`
type: Comment

http://stackoverflow.com/q/51153201
possible better answer: http://stackoverflow.com/a/51153550
has comment: http://stackoverflow.com/comment/89289815
has comment: http://stackoverflow.com/comment/89289786
type: Question
has comment: http://stackoverflow.com/comment/89290444
has answer: http://stackoverflow.com/a/51153356
tagged with: python
has title: Get a value from columns in the output of Python subprocess.call
tagged with: python-3.x
tagged with: subprocess
has answer: http://stackoverflow.com/a/51153483
score: 0
has answer: http://stackoverflow.com/a/51153672
answer count: 5
has answer: http://stackoverflow.com/a/51153310
has answer: http://stackoverflow.com/a/51153550
accepted answer: http://stackoverflow.com/a/51153672
type: AnsweredQuestion
has body: Before explaining my question I want to mention that I have taken a look at various other questions at StackOverflow but couldn't find any solution related to my problem. So, that's why don't mark this as duplicate, please! I'm working on a Python(3.6) project in which I need to run a terminal command and parse a value from the output which is in the form of columns. Here's the command I ran: output = subprocess.call('kubectl get svc', shell=True) And here's the output: b'NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.35.240.1 &lt;none&gt; 443/TCP 28m node-app1 LoadBalancer 10.35.245.164 35.239.29.239 8000:32249/TCP 26m Now, I need to get EXTERNAL-IP from the second row and 4th column. How can I get this value?

http://stackoverflow.com/comment/89120464
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51065046
type: QuestionComment
has text: And how do you match the business ID to the business name? For what you have asked, there is a lot of information that is missing.

http://stackoverflow.com/comment/89141021
has text: This usually happens when there are not enough RAM on the GPU(s) to load the whole dataset (or a batch of it). Would you please post your code as well? Further, if your image files are on the hard disk, have you tried using [`ImageDataGenerator`](https://keras.io/preprocessing/image/) class and its [`flow_from_directory`](https://keras.io/preprocessing/image/#flow_from_directory) method? Plus, you should [properly set up your model](https://keras.io/getting-started/faq/#how-can-i-run-a-keras-model-on-multiple-gpus) to be able to train it on multiple GPUs.
comment on: http://stackoverflow.com/q/51034355
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89031368
type: AnswerComment
comment on: http://stackoverflow.com/a/51019255
score: 0
type: Comment
has text: You're a life saver. I understand row is the iterative value referring to row count, I am not sure what row_group is iterating in this code though.

list
tags question: http://stackoverflow.com/q/51133127
tags question: http://stackoverflow.com/q/51070068
type: Tag
tags question: http://stackoverflow.com/q/51092178
tags question: http://stackoverflow.com/q/51159491
tags question: http://stackoverflow.com/q/51053841
tags question: http://stackoverflow.com/q/51065837
tags question: http://stackoverflow.com/q/51159785
tags question: http://stackoverflow.com/q/51156507
tags question: http://stackoverflow.com/q/51103389
tags question: http://stackoverflow.com/q/51042752
tags question: http://stackoverflow.com/q/51038115
tags question: http://stackoverflow.com/q/51085230
tags question: http://stackoverflow.com/q/51061732
tags question: http://stackoverflow.com/q/51159971
tags question: http://stackoverflow.com/q/51143858
tags question: http://stackoverflow.com/q/51014310
tags question: http://stackoverflow.com/q/51099772
tags question: http://stackoverflow.com/q/51036326
tags question: http://stackoverflow.com/q/51092023
tags question: http://stackoverflow.com/q/51139632
tags question: http://stackoverflow.com/q/51058652
tags question: http://stackoverflow.com/q/51167254
tags question: http://stackoverflow.com/q/51143074
tags question: http://stackoverflow.com/q/51049629
tags question: http://stackoverflow.com/q/51124815
tags question: http://stackoverflow.com/q/51091885
tags question: http://stackoverflow.com/q/51076494
tags question: http://stackoverflow.com/q/51012536
tags question: http://stackoverflow.com/q/51072793
tags question: http://stackoverflow.com/q/51149550
tags question: http://stackoverflow.com/q/51146094
tags question: http://stackoverflow.com/q/51144303
tags question: http://stackoverflow.com/q/51085161
tags question: http://stackoverflow.com/q/51081291
tags question: http://stackoverflow.com/q/51118695
tags question: http://stackoverflow.com/q/51015310
tags question: http://stackoverflow.com/q/51037170
tags question: http://stackoverflow.com/q/51043766
tags question: http://stackoverflow.com/q/51114987
tags question: http://stackoverflow.com/q/51104478
tags question: http://stackoverflow.com/q/51154939
tags question: http://stackoverflow.com/q/51045880
tags question: http://stackoverflow.com/q/51116774
tags question: http://stackoverflow.com/q/51081841
tags question: http://stackoverflow.com/q/51045771
tag name: list
tags question: http://stackoverflow.com/q/51095634
tags question: http://stackoverflow.com/q/51022485
tags question: http://stackoverflow.com/q/51020992
tags question: http://stackoverflow.com/q/51055277
tags question: http://stackoverflow.com/q/51067197
tags question: http://stackoverflow.com/q/51070538
tags question: http://stackoverflow.com/q/51162027
tags question: http://stackoverflow.com/q/51137946
tags question: http://stackoverflow.com/q/51125769
tags question: http://stackoverflow.com/q/51061113
tags question: http://stackoverflow.com/q/51027813
tags question: http://stackoverflow.com/q/51055063
tags question: http://stackoverflow.com/q/51044731
tags question: http://stackoverflow.com/q/51021662
tags question: http://stackoverflow.com/q/51100078
tags question: http://stackoverflow.com/q/51135507
tags question: http://stackoverflow.com/q/51100043
tags question: http://stackoverflow.com/q/51053174
tags question: http://stackoverflow.com/q/51068844
tags question: http://stackoverflow.com/q/51052112
tags question: http://stackoverflow.com/q/51100680
tags question: http://stackoverflow.com/q/51070622
tags question: http://stackoverflow.com/q/51088935
tags question: http://stackoverflow.com/q/51060477
tags question: http://stackoverflow.com/q/51030465
tags question: http://stackoverflow.com/q/51091466
tags question: http://stackoverflow.com/q/51062934
tags question: http://stackoverflow.com/q/51113557
tags question: http://stackoverflow.com/q/51146967
tags question: http://stackoverflow.com/q/51156042
tags question: http://stackoverflow.com/q/51093963
tags question: http://stackoverflow.com/q/51090971
tags question: http://stackoverflow.com/q/51149822

http://stackoverflow.com/comment/89308387
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51162353
has text: If you extended the User model with the AbstractUser you should simply be able to run `{{ user.additional_field }}`. If you wanted to provide your view and all other relevant code that would help.

numpy
tags question: http://stackoverflow.com/q/51013319
tags question: http://stackoverflow.com/q/51152183
tags question: http://stackoverflow.com/q/51122073
tags question: http://stackoverflow.com/q/51083523
tags question: http://stackoverflow.com/q/51096373
tags question: http://stackoverflow.com/q/51139460
tags question: http://stackoverflow.com/q/51091377
tags question: http://stackoverflow.com/q/51139788
tags question: http://stackoverflow.com/q/51163566
tags question: http://stackoverflow.com/q/51079247
tags question: http://stackoverflow.com/q/51030316
tags question: http://stackoverflow.com/q/51077962
tags question: http://stackoverflow.com/q/51085435
tags question: http://stackoverflow.com/q/51062412
tags question: http://stackoverflow.com/q/51129506
tags question: http://stackoverflow.com/q/51064456
tags question: http://stackoverflow.com/q/51108716
tags question: http://stackoverflow.com/q/51110764
tags question: http://stackoverflow.com/q/51111378
tags question: http://stackoverflow.com/q/51120086
tags question: http://stackoverflow.com/q/51100078
tags question: http://stackoverflow.com/q/51082879
tags question: http://stackoverflow.com/q/51134734
tags question: http://stackoverflow.com/q/51013667
tags question: http://stackoverflow.com/q/51037886
tags question: http://stackoverflow.com/q/51093723
tags question: http://stackoverflow.com/q/51105703
tags question: http://stackoverflow.com/q/51119765
tags question: http://stackoverflow.com/q/51050622
tags question: http://stackoverflow.com/q/51084043
tags question: http://stackoverflow.com/q/51020482
tags question: http://stackoverflow.com/q/51021544
tags question: http://stackoverflow.com/q/51106131
tags question: http://stackoverflow.com/q/51069567
tags question: http://stackoverflow.com/q/51125847
tags question: http://stackoverflow.com/q/51031140
tags question: http://stackoverflow.com/q/51137573
tags question: http://stackoverflow.com/q/51014338
tags question: http://stackoverflow.com/q/51052346
tags question: http://stackoverflow.com/q/51094687
tags question: http://stackoverflow.com/q/51045305
tags question: http://stackoverflow.com/q/51038978
tags question: http://stackoverflow.com/q/51129662
tags question: http://stackoverflow.com/q/51127257
tags question: http://stackoverflow.com/q/51121265
tags question: http://stackoverflow.com/q/51049414
tags question: http://stackoverflow.com/q/51120615
tags question: http://stackoverflow.com/q/51018233
tags question: http://stackoverflow.com/q/51068981
tags question: http://stackoverflow.com/q/51026841
tags question: http://stackoverflow.com/q/51117941
tags question: http://stackoverflow.com/q/51040682
tags question: http://stackoverflow.com/q/51042867
tags question: http://stackoverflow.com/q/51102676
tags question: http://stackoverflow.com/q/51013059
tags question: http://stackoverflow.com/q/51108765
tags question: http://stackoverflow.com/q/51019609
tags question: http://stackoverflow.com/q/51137594
tags question: http://stackoverflow.com/q/51103952
tags question: http://stackoverflow.com/q/51086704
tags question: http://stackoverflow.com/q/51149911
tags question: http://stackoverflow.com/q/51029890
tags question: http://stackoverflow.com/q/51079559
tags question: http://stackoverflow.com/q/51117943
tags question: http://stackoverflow.com/q/51046237
tags question: http://stackoverflow.com/q/51161670
tags question: http://stackoverflow.com/q/51046762
tags question: http://stackoverflow.com/q/51124540
tags question: http://stackoverflow.com/q/51011970
tags question: http://stackoverflow.com/q/51158248
tags question: http://stackoverflow.com/q/51054293
tags question: http://stackoverflow.com/q/51072977
tags question: http://stackoverflow.com/q/51138775
tags question: http://stackoverflow.com/q/51088692
tags question: http://stackoverflow.com/q/51106618
tags question: http://stackoverflow.com/q/51121146
tags question: http://stackoverflow.com/q/51145748
tags question: http://stackoverflow.com/q/51164460
tags question: http://stackoverflow.com/q/51127657
tags question: http://stackoverflow.com/q/51073802

http://stackoverflow.com/comment/89162776
score: 0
comment on: http://stackoverflow.com/a/51051536
type: Comment
has text: That syntax is creating a 2D array as needed, what are the values for `grid_width` and `grid_height`? And I don't understand the second question. You refer to them by their indices in the grid. `cells[x][y]` is a different Cell than `cells[a][b]` (assuming `x,y` != `a,b`). Their "name" is their index pair into the grid.
type: AnswerComment

http://stackoverflow.com/a/51050155
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51050082
has comment: http://stackoverflow.com/comment/89091563
has comment: http://stackoverflow.com/comment/89092268
has comment: http://stackoverflow.com/comment/89091513
has comment: http://stackoverflow.com/comment/89091641
has body: If what you want to do is create a list out of semicolon-separated data, you should use re.split instead. lst = re.split(';|\n', updated_metabolite) Output ['cpd00001', 'cpd00009', 'cpd00015', ...]

http://stackoverflow.com/q/51026089
type: Question
has comment: http://stackoverflow.com/comment/89044788
has comment: http://stackoverflow.com/comment/89045802
tagged with: python
tagged with: dictionary
tagged with: double-quotes
has comment: http://stackoverflow.com/comment/89044758
score: 0
has body: The goal of my program is to create a dictionary of items (key) and their count (values). The keys are extracted from a text file, in which they're organized as lists. Example: ['synonymous_variant'] ['splice_region_variant&amp;synonymous_variant' ['synonymous_variant'] (each lists are on a new line, without any separators) Code: from collections import Counter file = open('/home/becquart/Stagiaire_refinement_construct_peptides/Travail5/RE__[Allogenomics]_travail_Vcf/results.txt', 'r').read() for char in '""-.,\n[]': file = file.replace(char,' ') for i in char: file = file.replace('""', ' ') file = file.lower() word_list = file.split() d = dict(Counter(word_list).most_common()) print d The output is something like: {"'coding_sequence_variant&amp;3_prime_utr_variant'": 6, "'inframe_insertion&amp;nmd_transcript_variant'": 17 etc. I would like to remove " from the keys, but I am having a hard time figuring it out as I'm very new in programming...I would be extremely happy if I could get this solved. Thank you in advance! Edit: Input file here: https://ufile.io/v1tm0
tagged with: collections
has comment: http://stackoverflow.com/comment/89044736
has comment: http://stackoverflow.com/comment/89044694
has title: Removing unecessary double quotes from keys in a dictionary - Python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89045377
tagged with: string
has comment: http://stackoverflow.com/comment/89044865
has comment: http://stackoverflow.com/comment/89045734

http://stackoverflow.com/q/51114826
has answer: http://stackoverflow.com/a/53088606
has answer: http://stackoverflow.com/a/57040866
tagged with: pycharm
tagged with: pip
has comment: http://stackoverflow.com/comment/89216095
possible better answer: http://stackoverflow.com/a/57040866
has title: Cannot import cv2 on PyCharm
has answer: http://stackoverflow.com/a/57258728
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89216132
has answer: http://stackoverflow.com/a/77240359
has comment: http://stackoverflow.com/comment/89215904
accepted answer: http://stackoverflow.com/a/53088606
type: Question
has comment: http://stackoverflow.com/comment/89215952
upvote count: 15
has comment: http://stackoverflow.com/comment/89216157
downvote count: 0
has comment: http://stackoverflow.com/comment/89216045
has comment: http://stackoverflow.com/comment/89216021
favorite count: 0
has comment: http://stackoverflow.com/comment/89215916
answer count: 5
has answer: http://stackoverflow.com/a/75819607
tagged with: python
has body: I am trying to import cv2 module in PyCharm, but it shows error. I tried in terminal as well pip install opencv-python pip3 install cv2 pip install opencv-python pip3 install cv2 and whatnot. Trying to install opencv-python from terminal shows this Requirement already satisfied: opencv-python in ./anaconda3/lib/python3.6/site-packages (3.4.1.15) and trying to install cv2 from terminal shows this Could not find a version that satisfies the requirement cv2 (from versions: ) No matching distribution found for cv2 However, trying to import cv2 on Pycharm shows this : Pycharm Error Image
score: 15

http://stackoverflow.com/q/51164683
has title: Django allauth - can I disable redirects after Social logins?
tagged with: django-allauth
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I would like to disable redirects after Social logins in django allauth, i.e. if a user is on page 'X' (and not logged in), then chooses to log in (via ajax request), they should remain on page 'X' (no reload/redirect etc.). This functionality would be similar to the normal Account setting, i.e. 'ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False' As far as I know there isn't a 'SOCIALACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS' setting available.
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89308194
score: 1
comment on: http://stackoverflow.com/a/51162314
type: AnswerComment
type: Comment
has text: Yeah, I know. It's a good answer, but I think it could be better by wording it a little better. (Obviously not the way I worded it in my comment, though, unless the OP is trying to write a Python implementation…)

http://stackoverflow.com/q/51159971
has answer: http://stackoverflow.com/a/51160128
has answer: http://stackoverflow.com/a/51160755
type: Question
has comment: http://stackoverflow.com/comment/89303543
has comment: http://stackoverflow.com/comment/89303404
tagged with: optimization
downvote count: 4
has answer: http://stackoverflow.com/a/51177673
accepted answer: http://stackoverflow.com/a/51160126
upvote count: 1
has body: Two lists are called similar if one can be obtained from another by swapping at most one pair of elements in one of the lists. I solved the problem, but I need to make it run in 4 seconds (Python3) for all inputs. Any ideas for making this more efficient? def areSimilar (a,b): counter=0 for i in range(len(a)): for j in range(len(b)): if counter &lt; 1 and a[i]!=b[i]: if a[i]==b[j]: temp=b[j] b[j]=b[i] b[i]=temp counter+=1 else: flag=False if a == b: flag=True else: flag = False return flag a= [832, 998, 148, 570, 533, 561, 894, 147, 455, 279] b= [832, 998, 148, 570, 533, 561, 455, 147, 894, 279] p=areSimilar(a,b) I think the nested loops are my problem.
possible better answer: http://stackoverflow.com/a/51160128
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89303440
has comment: http://stackoverflow.com/comment/89303447
has answer: http://stackoverflow.com/a/51160126
answer count: 5
score: -3
has answer: http://stackoverflow.com/a/51160178
tagged with: python
has title: Idenitifying "similar lists" for CodeFights challenge
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89303443
has comment: http://stackoverflow.com/comment/89303459
has comment: http://stackoverflow.com/comment/89303390

http://stackoverflow.com/comment/89112028
type: QuestionComment
comment on: http://stackoverflow.com/q/51059005
has text: This error is not about gcc, it is saying that specific MySQL header file is not found. You need to install mysql-devel or mariadb-devel package.
score: 0
type: Comment

http://stackoverflow.com/q/51055495
tagged with: paragraph
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51056426
tagged with: java
has body: I want to create a program such that if I have inserted a paragraph in a text area, I want certain parts of it to be put in the table in different columns. For example the statement is: My name is James Olson. I am 21 years old. I am a doctor. I live in Canterville, Bacon Street, London. Then the table should automatically look like: | Name | Age | Profession | Area Name | Street Name | Area | James | 21 | Doctor | Canterville | Bacon Street | London | I also want to know which language would go the best - Python or Java.
type: Question
answer count: 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51056426
tagged with: jtable
has title: Paragraph to Table in Different Columns
tagged with: python
favorite count: 0

http://stackoverflow.com/q/51036105
has comment: http://stackoverflow.com/comment/89611244
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89064564
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89063988
downvote count: 0
has body: {"summary": {"MemberID":"73164", "JoinDate":"2017-05-23", "class":"15-05", "status":"Registered", "confirmedDate":"2017-05-26", "referral":null, "renewalDate":"2020-05-23", }, "member": [{"memberCode":"njdskadh", "name":"masked", "address":"masked", "country": {"code":"JP", "description":"Japan"}, }], "license":null, "Interest":null, "documents": [{"fileDate":"2017-05-23", "fileId":"dkasdh7482121", "fileName":"dajkgdh.jpg", "fileUrl":"https://mask.api/file/dajkgdh", "docType":{"code":"hsjas","description":"Images"}}, {"fileDate":"2017-07-23", "fileId":"dkasdh74823473841", "fileName":"FFG.txt", "fileUrl":"https://mask.api/file/FFG", "docType":{"code":"hsjas","description":"text"}}]} Above is a truncated and anonymized version of the return value i got from calling an API. It is in the format of a dictionary of nested dictionaries and list. I would need to somehow extract the information into excel, grouped into headers (e.g. summary, member, license) and subheaders (e.g. MemberID, JoinDate) which each of these headers have. Oddly, there are certain fields (e.g. member) where the return value seems to be a list of dictionary. I am wondering if i should clean up the [ ] first as well. Another problem is also the documents header, where there are multiple documents with the same subheaders. The ultimate goal is to run a loop and append subsequent return values from the API call onto this master list. I am not very certain if headers, subheaders is the correct thinking or should i be doing separate sheets and headers instead (in this case i would need MemberID from the first sheet as an index identifier). Thank you. How the excel looks like
favorite count: 0
tagged with: python
has title: python - Splitting nested dictionary for export into excel with subheaders

http://stackoverflow.com/q/51095085
tagged with: datetime
downvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51095319
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51095114
accepted answer: http://stackoverflow.com/a/51095114
linked to: http://stackoverflow.com/q/19350806
possible better answer: http://stackoverflow.com/a/51095319
type: Question
answer count: 2
has body: I have a df like this: Sr. lwd_month lwd_year 1 3 2015 2 6 2018 3. 9 2017 4. NaN NaN 5. 5 2015 How can I merge this two columns to get dataframe like below?: Sr. lwd_month lwd_Year MonthYear 1 3 2015 03-2015 2 6 2018 06-2018 3. 9 2017 09-2017 4. NaN NaN NaT 5. 5 2015 05-2015 6. 3 NaN NaT Thanks
score: 0
tagged with: pandas
has title: How to merge month and year columns to get single mm-yyyy column?
upvote count: 1

http://stackoverflow.com/a/53382823
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51118565
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51118565
has body: This issue is addressed in the tf.data user guide (https://www.tensorflow.org/guide/datasets) in "Consuming NumPy arrays" section. Basically, create a dataset.make_initializable_iterator() iterator and feed your data at runtime. If this does not work for some reason, you can write your data to files or create a dataset from Python generator (https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator), where you can put arbitrary Python code including slicing your numpy array and yielding the slice.
score: 4

http://stackoverflow.com/comment/89052514
score: 1
comment on: http://stackoverflow.com/q/51030131
type: Comment
has text: Please post the text content of the error instead of images.
type: QuestionComment

http://stackoverflow.com/comment/89155556
has text: @deceze is it really necessary to embed a small stack-based language (Forth) inside a simple class just to save a few lines? :)
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51083555

keystroke
type: Tag
tags question: http://stackoverflow.com/q/51093710
tag name: keystroke

http://stackoverflow.com/q/51015662
tagged with: imshow
tagged with: rgb
tagged with: image
has answer: http://stackoverflow.com/a/75292988
accepted answer: http://stackoverflow.com/a/51099648
answer count: 2
has title: How do I display a TIFF image in Bokeh?
linked to: http://stackoverflow.com/q/7569553
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51099648
has comment: http://stackoverflow.com/comment/89155360
has body: I can load a TIFF image into memory as a NumPy array where each pixel is represented by a 3-element RGB vector: from PIL import Image import numpy as np arr=np.array(Image.open(imgfn)) For example the arr above might have shape (2469,2858,3). Follow the Bokeh docs, in Bokeh, pixels are 1D numbers that are interpreted with respect to a color map. How do I map my 3D RGB TIFF array into a 1D Bokeh colormap index array, and what colormap should I use? This post suggest I should write something called an RGBAColorMapper. How do I do that? There is also something call image_rgba which is a 4D pixel, how would I translate 3D pixels to 4D to use that? Basically I'm looking for the same functionality as MatPlotLib imshow.
tagged with: python
possible better answer: http://stackoverflow.com/a/75292988
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89157911
upvote count: 3
tagged with: bokeh
type: Question

http://stackoverflow.com/q/51157237
tagged with: python
has comment: http://stackoverflow.com/comment/89298022
tagged with: sms
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Twilio SMS Response - Python Quickstart Guide - 404 Not Found
has body: Following the Twilio SMS Python Quickstart guide found here: https://www.twilio.com/docs/sms/quickstart/python I can get up to the "Receive and reply to inbound SMS messages with Flask" section perfectly fine, with both my http://localhost:5000/ and ngrok URL showing the correct "Hello World" message. However, as soon as I replace the run.py file code with the instructed code to reply to the sender with an sms, both URLs become dead with a "404 Not Found" error. Have tried restarting everything etc. run.py: # /usr/bin/env python # Download the twilio-python library from twilio.com/docs/libraries/python from flask import Flask, request from twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/sms", methods=['GET', 'POST']) def sms_ahoy_reply(): """Respond to incoming messages with a friendly SMS.""" # Start our response resp = MessagingResponse() # Add a message resp.message("Ahoy! Thanks so much for your message.") return str(resp) if __name__ == "__main__": app.run(debug=True) Any ideas? As soon as I change the run.py code back to the original "Hello World" code both URLs run fine. Also, the ngrok server does show an attempted connection when I send an sms message to the twilio number too, but with a "404 Not Found" message next to it.
downvote count: 1
tagged with: http
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89297930
tagged with: flask
favorite count: 0
tagged with: twilio

http://stackoverflow.com/q/51098782
answer count: 1
tagged with: url
has comment: http://stackoverflow.com/comment/89185031
accepted answer: http://stackoverflow.com/a/51099037
favorite count: 0
linked to: http://stackoverflow.com/q/43423203
score: 0
has comment: http://stackoverflow.com/comment/89185149
has comment: http://stackoverflow.com/comment/89185070
tagged with: python
has title: Is it possible to check if a certain url is redericting without opening a request to the site in Python?
has body: I know that it is possible to check if a URL redirects, as mentioned in the following question and its answer. How to check if the url redirect to another url using Python using the following code: eq = urllib2.Request(url=url, headers=headers) resp = urllib2.urlopen(req, timeout=3) redirected = resp.geturl() != url # redirected will be a boolean True/False However, I have list of Millions of URLs. Currently it is discussed wether one of them is a harmful URL or redirects to a harmful URL. I want to know if it is possible to check for redirect without opening a direct connection to the redirecting website to avoid creating a connection with a harmful website?
tagged with: http-redirect
has comment: http://stackoverflow.com/comment/89185445
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89185135
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51099037
linked to: http://stackoverflow.com/q/110498
has comment: http://stackoverflow.com/comment/89185205
duplicate of: http://stackoverflow.com/q/110498
type: Question
has comment: http://stackoverflow.com/comment/89185154

http://stackoverflow.com/comment/89027311
score: 0
type: AnswerComment
has text: Thanks for the valuable comment. Is there any other testing built-in-functions available rather than equality checking in pandas?
comment on: http://stackoverflow.com/a/51017270
type: Comment

http://stackoverflow.com/a/51033314
has comment: http://stackoverflow.com/comment/89058838
has body: pop() takes an int value but random.choice(deck1) returns an element of deck1 which is a str. One way to fix this is by choosing a random index of deck1 to pull value out of: deck1.pop(random.randint(0,len(deck1)-1)) where random.randint(0,len(deck1)-1) returns a random index of deck1.
score: 0
answers question: http://stackoverflow.com/q/51033212
type: Answer

http://stackoverflow.com/q/51075535
has comment: http://stackoverflow.com/comment/89155309
answer count: 1
has title: Interactive Windows Service?
tagged with: service
tagged with: windows
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: ctypes
has answer: http://stackoverflow.com/a/51075946
accepted answer: http://stackoverflow.com/a/51075946
has body: I created a Windows Service in Python and tried to get the current window by GetForegroundWindow() from ctypes. To check if the PC is locked ( GetForegroundWindow() == when the PC is locked, works fine in a normal Python Skript) Apparently the Service has to be a "Interactive Service" to recognize the current Window. So the question is: Is there a way to start the Service as a Interactive Service ? The Windows Service is structured like this (I deleted some parts of the code so the post isnt that long): class Service(win32serviceutil.ServiceFramework): _svc_name_ = "Service" _svc_display_name_ = "Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Tell ReportServiceStatus we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, waitHint=10000) # And set stop event. win32event.SetEvent(self.hWaitStop) def GetAcceptedControls(self): result = win32serviceutil.ServiceFramework.GetAcceptedControls(self) result |= win32service.SERVICE_ACCEPT_PRESHUTDOWN return result def SvcOtherEx(self, control, event_type, data): if control == win32service.SERVICE_CONTROL_PRESHUTDOWN: #_log('received a pre-shutdown notification') self.SvcStop() def SvcDoRun(self): user32 = ctypes.windll.User32 #Do Something while True: time.sleep(1) print(str(user32.GetForegroundWindow())) # Wait until the Service is stopped win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
score: 0

http://stackoverflow.com/comment/89153657
has text: Do other modules installed the same way work for you?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51082504

http://stackoverflow.com/q/51139822
has comment: http://stackoverflow.com/comment/89320640
tagged with: python-2.7
downvote count: 0
has comment: http://stackoverflow.com/comment/89320444
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89282264
tagged with: python
has body: I am using openCV to train the data sets for face recognition. I have 3 pictures for as my training sets. Everything in the code works fine until I execute the code to train. cv2.error: OpenCV(3.4.1) C:\projects\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:359: error: (-210) Empty training data was given. You'll need more than one sample to learn a model. in function cv::face::LBPH::train Point to be noted that the path mentioned in the error doesn't even exist on my machine. I have two python files, one is created to just see a persons face on webcam and save it on some location. Below is the code:- import cv2 import numpy as np face_cascade = cv2.CascadeClassifier('data\haarcascade_frontalface_alt2.xml') cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) for (x, y, w, h) in faces: print(x, y, w, h) roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w] img_item = "amitesh2.png" color = (255, 0, 0) stroke = 2 width = x+w height = y+h rect = cv2.rectangle(frame, (x, y),(width, height), color, stroke) cv2.imwrite(img_item, roi_gray) cv2.imshow('test', frame) if cv2.waitKey(20) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() The above code is working as per the requirement. The problem is with the below code that is training and recognizing the face. import os import numpy as np import cv2 import pickle from PIL import Image face_cascade = cv2.CascadeClassifier('data\haarcascade_frontalface_alt2.xml') print(face_cascade) recog = cv2.face.LBPHFaceRecognizer_create() BASE_DIR = os.path.dirname(os.path.abspath(__file__)) img_dir = os.path.join(BASE_DIR, "images") curr_id = 0 label_ids = {} x_train = [] y_label = [] for root, dirs, files in os.walk(img_dir): for fil in files: if fil.endswith("png") or fil.endswith("jpg"): path = os.path.join(root, fil) label = os.path.basename(os.path.dirname(root…
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89264350
has comment: http://stackoverflow.com/comment/89277520
type: Question
tagged with: opencv
has title: why the openCV face recognition not able to find the training sets?

http://stackoverflow.com/comment/89171436
type: QuestionComment
comment on: http://stackoverflow.com/q/51091466
score: 0
has text: Thanks everyone, I got an answer so quickly! I see my mistake now. List comprehensions come later in the textbook.
type: Comment

http://stackoverflow.com/comment/89169067
comment on: http://stackoverflow.com/a/51051536
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173986/discussion-between-jasonpy-and-bowlinghawk95).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51066740
score: 0
tagged with: api
has title: Unable to find client_secret.json with Google Calendar API in python
type: UnansweredQuestion
tagged with: google-calendar-api
tagged with: python
has comment: http://stackoverflow.com/comment/89162092
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89136345
has comment: http://stackoverflow.com/comment/89153843
has body: I followed the instructions on this website to quick start with google Calendar API with python. I had no problem with the steps 1 to 3, I generated a json document from the google API website and copied it in my working directory along with the python file quickstart.py but when I try to run the program from the windows console I get this error: oauth2client.clientsecrets.InvalidClientSecretsError: ('Error opening file', 'client_secret.json', 'No such file or directory', 2) I don't understand where to place the file client_secret.json for it to be recognized. If you have any idea that could help me please share ! Thank you :)

http://stackoverflow.com/comment/89054248
comment on: http://stackoverflow.com/q/51030955
has text: Possible duplicate of [How to filter rows in pandas by regex](https://stackoverflow.com/questions/15325182/how-to-filter-rows-in-pandas-by-regex)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51105710
linked to: http://stackoverflow.com/q/16258290
has answer: http://stackoverflow.com/a/51105742
has answer: http://stackoverflow.com/a/73011445
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/38617046
tagged with: environment-variables
tagged with: python-3.x
has body: Summary: My site is running in DEBUG mode even though settings are set to DEBUG = False. FYI, I've researched this and found some excellent responses and testing ideas in these related questions (none of which helped, even though logically they SHOULD have): django DEBUG=False still runs in debug mode and Heroku Django DEBUG Setting not applied IIS FastCGIHandler environmental variable: Name = DJANGO_DEBUG Value = False Note: Removing this environmental variable causes a 500 error regardless of setting in production.py. settings/production.py: Different scenarios tried in settings/production.py using env variable set to False in my FastCGIHandler: DEBUG = os.environ.get('DJANGO_DEBUG', False) RESULT: Site runs in Debug Mode DEBUG = bool(os.environ.get('DJANGO_DEBUG', False)) RESULT: Site runs in Debug Mode DEBUG = False (hardcode w/o env var) RESULT: Site doesn't work, returns 500 page and error tracking gives ValueError: Missing staticfiles manifest entry for 'images/favicon/manifest.json' which is a very bizarre and misleading error. Other actions taken: I've checked both the base.py and production.py files for any other references to DEBUG or to the DJANGO_SETTINGS variable and they are clear. I also searched other .py files that the IIS server interacts with (wsgi.py, manage.py). I have even tried setting DEBUG = False in the base.py file as well with the same results. I installed python-decouple and tried using that. I installed django-environ and tried using that (I have another django site running on this server using django-environ to access the environmental variables which works fine.) I've never seen anything like this. The other environmental variables are working fine so it seems to be around this Boolean value. And why wouldn't hardcoding the DEBUG variable in the python settings work??? Any help in figuring out where to look next would be appreciated.
has title: Django DEBUG weirdness in IIS: DEBUG=False still runs in debug mode
type: UnansweredQuestion
tagged with: django
tagged with: python
type: Question

http://stackoverflow.com/a/65709704
type: Answer
upvote count: 0
score: -1
downvote count: 1
has body: discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing. The reason your getting this is because you need to define ctx.
answers question: http://stackoverflow.com/q/51166800

http://stackoverflow.com/q/51114887
answer count: 1
has body: I have an object that looks like this: a - ['A', 'B', 'C'] b - ['A', 'B', 'C'] c - ['A', 'B', 'C', 'D'] d - ['A', 'B', 'C', 'D'] each one of the keys has a number of available options as denoted by the list (e.g. a can choose between A, B, C and so on). I want to find a combination of pairs that will satisfy everyone. This could be: # Chosen Remaining Available Options ------------------------------------------ a - B - ['A', 'B', 'C'] - ['A', 'B', 'C'] b - A - ['A', 'C'] - ['A', 'B', 'C'] c - D - ['C', 'D'] - ['A', 'B', 'C', 'D'] d - C - ['C'] - ['A', 'B', 'C', 'D'] So in the example above a chose item B, reducing the pool of available options for the remaining participants. b then chose item A, and so on. I do this by looping through all participants based on how big is the pool of their available choices, the idea being that if I have a participant that wants only one item, then there is no choice but to give him that item, removing it from the pool. import random team_choices = {'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C'], 'c': ['A', 'B', 'C', 'D'], 'd': ['A', 'B', 'C', 'D']} teams_already_created = [] for team_b in sorted(team_choices, key=team_choices.__getitem__, reverse=False): available_opponents = [opponent for opponent in team_choices[team_b] if opponent not in teams_already_created] chosen_opponent = random.choice(available_opponents) teams_already_created.append(chosen_opponent) The way I do it though will not always work well since there is no guarantee that at some point it will make a choice that will at a later point choke some other player, leaving him no available options. And if chosen_opponent is empty then obviously this will fail. Is there a better way of doing this that will work everytime?
tagged with: algorithm
has title: Find viable combination from a list of preferences
upvote count: 5
tagged with: sorting
type: AnsweredQuestion
downvote count: 0
tagged with: permutation
has answer: http://stackoverflow.com/a/51115773
favorite count: 0
tagged with: python-3.x
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/51115773
tagged with: python

http://stackoverflow.com/q/51108063
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89205155
type: Question
has comment: http://stackoverflow.com/comment/89203366
possible better answer: http://stackoverflow.com/a/51108206
has answer: http://stackoverflow.com/a/51108214
accepted answer: http://stackoverflow.com/a/51108214
tagged with: inheritance
tagged with: class
has answer: http://stackoverflow.com/a/51108180
score: 0
answer count: 3
tagged with: pandas
has body: I'm looking to extend a Panda's DataFrame, creating an object where all of the original DataFrame attributes/methods are in tact, while making a few new attributes/methods available. I also need the ability to convert (or copy) objects that are already DataFrames to my new class. What I have seems to work, but I feel like I might have violated some fundamental convention. Is this the proper way of doing this, or should I even be doing it in the first place? import pandas as pd class DataFrame(pd.DataFrame): def __init__(self, df): df.__class__ = DataFrame # effectively 'cast' Pandas DataFrame as my own the idea being I could then initialize it directly from a Pandas DataFrame, e.g.: df = DataFrame(pd.read_csv(path))
has title: Proper way to extend Python class
has answer: http://stackoverflow.com/a/51108206

http://stackoverflow.com/comment/89206282
type: AnswerComment
type: Comment
has text: @ManishGadhock That's odd. It might be python code compiled with some sort of py2exe just in elf. Maybe cx_freeze?
comment on: http://stackoverflow.com/a/51109466
score: 0

http://stackoverflow.com/comment/89224144
has text: I tried the development header: https://dev.mysql.com/downloads/installer/
comment on: http://stackoverflow.com/q/51118963
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51137899
downvote count: 0
has comment: http://stackoverflow.com/comment/89280692
answers question: http://stackoverflow.com/q/51137594
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89280670
score: 2
has body: I think if need better performance, use itertools.groupby with unique for return lists in same ordering as original data. If order is not important use set: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}).set_index(['F','B', 'A']) print (df) C D E F B A a 4 a 7 1 5 5 b 8 3 3 4 c 9 5 6 b 5 d 4 7 9 e 2 1 2 4 f 3 0 4 from itertools import groupby from operator import itemgetter a = {k: list(set(list(zip(*g))[1])) for k, g in groupby(df.index.values.tolist(), itemgetter(0))} print (a) {'a': [4, 5], 'b': [5, 4]} Another pandas solution: d = df.reset_index().drop_duplicates(['F','B']).groupby('F')['B'].apply(list).to_dict() print (d) {'a': [4, 5], 'b': [5, 4]}

http://stackoverflow.com/q/51145486
has title: Python - How to convert Unicode code point to the character
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
has body: I'm trying to convert english character into Star Wars Aurebesh characters. I found the unicode code assignment for Aurebesh characters here: http://www.kreativekorp.com/ucsur/charts/aurebesh.htm So with code point such as "U+E890", can I print out the Aurebesh character in python?
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89275263
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/51145499
has answer: http://stackoverflow.com/a/51145517

http://stackoverflow.com/comment/89305796
type: QuestionComment
has text: Ive updated my post with the json info. here is what Im getting from debug: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
score: 0
comment on: http://stackoverflow.com/q/51159303
type: Comment

http://stackoverflow.com/comment/89243708
type: QuestionComment
comment on: http://stackoverflow.com/q/51129269
score: 0
has text: Hi @ZdaR. The headlight is merged with car itself. You can check the second and third image in the post. The headlight is not seperated.
type: Comment

http://stackoverflow.com/comment/89133687
type: QuestionComment
has text: https://mailchimp.com/help/css-in-html-email/
type: Comment
comment on: http://stackoverflow.com/q/51071923
score: 0

http://stackoverflow.com/q/51108884
has body: Our team is a small group of data analysts doing report development in a variety of languages including mostly SAS and Python. We are limited in what we can install. As such, we don't have a formalized version control system in place but can manually handle version controls, forking, merging, etc. since we typically manage our own scripts from start to finish. Now, however, I am working in parallel with a new member of the team and finding it increasingly challenging to manage different versions. I am looking for a simple way, using Python (3.6 via Anaconda) or Windows (7 or 10), to find the line-by-line differences between two files. I want to see the contents of both files with the differences highlighted. The files are stored in a shared folder and will get updated by multiple people in parallel, but as mentioned, there is no formal version control system. I know there are other utilities to install, and I know I could create something on my own, but I want something that doesn't need to be installed and doesn't need to be a custom utility.
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51108972
score: 0
has comment: http://stackoverflow.com/comment/89204962
answer count: 1
has title: How do I find and highlight differences between two text files?
accepted answer: http://stackoverflow.com/a/51108972
has comment: http://stackoverflow.com/comment/89205015
has comment: http://stackoverflow.com/comment/89205359
tagged with: sas
type: AnsweredQuestion

http://stackoverflow.com/comment/89168894
score: 1
has text: Thank you, I tried it and worked. Basically I had not prescribed the right axis.
type: AnswerComment
comment on: http://stackoverflow.com/a/51087920
type: Comment

http://stackoverflow.com/q/51111267
answer count: 2
tagged with: currency
tagged with: python
has title: Money Tax and Tip Float Complication
type: AnsweredQuestion
tagged with: raw-input
has answer: http://stackoverflow.com/a/51111282
score: 0
has body: I am making a program to find the taxed amount of money and combine that with the tip. I am working on the tipped amount and intro. Code: print "Welcome \nEnter The Amount Of Money For the Transaction" amount = raw_input print "Taxed Amount Below\n" taxed = (amount * float((1.065))) print taxed And this is what I get out: &gt;&gt;&gt; runfile('/home/meyer/.spyder2/temp.py', wdir='/home/meyer/.spyder2') Welcome Enter The Amount Of Money For the Transaction Taxed Amount Below Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile builtins.execfile(filename, *where) File "/home/meyer/.spyder2/temp.py", line 8, in &lt;module&gt; taxed = (amount * float((1.065))) TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'float' &gt;&gt;&gt; I know that I cant multiply by this float, but I cant find any other way. Even MPMath I am using python 2.7 Thanks In Advance!
type: Question
possible better answer: http://stackoverflow.com/a/51111284
accepted answer: http://stackoverflow.com/a/51111282
has comment: http://stackoverflow.com/comment/89209563
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51111284

http://stackoverflow.com/q/51106497
has body: When using this code import bitstring f = 1.0e+00 b = bitstring.pack('&gt;d', f) b.bin I get 64 bits 001111111111000000000000000000000000000000000000000000000000000 But I need to get Float (IEEE754 Single precision 32-bit) What is the &gt;d used for?
type: Question
tagged with: ieee-754
has comment: http://stackoverflow.com/comment/89212789
tagged with: type-conversion
score: 1
has title: Float number to 32 bits IEEE754 single precision is 64 bits
favorite count: 0
tagged with: binary
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16444726
tagged with: python
duplicate of: http://stackoverflow.com/q/16444726
answer count: 0
upvote count: 2
tagged with: bitstring
downvote count: 1

http://stackoverflow.com/comment/89114851
has text: It throws at "mrec.save()". But I assume the error is caused by the datetime field since the typeError happens while parsing the datetime
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51062461
type: Comment

http://stackoverflow.com/comment/89291815
type: Comment
has text: or try put double quotes at $gt and $lt
score: 0
comment on: http://stackoverflow.com/a/51154045
type: AnswerComment

http://stackoverflow.com/q/51020992
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: list
has body: I want to convert the 2nd Value in each list to integers, to then be increased by 1. This is an abstraction of a different code I am programming, but stuck on how to do it efficiently and keep getting errors. This will hopefully lead to 4 becoming 5, 16 to 17, and 7 to 8. listp=[["3","4"], ["7","16"], ["3","7"]] listp = list(map(int, listp[x][1])) length = len(listp)-1 i=0 for i in range(0, length): num=listp[i] num=num+1 listp[i]=num i=i+1 print (listp)
type: Question
has answer: http://stackoverflow.com/a/51021270
has title: Python:Converting specific elements in 2D array from string to integer permanently
score: -1
accepted answer: http://stackoverflow.com/a/51021219
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/89034649
favorite count: 0
has answer: http://stackoverflow.com/a/51021219
possible better answer: http://stackoverflow.com/a/51021270

http://stackoverflow.com/comment/92119267
type: AnswerComment
has text: Sorry for delay, yes creating using web interface is not an issue. It was more of an REST API question in fact.
comment on: http://stackoverflow.com/a/51334058
type: Comment
score: 0

http://stackoverflow.com/comment/89162823
score: 0
comment on: http://stackoverflow.com/q/51071365
type: QuestionComment
has text: If I just take the file `df` and run `grouped = df.groupby(['ID', 'Hour']) grouped.groups` this is the result `{(0, 16): Int64Index([5, 14, 16, 55, 130], dtype='int64'), (0, 17): Int64Index([7, 27, 126, 141, 185, 235], dtype='int64'),...` Except now I dont have the coordinates and I dont know how to convert the points to lines? Maybe I could index each position to get their xy then convert?
type: Comment

http://stackoverflow.com/a/51133041
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89250799
has comment: http://stackoverflow.com/comment/89252610
answers question: http://stackoverflow.com/q/51132454
has body: def distribute(number, bucket): if bucket == 1: yield [number] if number != 0: yield [-1 * number] elif number == 0: yield [0]*bucket else: for i in range(number+1): for j in distribute(number-i, 1): for k in distribute(i, bucket-1): yield j+k def generate(possibles, desired, distance): for index_distance_tuple in distribute(distance, len(desired)): retval = desired[:] for i, index in enumerate(index_distance_tuple): if index + i &lt; 0 or index + i &gt;= len(possibles): break retval[i] = possibles[index + i] else: yield retval For distance 1: for i in generate(possibles, desired, 1): print(i) Output : [30, 30, 40] [20, 40, 40] [20, 20, 40] [20, 30, 50] [20, 30, 30] For distance 2 : for i in generate(possibles, desired, 2): print(i) Output : [40, 30, 40] [30, 40, 40] [30, 20, 40] [30, 30, 50] [30, 30, 30] [20, 50, 40] [20, 40, 50] [20, 40, 30] [20, 20, 50] [20, 20, 30] [20, 30, 60] [20, 30, 20]
has comment: http://stackoverflow.com/comment/89250922
downvote count: 0
score: 1

http://stackoverflow.com/comment/89452278
type: Comment
has text: So i just replaced my `client` with `bot` in terms of code, However the code still doesn't work. My other commands work just fine but for some reason the bot won't give me errors about the code and nor it responds to me.
comment on: http://stackoverflow.com/a/51119889
type: AnswerComment
score: 0

http://stackoverflow.com/a/51043919
upvote count: 0
has comment: http://stackoverflow.com/comment/89079394
type: Answer
has comment: http://stackoverflow.com/comment/89080936
has body: If I clearly understand you question, you can try to slice the array into the shape you want in your self._parse_xxx_data function.
answers question: http://stackoverflow.com/q/51043703
downvote count: 1
has comment: http://stackoverflow.com/comment/89081162
score: -1

http://stackoverflow.com/a/61243194
has body: I've had the same issue. I simply downloaded python-64 installer and installed on my machine and choosed 64bit as interperter. I didn't understand why 32bit python doesn't work here. I hope this might be helpful.
type: Answer
has comment: http://stackoverflow.com/comment/108345139
score: 0
answers question: http://stackoverflow.com/q/51118963

featuretools
tag name: featuretools
tags question: http://stackoverflow.com/q/51028233
type: Tag

http://stackoverflow.com/q/51066916
tagged with: python
has comment: http://stackoverflow.com/comment/89123846
score: 0
linked to: http://stackoverflow.com/q/26720596
has comment: http://stackoverflow.com/comment/89123748
duplicate of: http://stackoverflow.com/q/26720596
has comment: http://stackoverflow.com/comment/89123725
type: UnansweredQuestion
has title: Why does it skip the 'if' statements in my python 3.x code for a simple RockPaperScissors?
tagged with: python-2.7
answer count: 0
has body: from random import randint print('''Choose one:1.Rock 2.Paper 3.Scissors ''') userChoice = input(Choose one:1.Rock, 2.Paper, 3.Scissors.) computerChoice=randint(1,3) if userChoice==1 : print("your choice is Rock.", end='') if computerChoice==2 : print("but computer chose Paper. XD. You lose!") elif computerChoice==1 : print("Here. Take another one. Hope you make some fire!(If you didn't get it, it's a draw!)") else : ("You're better than a machine (for now). You win! XO") elif userChoice==2: print("your choice is: Paper.", end ='') if computerChoice==2: print("and please stop mimicking the system. It's a Draw.") elif computerChoice==1: print(" Victorious! Poor system chose a Rock apparently.") else : ("Hehe! my scissors have torn your paper. XD") elif userChoice==3: print("your choice is:Scissors.", end='') if(computerChoice == 2): print("You've cut some virtual paper eventually. You did it! yay!") elif(computerChoice == 1): print("Wrong choice. Your scissors are blunted by y rock Loser!") else : ("Apparently you're mocking the computer :(. Why did you both choose the same") else : print("I didn't give you any such choice.")
type: Question

http://stackoverflow.com/q/51097463
score: 1
tagged with: stemming
upvote count: 1
answer count: 1
has body: I'm dealing with some nlp tasks. My inputs are french text and so, only Snowball Stemmer is usable in my context. But, unfortunately, it keeps giving me poor stems as it wouldn't remove even plural "s" or silent e. Below is some example: from nltk.stem import SnowballStemmer SnowballStemmer("french").stem("pommes, noisettes dorées &amp; moelleuses, la boîte de 350g") Output: 'pommes, noisettes dorées &amp; moelleuses, la boîte de 350g'
favorite count: 0
tagged with: french
accepted answer: http://stackoverflow.com/a/51107197
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89231232
has answer: http://stackoverflow.com/a/51107197
type: Question
tagged with: snowball
has title: Snowball Stemmer : poor french stemming
has comment: http://stackoverflow.com/comment/89201319
tagged with: nltk

http://stackoverflow.com/comment/114247532
type: AnswerComment
has text: @bad_coder Gracias, lo acabo de ver. Lo tengo que estudiar más despacio, pero dado que genero los rst de forma automática no creo que me resultw práctico tener que añadir excepciones para cada dataclass
type: Comment
comment on: http://stackoverflow.com/a/51131941
score: 0

http://stackoverflow.com/a/51134414
type: Answer
has body: SublimeLinter's settings file now contains a message template parameter which defaults to showing only the error message, documented as follows in the default settings file: // Show the messages for problems at your cursor position. // - {message} will be replaced by the actual messages. // - {linter} will be replaced by the linter reporting the error. // - {type} will be replaced by either warning or error. // - {code} will be replaced by the error code. // Set to "" to display nothing "statusbar.messages_template": "{message}", To show error codes, then, you need to: Open the SublimeLinter settings file. (On Sublime Text 3 on a Mac, I can access this via Sublime Text -> Preferences -> Package Settings -> Sublime Linter -> Settings; the menus will be slightly different in different environments.) In the "User" settings in the right-hand-pane of the split window that opens, add a "statusbar.messages_template" parameter that contains a {code} placeholder. For example, I use "{type} {code}: {message}" as my template: Save, and the messages shown in the status bar by SublimeLinter will henceforth contain the error code:
downvote count: 0
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51085060
accepted answer of: http://stackoverflow.com/q/51085060

http://stackoverflow.com/q/51164445
tagged with: image
accepted answer: http://stackoverflow.com/a/51178804
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89312538
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89337054
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89337208
has answer: http://stackoverflow.com/a/51178804
has body: From the client's POST submission, we are successfully receiving an image in the following format, data:image/jpeg;base64,/9j/.... and an image file is being generated by the following code: @app.route('/submission', methods=('GET', 'POST')) def submission(): if request.method == 'POST': raw_image = request.form['file'] #Problem Starts Here # this doesn't work either: # raw_image = raw_image.replace("data:image/jpeg;base64,/9j/", ''); with open(UPLOADED_IMAGES_DEST+'/image.jpeg', 'wb') as fh: fh.write(base64.decodebytes(raw_image)) #Problem Ends Here return jsonify(request.form) return render_template('submission.html') However, the image cannot be opened as it's an "Invalid or Unsupported Format". I'm trying to improve the conversion process so it will produce a viewable JPEG image. Beginning of raw_image: [binary]...
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89337610
has title: Converting data:image from base64 to JPEG in Python
tagged with: base64

http://stackoverflow.com/comment/89473035
comment on: http://stackoverflow.com/a/51107797
type: AnswerComment
has text: But I have seen some cases where this verification window appends inside the customers checkout page. any ideas ?
score: 0
type: Comment

http://stackoverflow.com/comment/119014328
has text: strange, that this highly actual question has so low upwotes.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51061358

http://stackoverflow.com/q/51139011
downvote count: 1
has body: I have a few quite large text files with data on them. I need to find a string that repeats from the data and the string will always have an id number after it. I will need to then save that number. Ive done some simple scripting with python but I am unsure where to start from with this or if python is even a good idea for this problem. Any help is appreciated.
type: Question
tagged with: find
score: -1
has title: Searching for a string in a file and saving the results
has comment: http://stackoverflow.com/comment/89262097
upvote count: 0
answer count: 1
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51142200
tagged with: save
tagged with: file
has comment: http://stackoverflow.com/comment/89265565
has comment: http://stackoverflow.com/comment/89262284

http://stackoverflow.com/a/51026683
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51026581
score: 1
has body: Use: df.name_id*=(df.groupby('name_id').name.transform(len)==1).map({True:-1,False:1}) df Out[50]: name_id name 0 -1 a 1 2 b 2 2 b 3 3 c 4 3 c 5 3 c

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51157237
tags question: http://stackoverflow.com/q/51109089
tags question: http://stackoverflow.com/q/51014182
type: Tag
tags question: http://stackoverflow.com/q/51145995

http://stackoverflow.com/q/51054497
downvote count: 0
accepted answer: http://stackoverflow.com/a/51054683
has comment: http://stackoverflow.com/comment/89099929
has comment: http://stackoverflow.com/comment/89100006
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89099859
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/75551423
has answer: http://stackoverflow.com/a/51054683
has title: Random value for each row in pandas data Frame
has comment: http://stackoverflow.com/comment/89099908
upvote count: 3
tagged with: random
tagged with: pandas
has comment: http://stackoverflow.com/comment/89099959
has body: Hi I have the following data frames: import numpy as np import pandas as pd df = pd.DataFrame() df['T1'] = ['A','B','C','D','E'] df['T2'] = ['G','H','I','J','K'] df['Match'] = df['T1'] +' Vs '+ df['T2'] Nsims = 5 df1 = pd.DataFrame((pd.np.tile(df,(Nsims,1)))) I created two new columns T1_point and T2_point by summing of five random numbers. when I do as follow: it gave me the same number for all rows. Ninit = 5 df1['T1_point'] = np.sum(np.random.uniform(size=Ninit)) df1['T2_point'] = np.sum(np.random.uniform(size=Ninit)) What I wanted to do is that I would like to get different values for each row by using random number. How could I do that? Thanks Zep.
favorite count: 0
has answer: http://stackoverflow.com/a/75551423
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89099968

http://stackoverflow.com/comment/89056969
has text: You cannot replace a line in a file unless the new line is exactly the same size as the one you're replacing. Usually you will read the entire file and write it back out with the line replaced.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51027738

http://stackoverflow.com/comment/97877432
has text: Not sure what' you meant by last comment. My point is that *try* / *except* ... statements are completely useless with crashes (e.g. *segfault*s), like this one appears to be. So surrounding the code in such a block will have no effect.
comment on: http://stackoverflow.com/a/51136818
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51106601
score: -1
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51106304
has body: You can use re.split to split on a combination of either a double quote before a comma or a comma followed by a digit import re data='"Hello, Hey",123,10.04' re.split(r'(?&lt;="),|,(?=\d)', data) ['"Hello, Hey"', '123', '10.04']

http://stackoverflow.com/q/51023435
has title: Get group of index values for word count more than 1
tagged with: dataframe
answer count: 2
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/51023491
tagged with: pandas
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/51023491
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51023678
has answer: http://stackoverflow.com/a/51023678
has body: I am trying to get index values along with that count of each word is more than 1 as list. Ref="easy to get to know to easy of to" With the Ref input I have this table say df1 word Count easy 2 to 4 get 1 know 1 of 1 And df is Index word 0 easy 1 to 2 get 3 to 4 know 5 to 6 easy 7 of 8 to So from these two table df and df1 what I want is Index word count [0,6] easy 2 [1,3,5,8] to 4 [2] get 1 [4] know 1 [7] of 1 It will be really great if someone help me with this.
type: Question

http://stackoverflow.com/q/51040358
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/46711557
tagged with: networkx
type: Question
has comment: http://stackoverflow.com/comment/89074857
linked to: http://stackoverflow.com/q/16417916
has body: I have three dictionaries where keys are the same, however the scales of these dictionaries vary significantly. I want to normalize/standardize the values of these dictionaries, so I can then sum them together to create an overall combined score for each key (with equal weights for the three different inputs). Current: page_score = {'andrew.lewis: 6.599', 'jack.redmond: 4.28'.....'geoff.storey: 2.345) eigen_score = {'andrew.lewis: 4.97', 'jack.redmond: 2.28'.....'geoff.storey: 3.927) (1 more) Normalized: page_score = {'andrew.lewis: 0.672', 'jack.redmond: 0.437'.....'geoff.storey: 0.276) hub_score = {'andrew.lewis: 0.432', 'jack.redmond: 0.762'.....'geoff.storey: 0.117) (1 more) End Output: overall_score = {'andrew.lewis: 2.738.....) """combination of values across the three standardized dictionaries""" How can I achieve this? I know how to do this for a list, however I'm not sure how to achieve this for a dictionary. I've tried the solutions provided here and here already, however strangely they created various errors. Any help would be appreciated. Code so far: G = nx.read_weighted_edgelist('Only_50_Employees1.csv', delimiter=',', create_using = nx.DiGraph(), nodetype=str) between_score = dict(nx.betweenness_centrality(G)) eigen_score = dict(nx.eigenvector_centrality(G)) page_score = nx.pagerank(G) Tried Already factor=1.0/sum(page_score.values()) normalised_d = {k: v*factor for k, v in page_score.items()} def normalize(page_score, target=1.0): raw = sum(page_score.values()) factor = target/raw return {key:value*factor for key,value in page_score.items()} def really_safe_normalise_in_place(page_score): factor=1.0/math.fsum(page_score.values()) for k in page_score: page_score[k] = page_score[k]*factor key_for_max = max(page_score.tems(), key=operator.itemgetter(1))[0] diff = 1.0 - math.fsum(page_score.values()) #print "discrepancy = " + str(diff) page_score[key_for_max] += diff d={v: v+1.0/v for v in xrange(1, 1000001)} really_safe_normalise_in_place(d) print math.…
accepted answer: http://stackoverflow.com/a/51042755
has comment: http://stackoverflow.com/comment/89072185
score: 0
has comment: http://stackoverflow.com/comment/89074141
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89074760
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89074083
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89074570
has answer: http://stackoverflow.com/a/51042755
has comment: http://stackoverflow.com/comment/89071862
has comment: http://stackoverflow.com/comment/89073079
has title: Python - normalize/standardize dictionary values

raspberry-pi3
tags question: http://stackoverflow.com/q/51130317
tags question: http://stackoverflow.com/q/51061898
tags question: http://stackoverflow.com/q/51085307
tags question: http://stackoverflow.com/q/51038364
tags question: http://stackoverflow.com/q/51108994
tags question: http://stackoverflow.com/q/51040303
tag name: raspberry-pi3
type: Tag
tags question: http://stackoverflow.com/q/51131983
tags question: http://stackoverflow.com/q/51097725

http://stackoverflow.com/q/51141635
tagged with: pandas
has comment: http://stackoverflow.com/comment/89267464
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has comment: http://stackoverflow.com/comment/89267668
answer count: 0
has comment: http://stackoverflow.com/comment/89267953
has title: Reference and create dataframes through loop
has body: I have many dataframes that are named the same except for a suffix. I need to perform the same operation on these dataframes and would like to streamline this process through a loop. I am trying to figure out how to reference the dataframes through a loop over the list of suffixes. For example, something along the lines of: for i in [a,b,c,d,e]: score_i=r2_score(df_i['col1'],df_i['col2'] and this would perform the same operation on all 5 dataframes and create 5 new variables. However, I'm not sure how to set this up without an error. Any advice would be appreciated - thanks!
type: Question
duplicate of: http://stackoverflow.com/q/1373164
score: 0

http://stackoverflow.com/q/51084617
has answer: http://stackoverflow.com/a/51086414
score: 0
tagged with: django
has body: Some confusion about static files (Python 3.6 Django 2.. IIS 8.5) My static files from site are found but the static files from the app are not found. GET http://127.0.0.1:81/static/css/pyapp.css 404 (Not Found) &lt;link rel="stylesheet" type="text/css" href="{% static 'css/pyapp.css' %}"&gt; I tried to add STATICFILES_DIRS =[(os.path.join(BASE_DIR, 'pyapp/static')),]"&lt; to the settings.py but did not help. Do I have to add a web.config also in the app static like in the site static folder? ├───pyapp │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───css | │ │ └───pyapp.css &lt;=== this is not found │ ├───templates │ │ └───pyapp | │ │ └───my.html &lt;=== this works │ └───__pycache__ └───pyweb ├───static &lt;=== this works │ └───admin │ ...... └───__pycache__ For IIS configuration i used this tutorial: http://blog.mattwoodward.com/2016/07/running-django-application-on-windows.html settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'pyapp.apps.PyappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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…
accepted answer: http://stackoverflow.com/a/51086414
has answer: http://stackoverflow.com/a/64273283
has comment: http://stackoverflow.com/comment/89157901
has title: Static Files from Site working, but not from app
has answer: http://stackoverflow.com/a/51086172
has comment: http://stackoverflow.com/comment/89158245
has answer: http://stackoverflow.com/a/51086123
possible better answer: http://stackoverflow.com/a/51084793
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51088103
has answer: http://stackoverflow.com/a/51084793
tagged with: iis-8.5
type: Question
has comment: http://stackoverflow.com/comment/89159840
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/89160304

http://stackoverflow.com/a/51105963
answers question: http://stackoverflow.com/q/51105887
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: Kivy already has an internal widget called Layout, which is subclassed all over the place. Try naming your own widget something else.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51105887

http://stackoverflow.com/a/51063055
downvote count: 1
has comment: http://stackoverflow.com/comment/109263651
has comment: http://stackoverflow.com/comment/94595607
answers question: http://stackoverflow.com/q/51061358
has body: I'd love to see this in official pipenv here. My suggestion would go to have this directory structure. ├── project └── requirements ├── dash │ ├── PipFile │ └── PipFile.lock ├── dev │ ├── PipFile │ └── PipFile.lock ├── jupyter │ ├── PipFile │ └── PipFile.lock └── test ├── PipFile └── PipFile.lock and based on what environment you need to work on, you can use after you know where is your virtual env using pipenv --venv or to use a custom venv location https://pipenv.kennethreitz.org/advanced/#custom-virtual-environment-location
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89140597
has comment: http://stackoverflow.com/comment/89141793
has comment: http://stackoverflow.com/comment/109306896
score: 1

http://stackoverflow.com/q/51015046
has body: so I got a Dataframe with at least 2-3 columns with numbers running from 1 to 3000, and the numbers have comma. I need to convert the numbers to float or int in all the relevant columns.this is an example for my Dataframe: data = pd.read_csv('exampleData.csv') data.head(10) Out[179]: Rank Total 1 2 20 40 1,200 1,400 NaN NaN as you can see from the example, my Dataframe consists of numbers, numbers with comma and some NaNs.I've read several posts here about converting to float or int, but I always get error messages such as: 'str' object has no attribute 'astype'. my approach is as follows for several columns: cols = ['Rank', 'Total'] data[cols] = data[cols].apply(lambda x: pd.to_numeric(x.astype(str) .str.replace(',',''), errors='coerce'))
tagged with: dataframe
has title: Error Converting Pandas Dataframe to float with comma
has answer: http://stackoverflow.com/a/51015098
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89022977
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89022870
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51015068
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51015068
has answer: http://stackoverflow.com/a/51015121
upvote count: 1
has comment: http://stackoverflow.com/comment/89048503
type: Question
accepted answer: http://stackoverflow.com/a/51015121

http://stackoverflow.com/a/51159613
downvote count: 0
score: 1
has body: The code displays correctly in a normal command line window. The problem is with Sublime's output window, which doesn't seem to be displaying the carriage return correctly (it replaces it with a newline).
upvote count: 1
answers question: http://stackoverflow.com/q/51159297
type: Answer

http://stackoverflow.com/comment/89028458
score: 0
comment on: http://stackoverflow.com/q/51016638
type: Comment
type: QuestionComment
has text: @jezrael Yes, apologies for not informing that before hand :)

http://stackoverflow.com/q/51164927
has comment: http://stackoverflow.com/comment/89315095
has comment: http://stackoverflow.com/comment/89317609
tagged with: tensorflow-datasets
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89316029
upvote count: 1
has comment: http://stackoverflow.com/comment/89316106
tagged with: tensorflow
has title: How can I output a list from TensorFlow Dataset map function?
type: Question
has comment: http://stackoverflow.com/comment/89452966
has body: I need examples in my dataset to be in the format ([feature_1, feature_2,...], labels) as I'm using Keras.Model.fit_generator. To do this, I'm going to read from .tfrecords: dataset = tf.data.TFRecordDataset(tf_records) dataset = dataset.map(map_func=parser, num_parallel_calls=num_parallel_calls) ... However, I'm having difficulty with the map_func: def parser(record, training=True): context_features = { "labels": tf.VarLenFeature(tf.int64) } sequence_features = { "feature_1": tf.FixedLenSequenceFeature([], dtype=tf.string), "feature_2": tf.FixedLenSequenceFeature([], dtype=tf.string) } context_parse, sequence_parsed = tf.parse_single_sequence_example(record, context_features, sequence_features) X_feature_1 = tf.decode_raw(sequence_parsed["feature_1"], tf.uint8) X_feature_2 = tf.decode_raw(sequence_parsed["feature_2"], tf.uint8) y = tf.sparse_to_dense(context_parse["labels"].values, [3862], 1) return ([X_feature_1, X_feature_2], y) If I try to use the list to hold [X_feature_1, X_feature_2] as above, I end up getting the following error: AttributeError: 'list' object has no attribute 'get_shape' How can I pass along a tuple that contains a list? Update (Workaround solution): So, the code in the question is part of a generator. I realized that since the generator just runs a tensorflow graph (hope the terminology is correct, I'm still new to this), I can do my conversion at the end instead: feature_1, feature_2, y = sess.run(next_el) yield [feature_1, feature_2], y Whilst this works, I still which I could do this in the map function.
has comment: http://stackoverflow.com/comment/89315012
downvote count: 0
score: 1

http://stackoverflow.com/a/51150852
answers question: http://stackoverflow.com/q/51150232
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Given an input list of column indices you wish to remove, you can remove these elements from a list of all indices. Simpler still, you can utilize set.difference to remove the necessary columns: foo[:, sorted(set(range(foo.shape[1])) - set([2, 4]))] To select specific rows or columns, you should not need to use numpy.delete. As you found, this is inefficient with NumPy.
accepted answer of: http://stackoverflow.com/q/51150232
type: Answer

http://stackoverflow.com/a/51080557
has comment: http://stackoverflow.com/comment/89150714
has comment: http://stackoverflow.com/comment/89190138
has body: List of machine groups per cloud account Something like this could help: cloud_accounts = [ {'cloud_account': 'a639efb6-d4e0-4929-b309-8171bf61b508', '_id': 'd0576830-df96-4411-ac33-4bac597f2010'}, {'cloud_account': 'a639efb6-d4e0-4929-b309-8171bf61b508', '_id': 'a650e642-ee41-4ab7-8ad1-797c7bdcd2aa'}, {'cloud_account': 'a639efb6-d4e0-4929-b309-8171bf61b508', '_id': 'c0a36d2e-f7dd-4d62-abe8-c26249e52520'}, {'cloud_account': 'fd4bbf86-9803-4724-9576-d83355bdcff2', '_id': '31140d2e-15a1-4203-bdbb-55c14cd6b83a'}] machine_groups_per_cloud_account = {d['cloud_account']: [] for d in cloud_accounts} for d in cloud_accounts: machine_groups_per_cloud_account[d['cloud_account']].append(d['_id']) import pprint pprint.pprint(machine_groups_per_cloud_account) Here is the output: {'a639efb6-d4e0-4929-b309-8171bf61b508': ['d0576830-df96-4411-ac33-4bac597f2010', 'a650e642-ee41-4ab7-8ad1-797c7bdcd2aa', 'c0a36d2e-f7dd-4d62-abe8-c26249e52520'], 'fd4bbf86-9803-4724-9576-d83355bdcff2': ['31140d2e-15a1-4203-bdbb-55c14cd6b83a']} In the result example you gave, you have multiple times the same keys in a dict, it is incorrect, so the idea here is to consider cloud_account as python dict keys and append _id in a associated list (python dict value). Number of machines per cloud account machine_groups = [ {'count': 1, '_id': '31140d2e-15a1-4203-bdbb-55c14cd6b83a'}, {'count': 17, '_id': 'c0a36d2e-f7dd-4d62-abe8-c26249e52520'}, {'count': 1, '_id': 'a650e642-ee41-4ab7-8ad1-797c7bdcd2aa'}, {'count': 1, '_id': 'd0576830-df96-4411-ac33-4bac597f2010'}] machine_groups_reorganized = {} for m in machine_groups: machine_groups_reorganized[m['_id']] = m['count'] machine_count_per_cloud_account = {d['cloud_account']: 0 for d in cloud_accounts} for d in cloud_accounts: machine_count_per_cloud_account[d['cloud_account']] += machine_groups_reorganized[d['_id']] import pprint pprint.pprint(machine_count_per_cloud_account) Here is the output: {'a639efb6-d4e0-4929-b309-8171bf61b508': 19, 'fd4bbf86-9803-4724-9576…
answers question: http://stackoverflow.com/q/51080028
has comment: http://stackoverflow.com/comment/89158338
type: Answer
has comment: http://stackoverflow.com/comment/89152383
has comment: http://stackoverflow.com/comment/89190009
has comment: http://stackoverflow.com/comment/89161041
has comment: http://stackoverflow.com/comment/89155702
has comment: http://stackoverflow.com/comment/89160753
has comment: http://stackoverflow.com/comment/89180454
has comment: http://stackoverflow.com/comment/89185865
has comment: http://stackoverflow.com/comment/89161074
has comment: http://stackoverflow.com/comment/89158401
has comment: http://stackoverflow.com/comment/89152844
score: 0
has comment: http://stackoverflow.com/comment/89151672
has comment: http://stackoverflow.com/comment/89149760

http://stackoverflow.com/comment/89220000
type: Comment
comment on: http://stackoverflow.com/a/51116516
has text: the picture shows the problem, but as you can see on pastebin there are exacly 100 points
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89030668
type: Comment
has text: @Alpha_Bords if you keep the `print(all.tell())` statement as is it will OF COURSE continue to print `None` - I thought this was obvious enough... The part about inheritance is totally unrelated.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51018194

http://stackoverflow.com/q/51103887
answer count: 1
tagged with: ssh
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51104059
upvote count: 3
type: Question
has body: I'm new to Paramiko. I am attempting to create a simple script that allows anyone to use their Linux credentials to run the command. I decided to test with a simple ls command but I am receiving errors. import paramiko username = *&lt;USERNAME&gt;* hostname = *&lt;HOSTNAME&gt;* port = 22 trans = paramiko.Transport((hostname,port)) trans.connect(username=username, password=password) channel = trans.open_channel("session") print(channel.send_ready()) print(channel.get_transport()) stdin,stdout,stderr = channel.exec_command("ls -lah") trans.close() I am receiving the following error: TypeError Traceback (most recent call last) &lt;ipython-input-28-ce837beea6fe&gt; in &lt;module&gt;() 6 trans.connect(username=username, password=password) 7 channel = trans.open_channel("session") ----&gt; 8 stdin,stdout,stderr = channel.exec_command("ls -lah") TypeError: 'NoneType' object is not iterable Any Ideas as to what I might be doing incorrectly?
downvote count: 0
linked to: http://stackoverflow.com/q/9470584
tagged with: paramiko
has title: Paramiko exec_command fails with 'NoneType' object is not iterable
has answer: http://stackoverflow.com/a/51104059
score: 3

http://stackoverflow.com/comment/89192263
has text: @Lumin, Yes, that's exactly the case. You may think it's inefficient to create a new dictionary. But it's not, it's O(n) complexity, which is the minimum possible given your data.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51102126
type: Comment

http://stackoverflow.com/a/51457764
has body: With pymc3 questions in general, your better to head to their discourse page. However, I was having a similar issue (not the exact same error message mind you) with pymc3 on windows. Try setting njobs=1 in the sample function and see if that helps. Update: The code above seems to compile fine on my machine, so maybe try updating pymc3/python to the newest versions
answers question: http://stackoverflow.com/q/51163148
score: 0
type: Answer

http://stackoverflow.com/q/51089257
type: Question
possible better answer: http://stackoverflow.com/a/51089382
tagged with: windows
has body: I am new to python and trying to create a simple API. below is the code for the same. from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': app.run(host='0.0.0.0',port=5000) I have saved this as code as "hello-world.py". When I am trying to run this file in command prompt using python command python hello-world.py Command executed in command prompt Here I have no error but web page is not getting displayed. Below is the error on web page. http://localhost:5000/ This site can’t be reached localhost refused to connect. Search Google for localhost 5000 ERR_CONNECTION_REFUSED 1st Issue - Even after running the code properly, why the web page is not displayed Now, I enter python command in my command prompt and then I try running file again python hello-world.py. Here I am getting the below error &gt;&gt;&gt; File "&lt;stdin&gt;", line 1 python hello-world.py ^ SyntaxError: invalid syntax 2nd Issue - Why I am getting an error while trying run the hello-world.py Please guide me on how to resolve this issue.
has answer: http://stackoverflow.com/a/51089382
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/51089404
answer count: 2
downvote count: 1
linked to: http://stackoverflow.com/q/761519
accepted answer: http://stackoverflow.com/a/51089404
type: AnsweredQuestion
upvote count: 0
has title: API not working
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/89166856

http://stackoverflow.com/comment/89264390
comment on: http://stackoverflow.com/a/51139968
type: AnswerComment
type: Comment
has text: This is exactly what I wanted, very slick! Thank you @Scott Boston
score: 1

http://stackoverflow.com/q/51164713
score: 9
has answer: http://stackoverflow.com/a/58248050
linked to: http://stackoverflow.com/q/5800009
has comment: http://stackoverflow.com/comment/89319134
tagged with: python
linked to: http://stackoverflow.com/q/51084825
has body: I use Python, opencv and PIL. image = cv2.imread('image.jpg') color = (235, 187, 7) How can I get pixel coordinates(x, y) if I know pixels color?
tagged with: opencv
upvote count: 9
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89320361
has answer: http://stackoverflow.com/a/63798698
has answer: http://stackoverflow.com/a/51165149
downvote count: 0
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51168723
type: Question
has answer: http://stackoverflow.com/a/62290811
has comment: http://stackoverflow.com/comment/89313017
has comment: http://stackoverflow.com/comment/89312701
has title: How to get pixel coordinates if I know color(RGB)?
favorite count: 0
has comment: http://stackoverflow.com/comment/89313406
tagged with: python-3.x

http://stackoverflow.com/comment/89221047
comment on: http://stackoverflow.com/a/51117422
type: Comment
has text: @connectyourcharger Well, why did you print a `\n` before every line number in the first place anyway?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51141066
tagged with: pandas
has body: I am using pandas and I have dataset something like this: **ID name total-cost** 1 a 7 2 b 4 3 c 1 4 e 6 5 f 80 6 k 85 So I need to get the fifth value in the order of the highest of total-cost, which is here 4 [85 80 7 6 4 1]. Not name, not ID, just a value.
favorite count: 0
accepted answer: http://stackoverflow.com/a/51141089
upvote count: 2
possible better answer: http://stackoverflow.com/a/51141257
has answer: http://stackoverflow.com/a/51141257
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39867061
downvote count: 3
has title: How to get field which has fifth in the order of the highest value in pandas
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51141089
score: -1

http://stackoverflow.com/a/51125888
type: Answer
downvote count: 0
score: 1
has body: #!/bin/bash python3 /home/me/workspace/project/foo.py I think this is your problem. @Martijn Pieters is spot on when he says it is a path issue. You need to ensure that the 'python3' you're calling is the python3 that has selenium installed. Wherever you're doing the pip3 freeze from, you need to ensure that is what the cron sees. When I use cronjobs I have my anaconda virtualenv explicitly run the job, as follows: /home/username/anaconda/envs/python3/bin/python /home/me/workspace/project/foo.py
upvote count: 1
has comment: http://stackoverflow.com/comment/95524510
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51124858
answers question: http://stackoverflow.com/q/51124858

http://stackoverflow.com/a/51167266
answers question: http://stackoverflow.com/q/51167093
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89317800
upvote count: 1
has body: From the documentation: On Unix-based systems, scandir() uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions. I would recommend looking at those if you want to know what's going on behind the scenes. opendir readdir FindFirstFileW FindNextFileW
downvote count: 0
has comment: http://stackoverflow.com/comment/89324773

http://stackoverflow.com/q/51029193
has body: I have a directory full of 60,000 files that are named by their molid. I have a second file in CSV format that has molids in column 1 with their respective CHEMBLID in column 2. I need to match the file name molid in the directory with a molid in the CSV file. If a match is found, the chemblid is added to the file (the file is rewritten to have the chemblid included). I am also using RDKit to calculate some properties I need written to the modified file too. I need to find a way to optimize this since I have to run it on 2 million files soon. The way I am interacting with arg parse is by listing all of the molid.sdf files in my directory with the bash parallel command. The csv file looks like: molid,chembl 319855,CHEMBLtest 187481,CHEMBL1527718 https://www.dropbox.com/s/6ynd9vbwwf6lqka/output_2.csv?dl=0 The file that needs to be modified looks like: 298512 from gamess16 based ATb pipeline OpenBabel06141815083D 34 35 0 0 1 0 0 0 0 0999 V2000 4.3885 -1.0129 1.6972 C 0 0 0 0 0 0 0 0 0 0 0 0 3.3885 -0.7157 0.5784 C 0 0 2 0 0 0 0 0 0 0 0 0 3.6479 -1.5425 -0.5699 O 0 0 0 0 0 0 0 0 0 0 0 0 3.4599 0.7380 0.1087 C 0 0 0 0 0 0 0 0 0 0 0 0 2.4770 1.0889 -1.0314 C 0 0 0 0 0 0 0 0 0 0 0 0 1.0165 0.9826 -0.6438 C 0 0 0 0 0 0 0 0 0 0 0 0 0.3679 2.0729 0.0029 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.9531 1.9980 0.3853 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.7151 0.8214 0.1489 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.0800 0.7051 0.5321 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.8067 -0.4453 0.2969 C 0 0 0 0 0 0 0 0 0 0 0 0 -5.2581 -0.5636 0.6988 C 0 0 0 0 0 0 0 0 0 0 0 0 -3.1581 -1.5376 -0.3496 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.8397 -1.4605 -0.7357 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.0762 -0.2830 -0.5007 C 0 0 0 0 0 0 0 0 0 0 0 0 0.2871 -0.1675 -0.8844 C 0 0 0 0 0 0 0 0 0 0 0 0 4.1834 -0.3978 2.5815 H 0 0 0 0 0 0 0 0 0 0 0 0 5.4123 -0.8100 1.3616 H 0 0 0 0 0 0 0 0 0 0 0 0 4.3301 -2.0654 2.0016 H 0 0 0 0 0 0 0 0 0 0 0 0 2.3709 -0.9175 0.9451 H 0 0 0 0 0 0 0 0 0 0 0 0 3.4809 -2.4622 -0.3076 H 0 0 0 0 0 0 0 0 0 0 0 0 3.2757 1.3897 0.9729 H 0 0 0…
type: Question
downvote count: 0
tagged with: bash
tagged with: argparse
has comment: http://stackoverflow.com/comment/89051095
answer count: 1
has answer: http://stackoverflow.com/a/51048928
accepted answer: http://stackoverflow.com/a/51048928
favorite count: 0
tagged with: rdkit
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/89056289
type: AnsweredQuestion
score: 3
has title: How can I optimize this script so it does not take a week to finish the task it is doing? (Used BASH PARALLEL too.)
has comment: http://stackoverflow.com/comment/89087076
upvote count: 3

http://stackoverflow.com/q/51040987
has comment: http://stackoverflow.com/comment/89073051
has comment: http://stackoverflow.com/comment/89073186
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89077288
has comment: http://stackoverflow.com/comment/89073452
score: -5
favorite count: 0
has title: updating python code for version 2.7, to run on version 3.0
has comment: http://stackoverflow.com/comment/89073068
type: Question
has body: I have been given code to control a vacuum pump and take measurements in my lab that runs correctly on version 2.7 of python, however the computer that is linked to the vacuum system in the lab only has version 3.0 so the code does not run correctly. If anyone could update the code I would be very grateful. Code: # -*- coding: utf-8 -*- """ Created on Fri Jul 14 10:25:56 2017 @author: jav2g09 This module contains drivers for the following equipment from Pfeiffer Vacuum: * TPG 262 and TPG 261 Dual Gauge. Dual-Channel Measurement and Control Unit for Compact Gauges """ print ("start") import time import serial import numpy as np # Code translations constants MEASUREMENT_STATUS = { 0: 'Measurement data okay', 1: 'Underrange', 2: 'Overrange', 3: 'Sensor error', 4: 'Sensor off (IKR, PKR, IMR, PBR)', 5: 'No sensor (output: 5,2.0000E-2 [mbar])', 6: 'Identification error' } GAUGE_IDS = { 'TPR': 'Pirani Gauge or Pirani Capacitive gauge', 'IKR9': 'Cold Cathode Gauge 10E-9 ', 'IKR11': 'Cold Cathode Gauge 10E-11 ', 'PKR': 'FullRange CC Gauge', 'PBR': 'FullRange BA Gauge', 'IMR': 'Pirani / High Pressure Gauge', 'CMR': 'Linear gauge', 'noSEn': 'no SEnsor', 'noid': 'no identifier' } PRESSURE_UNITS = {0: 'mbar/bar', 1: 'Torr', 2: 'Pascal'} class TPG26x(object): r"""Abstract class that implements the common driver for the TPG 261 and TPG 262 dual channel measurement and control unit. The driver implements the following 6 commands out the 39 in the specification: * PNR: Program number (firmware version) * PR[1,2]: Pressure measurement (measurement data) gauge [1, 2] * PRX: Pressure measurement (measurement data) gauge 1 and 2 * TID: Transmitter identification (gauge identification) * UNI: Pressure unit * RST: RS232 test This class also contains the following class variables, for the specific characters that are used in the communication: :var ETX: End text (Ctrl-c), chr(3), \\x15 :var CR: Carriage return, chr(13), \\r :var LF: Line feed, chr(10), \\n :var ENQ: Enquiry, chr(5), \\x05 …
has comment: http://stackoverflow.com/comment/89150782
tagged with: python
has comment: http://stackoverflow.com/comment/89116130
has comment: http://stackoverflow.com/comment/89073334
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51041125
downvote count: 6

http://stackoverflow.com/q/51130636
has body: I want to export the shapefile from a PostgreSQL database using python but i am getting an error of "column not exist". The value "Deurali" exists in table. error shows: my code with error is shown in screenshot.
type: Question
has comment: http://stackoverflow.com/comment/89788190
tagged with: database
has comment: http://stackoverflow.com/comment/89775538
upvote count: 1
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has title: Export shapefile using pgsql2shp module in Python IDE
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51130022
tagged with: seaborn
tagged with: python
tagged with: plot
type: AnsweredQuestion
type: Question
has title: Python: dynamically produce seaborn plots then display results side-by-side?
has comment: http://stackoverflow.com/comment/89245993
score: 0
has answer: http://stackoverflow.com/a/51134040
answer count: 1
has body: I'm trying to produce multiple seaborn kernel density plots for the numeric variables of my Pandas DataFrame. I have the names of all of my numeric columns in a list, numberCol. Presently, I can make a kdeplot for each variable that I explicitly name, like so: import seaborn as sbn sbn.set_style('whitegrid') sbn.kdeplot(np.array(df.v2), bw=0.5) # for pandas.core.frame.DataFrame input Is there a better way to iterate through the numberCol list, produce an sbn.kdeplot for each variable in numberCol, then display them side-by-side with something smarter than something like: import matplotlib.pyplot as plt import seaborn as sns # Here we create a figure instance, and two subplots fig = plt.figure(figsize = (20,20)) # width x height ax1 = fig.add_subplot(3, 3, 1) # row, column, position ax2 = fig.add_subplot(3, 3, 2) ax3 = fig.add_subplot(3, 3, 3) # We use ax parameter to tell seaborn which subplot to use for this plot sns.heatmap(data=subset1.corr(), ax=ax1, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12}) sns.heatmap(data=subset2.corr(), ax=ax2, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12}) sns.heatmap(data=subset3.corr(), ax=ax3, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
accepted answer: http://stackoverflow.com/a/51134040

http://stackoverflow.com/a/51115137
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/89216698
has body: Instead of returning False if the check fails, instead raise a subclass of CommandError, then handle that error in the on_command_error event. class UserBlacklisted(commands.CommandError): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) class ServerBlacklisted(commands.CommandError): def __init__(self, server, *args, **kwargs): self.server = server super().__init__(*args, **kwargs) def blacklists(users, servers): def predicate(ctx): if ctx.message.author.id in users: raise UserBlacklisted(ctx.message.author) elif ctx.message.server.id in servers: raise ServerBlacklisted(ctx.message.server) else: return True return commands.check(predicate) @bot.event async def on_command_error(error, ctx): if isinstance(error, UserBlacklisted): await bot.send_message(ctx.message.channel, "User {} has been blacklisted".format(error.user.mention)) elif isinstance(error, ServerBlacklisted): await bot.send_message(ctx.message.channel, "Server {} has been blacklisted".format(error.server.name)) @bot.command(pass_context=True) @blacklists(LIST_OF_USER_IDS, LIST_OF_SERVER_IDS) async def hello(ctx): await bot.say("Hello {}".format(ctx.message.author.mention))
answers question: http://stackoverflow.com/q/51115044
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51115044
has comment: http://stackoverflow.com/comment/89217122

http://stackoverflow.com/q/51033910
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51034361
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89059957
has title: Create individual objects based on json response
tagged with: python
tagged with: dictionary
downvote count: 0
type: UnansweredQuestion
type: Question
has body: I'm trying to take a json response and create as many objects that are contained in the response. Based on the text below, I want variable to be based on "testuser1" and the next variable to be based on "testuser2", and so on. Im able to convert the response to a dictionary but I'm sure how to count the objects and make variables out of each so I can refer and change them later in the code. {'Accounts': [ {'Name': 'testuser1', 'Username': 'testuser1', 'Email': 'test1@example.com'}, {'Name': 'testuser2', 'Username': 'testuser2', 'Email': 'test2@example.com'} ] Basically, I want to count and create as many objects that are in the response. I don't want to use the split function to look for the {}. For example: $var1 = {'Name': 'testuser1', 'Username': 'testuser2=1', 'Email': 'test1@example.com'} and $var2 = {'Name': 'testuser2', 'Username': 'testuser2', 'Email': 'test2@example.com'}
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51035261

http://stackoverflow.com/comment/89171382
type: QuestionComment
has text: So then how do you work with large XML files? But that is something that I didn't think about.
type: Comment
comment on: http://stackoverflow.com/q/51091217
score: 0

http://stackoverflow.com/comment/89244159
comment on: http://stackoverflow.com/a/51129668
has text: yeah, it's just the path used in cron ... and as I said ... you've already set it in your crontab, we're just adding `/usr/local/bin` to it. you could prepend `$PATH` to that if it makes you feel better, but it won't do anything as cron unsets env.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/121811748
type: Comment
has text: Thank you very much. I was reshaping the probabilities in the wrong way.
comment on: http://stackoverflow.com/a/53903083
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89088856
score: 0
comment on: http://stackoverflow.com/q/51048776
has text: Sounds like maybe you want a different channel for responses, then, so the other system can send the answer on it? There's nothing required code-wise you don't already have -- just need to copy the code you already have for subscribing and listening into the client so it can listen for a response, changing the channel identifier to a different one.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52021082
type: Answer
has body: I Had the same problem and I found that it's happening because I had {{ form }} Django tag this tag is also loading the non_field_errors so I had to render it manually like this {{ form.non_field_errors }} {{ form.label }} {{ form.field_name }}
score: 0
answers question: http://stackoverflow.com/q/51090505

http://stackoverflow.com/comment/89170631
type: Comment
has text: The default indexing of scikit-learn functions are expecting numpy arrays. Use .iloc or use `X = X.values` in advance. Please consider accepting my answer
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51091177

http://stackoverflow.com/comment/89296413
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51147762
has text: Duplicate of this https://stackoverflow.com/questions/44586356/airflow-failed-slack-message? Rather than using `on_failure_callback` and `on_success_callback`, why not just make the slack message a task in your DAG as you are requesting a message whether the task is a success/failure.
score: 0

http://stackoverflow.com/q/51088092
tagged with: python
upvote count: 4
downvote count: 1
has title: Notepad++ changes the encoding of my code
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51106552
accepted answer: http://stackoverflow.com/a/51106552
type: Question
tagged with: notepad++
has comment: http://stackoverflow.com/comment/89170650
answer count: 1
linked to: http://stackoverflow.com/q/2223882
favorite count: 0
has body: I've some python code, that contains recognition for some hindi text. I deliberately save it as UTF-8, but when I re-open it, the hindi symbols change to russian text(mostly) or simply a ?. The encoding too changes to OEM 866 which is cyrillic. Here are the screenshots, (lines 90 and 98): Because of this encoding change, my code too isn't running at all, as the regular expressions consider ? as a special input. So what should I do?

http://stackoverflow.com/comment/89301276
score: 4
has text: *how can I make sure that the changes made by somebody in a previous request don't end up affecting another person's separate request?* Don't use global variables.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51158998

http://stackoverflow.com/a/51087739
score: 5
accepted answer of: http://stackoverflow.com/q/51077990
type: AcceptedAnswer
downvote count: 0
has body: import numpy as np import cv2 from PIL import Image from tesserocr import PyTessBaseAPI, RIL if __name__ == '__main__': image = cv2.imread('image.png',cv2.IMREAD_UNCHANGED) image = cv2.resize(image, (0,0), fx=0.5, fy=0.5) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret,binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV) binary = cv2.medianBlur(binary, 3) (rows,cols) = image.shape[:2] H = cv2.Sobel(binary, cv2.CV_8U, 1, 0, ksize = 5) V = cv2.Sobel(binary, cv2.CV_8U, 0, 1, ksize = 5) _,contours,_ = cv2.findContours(V, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: (x,y,w,h) = cv2.boundingRect(cnt) if w &lt; cols/3 and h &lt; rows/3: cv2.drawContours(V, [cnt], -1, 0, -1) _,contours,_ = cv2.findContours(H, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: (x,y,w,h) = cv2.boundingRect(cnt) if w &lt; cols/3 and h &lt; rows/3: cv2.drawContours(H, [cnt], -1, 0, -1) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)) V = cv2.morphologyEx(V, cv2.MORPH_DILATE, kernel, iterations = 3) H = cv2.morphologyEx(H, cv2.MORPH_DILATE, kernel, iterations = 3) binary[V == 255] = 0 binary[H == 255] = 0 binary = cv2.bitwise_not(binary) api = PyTessBaseAPI() api.SetImage(Image.fromarray(binary)) text = api.GetUTF8Text() text = text.split() boxes = api.GetComponentImages(RIL.TEXTLINE, True) for i, (_, box, _, _) in enumerate(boxes): (x,y,w,h) = box['x'], box['y'], box['w'], box['h'] cv2.rectangle(image, (x,y), (x+w,y+h), (0,0,255)) cv2.putText(image, text[i], (x,y), cv2.FONT_HERSHEY_PLAIN, 1, (255,0,0)) cv2.imshow('image', image) cv2.waitKey(0) cv2.destroyAllWindows()
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51077990

http://stackoverflow.com/comment/89174401
type: AnswerComment
has text: It's possible but it's not recommended because they all return completely different objects--`get_A` returns a list, `get_B` returns a dict and `post_C` returns a string. It's a good practice to keep function signatures consistent by having fixed returning data types.
comment on: http://stackoverflow.com/a/51093081
type: Comment
score: 0

http://stackoverflow.com/q/51092529
downvote count: 1
has comment: http://stackoverflow.com/comment/89173335
favorite count: 0
has title: translated matlab code into python, but python is way slower
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17559140
tagged with: python
has comment: http://stackoverflow.com/comment/89198482
tagged with: matlab
has body: So I've been starting to use python recently, and i am working on a project of calculating wind exposure. I've managed my code in matlab and it runs very fast(can be done in 3 minutes), but after I translated my code into python, i am getting the same result but it takes 3hours to finish it's job. I really need a hand on checking what's causing such a huge difference... So here's my python code. I can give out my matlab code if anyone need it. from netCDF4 import Dataset, num2date import numpy as np import matplotlib.pyplot as plt from scipy import interpolate #import pylab as py #input data dem = Dataset('comparearea_fill.nc','r') lon = np.array(dem.variables['lon']) lat = np.array(dem.variables['lat']) DEM = np.array(dem.variables['elevation']) carea = Dataset('carea.nc','r') u = np.array(carea.variables['u10']) v = np.array(carea.variables['v10']) mu = np.mean(u, axis=0) mv = np.mean(v, axis=0) x = np.linspace(1,21,21) y = np.linspace(1,11,11) newu = interpolate.interp2d(x, y, mu, kind='cubic') newv = interpolate.interp2d(x, y, mv, kind='cubic') spu = newu(lon,lat) spv = newv(lon,lat) A = np.zeros((4951,9451)) B = np.zeros((4951,9451)) for i in range(100,4850): for j in range(100,9350): for n in range(20): A[i,j] = (DEM[i,j]-np.max(DEM[np.floor(n*spv[i,j]).astype(int),j-np.floor(n*spu[i,j]).astype(int)]))/DEM[i,j] if A[i,j] &lt; 0: A[i,j] = 0 B[i,j] = (DEM[i,j]-np.max(DEM[i-np.ceil(n*spv[i,j]).astype(int),j-np.ceil(n*spu[i,j]).astype(int)]))/DEM[i,j] if B[i,j] &lt; 0: B[i,j] = 0 C = A+B plt.contourf(lon,lat,C); plt.colorbar() here the mu and mv are the monthly average of the u and v wind, while the spu and spv are the spline interpulated u and v wind to fit the resolution of my dem data set.
answer count: 0
tagged with: translate
has comment: http://stackoverflow.com/comment/89173387
linked to: http://stackoverflow.com/q/46475162
type: Question
has comment: http://stackoverflow.com/comment/89173832
has comment: http://stackoverflow.com/comment/89173351
has comment: http://stackoverflow.com/comment/89173391
score: 0
upvote count: 1

http://stackoverflow.com/q/51137262
type: UnansweredQuestion
tagged with: datetime
tagged with: python
answer count: 0
has body: I have a time hour, minute, seconde serverTime = 'Jul 2, 2018 3:21:56 PM' serverTime = serverTime.strftime('%H:%M:%S') serverTime = datetime.strptime(serverTime, '%H:%M:%S').time() print(serverTime) &gt;&gt; 15:21:56 print(type(serverTime)) &gt;&gt; &lt;class 'datetime.time'&gt; and I have a timedelta like this openTimeFrom = timedelta(milliseconds=hours['fromT'] print(serverTime) &gt;&gt; 08:00:00 print(type(openTimeFrom)) &gt;&gt; &lt;class 'datetime.timedelta'&gt; and i want compare openTimeFrom and serverTime to know if serverTime is greater than openTimeFrom but when i do this if serverTime &gt; openTimeFrom: I have this error TypeError: '>' not supported between instances of 'datetime.time' and 'datetime.timedelta'
type: Question
has comment: http://stackoverflow.com/comment/89258486
has title: python compare datatime.time to datetime.timedelta
score: 0
has comment: http://stackoverflow.com/comment/89258579
tagged with: timedelta
has comment: http://stackoverflow.com/comment/89278819

http://stackoverflow.com/q/51162300
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89309109
type: Question
has title: GitLab CI: how to simulate user input from console
answer count: 1
downvote count: 0
tagged with: gitlab-ci
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89308912
has answer: http://stackoverflow.com/a/55090249
tagged with: python
has body: I have a .gitlab-ci.yml similar to this: image: python:3.6 before_script: - pip install -r .requirements test: script: - python main.py --arg myArg The python script main.py is a command line program and expects some input from the user, which is requested with input: userName = input("Please input your name:") I know that maybe I shouldn't call that python script for continuous integration and I also have unit tests for all other scripts which can be tested fine. But nevertheless, I would like to know, if it is possible to somehow simulate the user input by specifying it in the yml itself. Somebody any idea?

http://stackoverflow.com/a/51069874
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89129843
has comment: http://stackoverflow.com/comment/89130118
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/89129753
answers question: http://stackoverflow.com/q/51069677
has body: you need to wait for javascript to laod the page, i think in this is the problem, if you want you can use selenium # your imports ... from selenium import webdriver site = 'http://heroimages.com/portfolio' directory = "pixabay/" #Relative to script location driver = webdriver.Chrome('/usr/local/bin/chromedriver') driver.get(site) soup = BeautifulSoup(driver.page_source, 'html.parser') img_tags = soup.find_all('img') urls = [img['src'] for img in img_tags] for url in urls: print(url) # your code ... Output # from `http://heroimages.com/portfolio` https://ssl.c.photoshelter.com/img-get2/I00004gQScPHUm5I/sec=wdtsdfoeflwefms1440ed201806304risXP3bS2xDXil/fill=350x233/361-03112.jpg https://ssl.c.photoshelter.com/img-get2/I0000h9YWTlnCxXY/sec=wdtsdfoeflwefms1440ed20180630Nq90zU4qg6ukT5K/fill=350x233/378-01449.jpg https://ssl.c.photoshelter.com/img-get2/I0000HNg_JtT_QrQ/sec=wdtsdfoeflwefms1440ed201806304CZwwO1L641maB9/fill=350x233/238-1027-hro-3552.jpg https://ssl.c.photoshelter.com/img-get2/I00000LWwYspqXuk/sec=wdtsdfoeflwefms1440ed201806302BP_NaDsGb7udq0/fill=350x233/258-02351.jpg # and many others images Also the script that check if the directory exists, if it don't exist create it. ... directory = os.path.dirname(os.path.realpath(__file__)) + '/pixabay/' if not os.path.exists(directory): os.makedirs(directory) ...
accepted answer of: http://stackoverflow.com/q/51069677

http://stackoverflow.com/comment/89291919
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51154236
has text: It is now showing request_time not defined. request_time key is present in the document itself. Do I need to define it somehow ?

http://stackoverflow.com/a/51152881
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89289353
answers question: http://stackoverflow.com/q/51152538
has body: You can try using event to call function. If "Enter" occurs for button then call a function that calls pack() and if "Leave" occurs for button then call a function that calls pack_forget(). Check this link for event description:List of All Tkinter Events If you wish your button to stay at a defined place then you can use place(x,y) instead of pack()
upvote count: 1
has comment: http://stackoverflow.com/comment/89369836
type: Answer
has comment: http://stackoverflow.com/comment/89334633

http://stackoverflow.com/q/51111163
has comment: http://stackoverflow.com/comment/89210029
has answer: http://stackoverflow.com/a/78999262
has comment: http://stackoverflow.com/comment/89209360
accepted answer: http://stackoverflow.com/a/51111300
has comment: http://stackoverflow.com/comment/89209411
has answer: http://stackoverflow.com/a/62637149
has comment: http://stackoverflow.com/comment/89228287
favorite count: 0
tagged with: python-3.x
answer count: 5
possible better answer: http://stackoverflow.com/a/51111236
has answer: http://stackoverflow.com/a/63362247
has comment: http://stackoverflow.com/comment/89209486
tagged with: python
has answer: http://stackoverflow.com/a/51111236
score: 2
has comment: http://stackoverflow.com/comment/89209444
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33508034
has comment: http://stackoverflow.com/comment/89209402
upvote count: 3
has body: Please help me understand what i did wrong. The problem is The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”) Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1. def collatz(number): if number%2==0: print(number//2) else: print(3*number+1) x = int(input('print num')) while TRUE: if collatz(x)!=1: break
has answer: http://stackoverflow.com/a/51111300
has comment: http://stackoverflow.com/comment/89209435
downvote count: 1
tagged with: collatz
type: Question
has comment: http://stackoverflow.com/comment/89209442
has title: Collatz Loop Structure
has comment: http://stackoverflow.com/comment/89209399

http://stackoverflow.com/comment/89224627
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51119339
has text: thanks you a lot, i need to mix those data because i want to know what data from column arr[:, [2]] are for column arr[:, [0]]. Do you know if i can do that from this way? thanks you...

http://stackoverflow.com/q/51050486
has comment: http://stackoverflow.com/comment/89091982
favorite count: 0
has answer: http://stackoverflow.com/a/51062915
accepted answer: http://stackoverflow.com/a/51062915
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89092013
has body: I am writing a class that should write a csv file with a delimiter ',' class DelFile(WriteFile): def __init__(self, TextFile): self.TextFile = TextFile def write(self, Mssg, Delimiter): with open(self.TextFile, "w+") as csv_file: writer = csv.writer(csv_file, delimiter=',') for item in Mssg: writer.writerow(item) I am calling it here: c = DelFile('text3.csv') c.write(['a','b','c'], ',') As a result, I get this: I would like to write the content as rows and not as columns a, b, c. Also, I did not understand why the result is jumping lines. Any help is highly appreciated!
type: Question
tagged with: oop
score: -1
tagged with: class
has comment: http://stackoverflow.com/comment/89092032
has title: Writing in csv file from a list
answer count: 1

http://stackoverflow.com/a/51030313
has body: Based on the comment by DanielRoseman : The tokens list is being mutated outside the tokenize function, using the analyze; after which the if condition is good. You don't show the code for analyze(), but I would guess that it mutates its argument - ie it removes all the entries from tokens as it analyzes them, and if there are any left after it returns that must be a syntax error. – Daniel Roseman
accepted answer of: http://stackoverflow.com/q/51017508
answers question: http://stackoverflow.com/q/51017508
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/51064959
has answer: http://stackoverflow.com/a/51065155
favorite count: 0
possible better answer: http://stackoverflow.com/a/51066028
tagged with: python
has answer: http://stackoverflow.com/a/51066028
has body: guys. I started to study classes recently and while playing around was trying to do something like this : from functools import partial class test(): def __init__(self): exec('def foo(self, number): x = number; return x') def printingX(self): command = partial(self.foo, 1) print command a = test() a.printingX() It's of course giving an error, but my question is : Is it possible to store method inside 'init' and then to call it in other methods later? If it's possible, is it a good practice to do or bad?
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/51065155
has comment: http://stackoverflow.com/comment/89119942
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51065731
tagged with: class
has title: how to do 'exec' definition inside class Python
answer count: 3
score: 3

class
tags question: http://stackoverflow.com/q/51032505
tags question: http://stackoverflow.com/q/51105738
tags question: http://stackoverflow.com/q/51135073
tags question: http://stackoverflow.com/q/51109531
tags question: http://stackoverflow.com/q/51163974
tags question: http://stackoverflow.com/q/51113138
tags question: http://stackoverflow.com/q/51133631
tags question: http://stackoverflow.com/q/51164663
tags question: http://stackoverflow.com/q/51126987
tags question: http://stackoverflow.com/q/51098231
tags question: http://stackoverflow.com/q/51144929
tags question: http://stackoverflow.com/q/51124446
tags question: http://stackoverflow.com/q/51080445
tags question: http://stackoverflow.com/q/51102145
tags question: http://stackoverflow.com/q/51165352
tags question: http://stackoverflow.com/q/51101392
tags question: http://stackoverflow.com/q/51020990
tags question: http://stackoverflow.com/q/51108063
tags question: http://stackoverflow.com/q/51064959
tags question: http://stackoverflow.com/q/51044182
tags question: http://stackoverflow.com/q/51071604
type: Tag
tags question: http://stackoverflow.com/q/51043969
tags question: http://stackoverflow.com/q/51153499
tags question: http://stackoverflow.com/q/51165504
tags question: http://stackoverflow.com/q/51104120
tags question: http://stackoverflow.com/q/51085337
tags question: http://stackoverflow.com/q/51023118
tag name: class
tags question: http://stackoverflow.com/q/51083555
tags question: http://stackoverflow.com/q/51122061
tags question: http://stackoverflow.com/q/51089821
tags question: http://stackoverflow.com/q/51079683
tags question: http://stackoverflow.com/q/51143317
tags question: http://stackoverflow.com/q/51031774
tags question: http://stackoverflow.com/q/51158618
tags question: http://stackoverflow.com/q/51084007
tags question: http://stackoverflow.com/q/51077772
tags question: http://stackoverflow.com/q/51050486

http://stackoverflow.com/a/51103974
answers question: http://stackoverflow.com/q/51103867
downvote count: 0
has body: jsfields = jsondata, jsondata This line creates a tuple containing two copies of jsondata. A tuple is somewhat like a list, but is immutable, meaning that you cannot add anything to it after it is created. You probably want to do this to create a list: jsfields = [jsondata, jsondata] This creates a list with two copies of jsondata in it. You can then add more entries pretty easily: jsfields.append(some_other_dict)
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/89239839
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51127411
score: 2
has text: `function_2` is never used here, and is irrelevant.

http://stackoverflow.com/q/51156263
score: 0
has body: Hi everyone and thanks for trying to help me ! I encounter trouble when trying to import a python module generated by swig. I have a basic library "example" containing few methods. Next to it I have a main program dynamically linked to python. This program imports the generated module and calls a function in it. If my library example is a shared one, named _example.so, everything works perfectly, and I can import it in python. But if my library is static, _example.a, and linked to the main program, then I will have the error "no module named _example was found" unless I add a call to SWIG_init() in the main function. What exactly does SWIG_init() , and when should I use it ? It seems quite weird to me because it's never said in the documentation to do such a call. I know that dealing with a .so shared library is better but I try to reproduce the behavior of what I have on a big project at work, so I really have to understand what happens when the module is static. Here is my main file : #include "Python.h" #include &lt;iostream&gt; #if PY_VERSION_HEX &gt;= 0x03000000 # define SWIG_init PyInit__example #else # define SWIG_init init_example #endif #ifdef __cplusplus extern "C" #endif #if PY_VERSION_HEX &gt;= 0x03000000 PyObject* #else void #endif SWIG_init(void); int main (int arc, char** argv) { Py_Initialize(); SWIG_init(); // needed only using the statically linked version of example ? PyRun_SimpleString("print \"Hello world from Python !\""); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"/path/to/my/module\")"); PyRun_SimpleString("import example"); PyRun_SimpleString("a = example.Example()"); PyRun_SimpleString("print a.fact(5)"); } Here is how things are generated : swig -c++ -python example.i g++ -fpic -c example.cpp example_wrap.cxx -I/include/python2.7 -lstdc++ ar rvs libexample.a example.o example_wrap.o // to generate dynamic instead of static : g++ -shared example.o example_wrap.o -o _example.so g++ main.cpp -I/include/python2.7 l…
answer count: 1
has answer: http://stackoverflow.com/a/51159236
accepted answer: http://stackoverflow.com/a/51159236
tagged with: python
tagged with: c++
type: AnsweredQuestion
has title: Swig/python : when SWIG_init() is needed?
type: Question
tagged with: swig

cx-freeze
tags question: http://stackoverflow.com/q/51106867
tags question: http://stackoverflow.com/q/51067599
tag name: cx-freeze
tags question: http://stackoverflow.com/q/51094972
type: Tag
tags question: http://stackoverflow.com/q/51046546
tags question: http://stackoverflow.com/q/51104597
tags question: http://stackoverflow.com/q/51091547

http://stackoverflow.com/a/51129559
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51129550
has comment: http://stackoverflow.com/comment/89244013
upvote count: 2
answers question: http://stackoverflow.com/q/51129550
has comment: http://stackoverflow.com/comment/89385114
has body: Use str.contains with boolean indexing, ~ is for inverting boolean mask: m = df['Code'].str.contains("^[0-9]{1,5}$") df1 = df[m] print (df1) No Code Name Rem Last Done LACP Chg % Chg Vol ('00) 0 1 0012 3A [S] s 0.940 0.940 - - 20 1 2 7054 AASIA [S] s - 0.205 - - - 2 3 5238 AAX [S] s 0.345 0.340 0.005 +1.47 37,806 4 5 7086 ABLEGRP [S] s 0.095 0.100 -0.005 -5.00 300 df2 = df[~m] print (df2) No Code Name Rem Last Done LACP Chg % Chg Vol ('00) 3 4 5238WA AAX-WA [S] s 0.135 0.135 - - 590 Detail: print (m) 0 True 1 True 2 True 3 False 4 True Name: Code, dtype: bool print (~m) 0 False 1 False 2 False 3 True 4 False Name: Code, dtype: bool
has comment: http://stackoverflow.com/comment/89386749
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/89079079
type: Comment
comment on: http://stackoverflow.com/a/51042300
type: AnswerComment
score: 0
has text: Interesting, this solution is exactly what I posted, just bloated up by a few lines :/ This code just wraps every row in a list, just to unwrap it again outside of `read_from_db()`. When I copy your exact code (which you now changed according to my proposal), it works just fine. There must be something else then that breaks your code.

http://stackoverflow.com/q/51112685
tagged with: gcloud
favorite count: 0
tagged with: python
tagged with: node.js
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: circleci
type: Question
tagged with: google-cloud-sdk
has answer: http://stackoverflow.com/a/52769509
has title: circleci with gcloud sdk UnicodeDecodeError
upvote count: 1
answer count: 1
has body: Before asking question, I wanna say that I've looked up every similar questions in stackoverflow, but everything was of no use. I am experiencing a strange error recently. I've used CircleCI as CI/CD tool to deploy my service to GCP app engine. Recently, I realized that nodejs8 is now available for standard app engine. So I switched from flex app engine to standard app engine, and changed my app.yaml, from env: flex runtime: nodejs automatic_scaling: min_num_instances: 1 to runtime: nodejs8 instance_class: F2 automatic_scaling: min_instances: 0 I only changed my app.yaml, but this error happens Beginning deployment of service [default]... ERROR: gcloud crashed (UnicodeDecodeError): 'ascii' codec can't decode byte 0xeb in position 14: ordinal not in range(128) If you would like to report this issue, please run the following command: gcloud feedback To check gcloud for common problems, please run the following command: gcloud info --run-diagnostics Exited with code 1 I know that this is related to python. But I cannot understand why this error happens as I only changed app.yaml. Is this a bug of gcloud sdk, or CircleCI?

http://stackoverflow.com/comment/89178564
comment on: http://stackoverflow.com/a/51093645
has text: @KeithW this works fine for me. If it does for you as well please don't forget to upvote and mark the answer as correct. Thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89162192
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51071600
has text: @Dvorog Noted and agreed. I think the SO "homework" debate is distraction when all questions should be held to the same standards.
type: QuestionComment

http://stackoverflow.com/comment/89179397
has text: TL;DR Don't worry about it until it's an actual noticeable problem. (really great write-up though)
score: 1
comment on: http://stackoverflow.com/a/51095822
type: AnswerComment
type: Comment

pyspark
tags question: http://stackoverflow.com/q/51099157
tags question: http://stackoverflow.com/q/51117205
tags question: http://stackoverflow.com/q/51137909
tags question: http://stackoverflow.com/q/51120814
tags question: http://stackoverflow.com/q/51034680
tags question: http://stackoverflow.com/q/51070251
tags question: http://stackoverflow.com/q/51151850
tags question: http://stackoverflow.com/q/51130711
tags question: http://stackoverflow.com/q/51110701
type: Tag
tags question: http://stackoverflow.com/q/51024285
tags question: http://stackoverflow.com/q/51082758
tags question: http://stackoverflow.com/q/51084621
tags question: http://stackoverflow.com/q/51143278
tags question: http://stackoverflow.com/q/51052553
tags question: http://stackoverflow.com/q/51129312
tags question: http://stackoverflow.com/q/51082687
tags question: http://stackoverflow.com/q/51158135
tags question: http://stackoverflow.com/q/51074280
tags question: http://stackoverflow.com/q/51077948
tags question: http://stackoverflow.com/q/51072108
tags question: http://stackoverflow.com/q/51078195
tags question: http://stackoverflow.com/q/51145894
tags question: http://stackoverflow.com/q/51159672
tags question: http://stackoverflow.com/q/51014632
tags question: http://stackoverflow.com/q/51145331
tags question: http://stackoverflow.com/q/51034637
tags question: http://stackoverflow.com/q/51084514
tags question: http://stackoverflow.com/q/51050982
tags question: http://stackoverflow.com/q/51091931
tags question: http://stackoverflow.com/q/51096435
tags question: http://stackoverflow.com/q/51157212
tags question: http://stackoverflow.com/q/51120046
tags question: http://stackoverflow.com/q/51072816
tags question: http://stackoverflow.com/q/51019490
tags question: http://stackoverflow.com/q/51053179
tag name: pyspark
tags question: http://stackoverflow.com/q/51144078
tags question: http://stackoverflow.com/q/51105475

http://stackoverflow.com/a/70091711
score: 0
answers question: http://stackoverflow.com/q/51069716
type: Answer
has body: In Jupyter Lab, although my Python was 3.9 but it was using 3.7 paths (I have multiple Pythons installed): import sys sys.path ['D:\\Projects', 'C:\\Program Files\\Python37\\python37.zip', 'C:\\Program Files\\Python37\\DLLs', 'C:\\Program Files\\Python37\\lib', 'C:\\Program Files\\Python37', '', 'C:\\Users\\John\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Program Files\\Python37\\lib\\site-packages', 'C:\\Program Files\\Python37\\lib\\site-packages\\win32', 'C:\\Program Files\\Python37\\lib\\site-packages\\win32\\lib', 'C:\\Program Files\\Python37\\lib\\site-packages\\Pythonwin', 'C:\\Program Files\\Python37\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\John\\.ipython'] So I did !pip3.7 install --user wget, and then it worked.

http://stackoverflow.com/q/51126471
type: AnsweredQuestion
has body: I'm trying to install channels_redis and got following error. pip install channels_redis Collecting channels_redis Using cached https://files.pythonhosted.org/packages/63/ae/adea3b1913aebb84ec6b6f3c30ba81b8bef79f99b51c7240810284152df4/channels_redis-2.2.1-py2.py3-none-any.whl Requirement already satisfied: channels~=2.0 in ./env/lib/python3.6/site-packages (from channels_redis) (2.1.1) Requirement already satisfied: asgiref~=2.1 in ./env/lib/python3.6/site-packages (from channels_redis) (2.3.2) Collecting msgpack~=0.5.0 (from channels_redis) Using cached https://files.pythonhosted.org/packages/22/4e/dcf124fd97e5f5611123d6ad9f40ffd6eb979d1efdc1049e28a795672fcd/msgpack-0.5.6-cp36-cp36m-manylinux1_x86_64.whl Collecting aioredis~=1.0 (from channels_redis) Using cached https://files.pythonhosted.org/packages/83/4f/fb41fd054522b2f15cf8c9a0b119096a3f2e4db41c9cd7c114da8de742b1/aioredis-1.1.0-py3-none-any.whl Requirement already satisfied: daphne~=2.1 in ./env/lib/python3.6/site-packages (from channels~=2.0-&gt;channels_redis) (2.1.2) Requirement already satisfied: Django&gt;=1.11 in ./env/lib/python3.6/site-packages (from channels~=2.0-&gt;channels_redis) (2.0.6) Requirement already satisfied: async-timeout&lt;4.0,&gt;=2.0 in ./env/lib/python3.6/site-packages (from asgiref~=2.1-&gt;channels_redis) (2.0.1) Collecting hiredis (from aioredis~=1.0-&gt;channels_redis) Using cached https://files.pythonhosted.org/packages/1b/98/4766d85124b785ff1989ee1c79631a1b6ecfcb444ff39999a87877b2027e/hiredis-0.2.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; File "/tmp/pip-install-aqp5bl02/hiredis/setup.py", line 81, in &lt;module&gt; 'Topic :: Software Development', File "/usr/lib/python3.6/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/home/danil/projects/python/collann/env/lib/python3.6/site-packages/setuptools/dist.py", line 364, in __init__ self.pat…
tagged with: redis
type: Question
has title: AttributeError: module 'pkg_resources' has no attribute 'safe_name' django channels redis
tagged with: python
accepted answer: http://stackoverflow.com/a/51129421
has comment: http://stackoverflow.com/comment/89369107
score: 0
linked to: http://stackoverflow.com/q/39925227
tagged with: django-channels
answer count: 1
has comment: http://stackoverflow.com/comment/89373197
has answer: http://stackoverflow.com/a/51129421

http://stackoverflow.com/a/51092818
score: 0
answers question: http://stackoverflow.com/q/51091885
type: Answer
has body: What you want are sets, not lists. They support these sort of operations very well. To make sets, either call set(xs) on a list xs, or use a set literal like {'a', 'b', ... } (as opposed to a similar list literal using square brackets). With these sets, you can do things like foo = {'a', 'b'} bar = {'b', 'c', 'd'} foo.difference(bar) # returns {'a'} foo.union(bar) # returns {'a', 'b', 'c', 'd'} foo.intersection(bar) # returns {'b'} foo.symmetric_difference(bar) # returns {'a', 'c', 'd'} ... You can also convert back to lists by calling list(foo) or similar. With these tools, you can easily build up the venn diagrams you desire. Note that all these functions return new sets, never modifying the originals.

http://stackoverflow.com/comment/89213578
type: QuestionComment
has text: If there's no explicit `return` statement `None` is returned
score: 0
comment on: http://stackoverflow.com/q/51113346
type: Comment

http://stackoverflow.com/comment/89186812
type: Comment
comment on: http://stackoverflow.com/q/51089207
type: QuestionComment
has text: Sorry If could not be more specific. K-means and Dbscan are using only euclidian distance. How would I add the **demand** restriction to the clusterization?
score: 0

http://stackoverflow.com/comment/89085064
type: Comment
has text: I have tried following queries "CREATE TABLE SectionChange(SecID integer SET DEFAULT=10, StartTime varchar(50), EndTime varchar(50), indes varchar(50))" and "CREATE TABLE SectionChange(SecID integer SET DEFAULT 10, StartTime varchar(50), EndTime varchar(50), indes varchar(50))" Why it is so only for ODBC connection?. I have heard that SET DEFAULT command works for OLE DB or ADO connection. How do i fix this without going to OLE DB or ADO connection. Please help.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51026705

http://stackoverflow.com/comment/89087120
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51045860
type: AnswerComment
has text: Could I control the robot with python?

http://stackoverflow.com/comment/89262723
type: Comment
has text: @martineau or i should say: it turns into a general dicussion about all ABCs, at least with regards to `copy()`. doesn't explain why `clear()` is left out though.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51139255

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/51158638
tag name: countvectorizer

http://stackoverflow.com/comment/89021468
comment on: http://stackoverflow.com/q/51014286
type: QuestionComment
has text: Please look at `tf.trainable_varaibles()`api.
score: 0
type: Comment

http://stackoverflow.com/q/51065115
has title: How to count different value occurrences in each hour?
has answer: http://stackoverflow.com/a/51065293
has comment: http://stackoverflow.com/comment/89120406
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89127653
downvote count: 2
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51065621
score: -1
answer count: 2
has body: I have a dataframe called df, which looks like this: with one column of timestamp and a column of s with only three possible values 1, 0, -1. Now I want to count how many 1, 0 ,-1 are in each hour. Could someone help? Thanks. timestamp s 1/6/2018 23:10 0 1/6/2018 23:15 0 1/6/2018 23:23 0 1/6/2018 23:34 0 1/7/2018 0:05 0 1/7/2018 0:09 0 1/7/2018 0:46 0 1/7/2018 0:49 0 1/7/2018 0:49 -1 1/7/2018 0:52 -1 1/7/2018 1:17 1 1/7/2018 1:26 0 1/7/2018 2:16 0 1/7/2018 2:23 1 1/7/2018 2:27 1 1/7/2018 2:34 0 1/7/2018 2:41 1 1/7/2018 2:43 1 1/7/2018 2:49 1 My desired dataframe looks something like: timestamp s_-1 s_0 s_1 1/6/2018 23:00 0 4 0 1/7/2018 0:00 2 4 0 1/7/2018 1:00 0 2 3 1/7/2018 2:00 0 2 5
favorite count: 0
has comment: http://stackoverflow.com/comment/89120280
has answer: http://stackoverflow.com/a/51065621
possible better answer: http://stackoverflow.com/a/51065293
tagged with: python

http://stackoverflow.com/a/51032001
answers question: http://stackoverflow.com/q/51031493
has body: You need to specify the local file path import boto3 import botocore from botocore.exceptions import ClientError BUCKET_NAME = 'mybucket' KEY = 'test.txt' LOCAL_FILE = '/tmp/test.txt' s3 = boto3.resource('s3') def lambda_handler(event, context): try: obj=s3.Bucket(BUCKET_NAME).download_file(LOCAL_FILE, KEY) except ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise with open('/tmp/test.txt', 'a') as fd: fd.write("this is a new string\n") s3.meta.client.upload_file(LOCAL_FILE, BUCKET_NAME, KEY) Boto3 doc reference: http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.download_file
has comment: http://stackoverflow.com/comment/89057216
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89092863

http://stackoverflow.com/q/51089777
favorite count: 0
has comment: http://stackoverflow.com/comment/89191010
tagged with: flask-admin
tagged with: python
type: AnsweredQuestion
has body: I have three tables in my SQLAlchemy database (using Flask SQLAlchemy): Product, Product variation and Order. I want to see in an order, which product and its variation it includes. It works well with relationships/foreign keys, but the main problem: if I add a product to order, I can still add variation from another product (using Flask-Admin, or just flask shell). So, main question: how to create connection between tables, so variations can be added only if they're variations of order product? Thanks :) Another solution: how to add column to Orders table, so it'll get product name from Product table, based on variation id? I tried to use column_property, Post.query.get(variation_id), variation.parent_id, backhref variation.origin_product but without any success :) My models: Product (like Samsung Galaxy 7) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), index=True) brand = db.Column(db.String(120)) variations = db.relationship('Variation', backref='origin_product', lazy='dynamic') orders = db.relationship('Order', backref='product_in_order', lazy='dynamic') Product variation (like Samsung Galaxy 7 Blue 32GB) class Variation(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), index=True) price = db.Column(db.Integer) product_id = db.Column(db.Integer, db.ForeignKey('product.id')) orders = db.relationship('Order', backref='variation_in_order', lazy='dynamic') Order class Order(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) variation_id = db.Column(db.Integer, db.ForeignKey('variation.id')) product_id = db.Column(db.Integer, db.ForeignKey('product.id')) P.S. product_id = db.Column(db.Integer, db.ForeignKey('variation.product_id')) works in db, I see right product id. Still external tools like Flask-Admin see product_id column as variation object, so no use. Need a way, to connect product object to…
downvote count: 0
has title: Flask SQLAlchemy: How to add a column that depends on another table?
score: 6
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89200931
has comment: http://stackoverflow.com/comment/89201740
upvote count: 6
tagged with: flask
has comment: http://stackoverflow.com/comment/89194767
has answer: http://stackoverflow.com/a/51108595
accepted answer: http://stackoverflow.com/a/51108595
answer count: 1
tagged with: flask-sqlalchemy

http://stackoverflow.com/a/51121924
upvote count: 1
answers question: http://stackoverflow.com/q/51084602
score: 1
downvote count: 0
has body: This behaviour is dependent on different incompatible versions of libjpeg used by cv2 and PIL/Pillow, as @fireant already pointed out. For example, when I try to run this code with older versions of Pillow (like 3.4.2), it generates same output. In my tests, Pillow 3.4.2 and older (oldest version tried was 2.2.0) all use libjpeg 8, while Pillow 4.0.0 and newer use libjpeg 9.2. OpenCV, on the other hand, might use different versions on different systems: On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian* and Ubuntu*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. So on Debian/Ubuntu systems opencv might use libjpeg-turbo which comes with the OS. (My machine, specifically, had version 8 installed.) The way to fix this is to ensure that both Pillow and OpenCV use same libjpeg version. You could try this: if you have relatively new PIL/Pillow, downgrade it to version <= 3.4.2 (this is what worked for me) pip install Pillow==3.4.2 if you have old Pillow version, you could try to upgrade it to version >= 4.0.0 If that doesn't help, your solution could be either of two: recompiling your OpenCV with same libjpeg flavor as used by Pillow. reinstalling Pillow from source using same libjpeg version as used by OpenCV.
type: Answer

http://stackoverflow.com/a/51017696
has comment: http://stackoverflow.com/comment/89055070
type: Answer
has comment: http://stackoverflow.com/comment/127784056
answers question: http://stackoverflow.com/q/51014954
accepted answer of: http://stackoverflow.com/q/51014954
score: 8
type: AcceptedAnswer
has body: The problem is in the call to run_in_executor: futures = [ loop.run_in_executor( executor, searching(queries) ) ] run_in_executor accepts a function to execute. The code doesn't pass it a function, it calls a function, searching, and passes run_in_executor the return value of that call. That has two consequences: the code doesn't work as intended - it invokes the searches one by after the other, not in parallel; it displays an error complaining of an attempt by run_in_executor to invoke the None return value of searching(...). Confusingly, the error is raised only later, when awaiting the futures returned by run_in_executor, by which time all the searches have actually finished. The correct way to call run_in_executor would be something like: futures = [ loop.run_in_executor(executor, searching, queries) ] Note how the searching function is now only mentioned rather than used. Also, if you are only using asyncio to invoke synchronous calls in run_in_executor, you are not really benefiting from its use. You could get the same effect using threading-based tools from concurrent.futures directly, but without the need to adjust your whole program to asyncio. run_in_executor is meant to be used sparingly, either for occasional interfacing with legacy APIs that don't provide an async front-end, or for CPU-heavy code which cannot be meaningfully converted to coroutines.
downvote count: 0
upvote count: 8

http://stackoverflow.com/a/51158930
answers question: http://stackoverflow.com/q/51158872
type: Answer
has body: You don't need to explicitly loop. You can use zip to join your two lists and then wrap it in a dict for the result you're looking for: &gt;&gt;&gt; dict(zip(num_list, name_list)) {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51158872
score: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89136384
comment on: http://stackoverflow.com/q/51072660
has text: Yes and no. What they are possibly getting at is that you have outlined a solution for some problem you haven't really explained in detail why you need it. You are then asking how to get your solution working. The reason for going more into the actual problem or reason why you need it, is that someone may suggest a completely different way of doing it which may be simpler or more appropriate. It is not uncommon to get this response as many questions on SO are like this. Help me with this specific solution, when there was often better solutions to begin with.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89107872
score: 0
has text: Your CPU does not support AVX -- see question & answer above.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51056479

http://stackoverflow.com/a/51161401
score: 2
answers question: http://stackoverflow.com/q/51159297
upvote count: 2
downvote count: 0
type: Answer
has body: For background, if you use View Package File from the command palette to view Default/exec.py you can examine the code that's being used to execute programs and display their output into the panel. As a short synopsis, the program is executed in a background thread, and the output of stdout and stderr are read from using this code: def read_fileno(self, fileno, execute_finished): decoder_cls = codecs.getincrementaldecoder(self.listener.encoding) decoder = decoder_cls('replace') while True: data = decoder.decode(os.read(fileno, 2**16)) if len(data) &gt; 0: if self.listener: self.listener.on_data(self, data) else: try: os.close(fileno) except OSError: pass if execute_finished and self.listener: self.listener.on_finished(self) break That is, whenever they read any data, they invoke on_data() in the object that's listening for results, which in this case is the exec command itself. The implementation of that method looks like this: def on_data(self, proc, data): # Normalize newlines, Sublime Text always uses a single \n separator # in memory. data = data.replace('\r\n', '\n').replace('\r', '\n') self.append_string(proc, data) Internally Sublime uses \n as the line separator, so on windows \r\n is interpreted as \n, and on MacOS \r is interpreted as \n as well. So on the one hand this doesn't do what you expect because your \r is effectively treated the same as \n is. Aside of that, if you trace the call to append_string() through the guard code that keeps it thread safe and allows it to interact with the Sublime core, it ends up in a line that looks like this: self.output_view.run_command( 'append', {'characters': characters, 'force': True, 'scroll_to_end': True}) That is, whatever characters you provide, they're directly appended to the output buffer without regard to what they might contain. If you were to provide a custom build target (a somewhat advanced plugin but still possible) this behaviour could be modified, although it might be tricky to get it to work on Mac…

http://stackoverflow.com/q/51031359
has comment: http://stackoverflow.com/comment/89146538
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/51068486
upvote count: 2
has comment: http://stackoverflow.com/comment/89146666
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89222115
score: 2
has body: I am trying to run python code in ROS and it includes a module (module not made for ROS) that I had to pip install. When I try running the code in my catkin workspace with roscore running, it cannot find the module I installed and gives me an ImportError. Any idea on how to run already created modules on ROS with rospy?
has title: Python Modules and submodules in ROS catkin workspace
has comment: http://stackoverflow.com/comment/89107356
type: Question
tagged with: ros
answer count: 1
downvote count: 0
favorite count: 0
tagged with: rospy

http://stackoverflow.com/q/51137770
tagged with: torrent
tagged with: magnet-uri
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: libtorrent
tagged with: libtorrent-rasterbar
has title: Libtorrent: Add multiple tracker in magnet_link uri
has answer: http://stackoverflow.com/a/51138073
tagged with: python
has body: I am trying to use multiple tracker in libtorrent. I am using magnet_link instead of torrent file directly in leechers. While seeding I am able to add multiple tracker in add_tracker(). But when I am generating magnet_link like: magnet_link = "magnet:?xt=urn:btih:"+b32hash+"&amp;tr="+tracker I am not sure, how can I add multiple tracker in tr="+tracker Seeder side code to generate magnet link: torrent = open(tfile_path, 'r').read() metadata = lt.bdecode(torrent) hashcontents = lt.bencode(metadata['info']) digest = hashlib.sha1(hashcontents).digest() b32hash = base64.b32encode(digest) magnet_link = "magnet:?xt=urn:btih:"+b32hash+"&amp;tr="+tracker Leecher side code to use magnet_link: params = {'save_path': temp_path} h = lt.add_magnet_uri(ses, magnet_link, params)
type: AnsweredQuestion
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51138073

http://stackoverflow.com/a/52845239
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51071212
answers question: http://stackoverflow.com/q/51071212
has body: Ok, here is bijective mapping from index to 5bytes string and back, based on Linear Congruential Generator. I used constants for drand48, seems to work fine for 40bits LCG, with seed 1 I tested all 240 values and got full period. It relies on unsigned 64bit math with masked overflow, thus heavy use of NumPy. Packing and unpacking done in somewhat crude way, lots of things to improve. Don't hesitate to ask questions. import numpy as np # unsigned constants ZERO = np.uint64(0) ONE = np.uint64(1) # signed constants SZERO = np.int64(0) SONE = np.int64(1) MONE = np.int64(-1) # LCG parameters bits = np.uint64(40) mult = np.uint64(25214903917) incr = np.uint64(11) mod = np.uint64( np.left_shift(ONE, bits) ) mask = np.uint64(mod - ONE) def rang(seed: np.uint64) -&gt; np.uint64: """ LCG mapping from one 40bit integer to another """ return np.uint64(np.bitwise_and(mult*np.uint64(seed) + incr, mask)) def compute_nskip(nskp: np.int64) -&gt; np.int64: nskip: np.int64 = nskp while nskip &lt; SZERO: t: np.uint64 = np.uint64(nskip) + mod nskip = np.int64(t) return np.int64( np.bitwise_and(np.uint64(nskip), mask) ) def skip(nskp: np.int64, seed: np.uint64) -&gt; np.uint64: # inverse mapping """ Jump from given seed by number of skips """ nskip: np.int64 = compute_nskip(nskp) m: np.uint64 = mult # original multiplicative constant c: np.uint64 = incr # original additive constant m_next: np.uint64 = ONE # new effective multiplicative constant c_next: np.uint64 = ZERO # new effective additive constant while nskip &gt; SZERO: if np.bitwise_and(nskip, SONE) != SZERO: # check least significant bit for being 1 m_next = np.bitwise_and(m_next * m, mask) c_next = np.bitwise_and(c_next * m + c, mask) c = np.bitwise_and((m + ONE) * c, mask) m = np.bitwise_and(m * m, mask) nskip = np.right_shift(nskip, SONE) # shift right, dropping least significant bit # with G and C, we can now find the new seed return np.bitwise_and(m_next * seed + c_next, mask) def index2bytes(i: np.uint64) -&gt; bytes: bbb: …
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51045839
favorite count: 0
has comment: http://stackoverflow.com/comment/89101799
upvote count: 3
has comment: http://stackoverflow.com/comment/89103127
tagged with: python
has answer: http://stackoverflow.com/a/52384435
answer count: 4
tagged with: conv-neural-network
downvote count: 0
tagged with: pytorch
has answer: http://stackoverflow.com/a/57436834
has title: Pytorch inceptionV3 transfer learning gives error - max() received an invalid combination of arguments
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/51056318
tagged with: deep-learning
has body: The program for transfer learning inception_v3 in pytorch that i am using is here : https://drive.google.com/file/d/1zn4z7nOp_wJne0En6zq4WJfwHVVftERT/view?usp=sharing I am getting the following error upon running the program : Epoch 0/24 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-20-cc88ea5f8bd3&gt; in &lt;module&gt;() 1 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, ----&gt; 2 num_epochs=25) &lt;ipython-input-17-812cf3c4576a&gt; in train_model(model, criterion, optimizer, scheduler, num_epochs) 33 outputs = model(inputs) 34 print(outputs) ---&gt; 35 _, preds = torch.max(outputs, 1) 36 loss = criterion(outputs, labels) 37 TypeError: max() received an invalid combination of arguments - got (tuple, int), but expected one of: * (Tensor input) * (Tensor input, Tensor other, Tensor out) * (Tensor input, int dim, bool keepdim, tuple of Tensors out) How can this be fixed ? Thank you
has answer: http://stackoverflow.com/a/53830126

http://stackoverflow.com/comment/89322059
has text: @amplifier I didn't find this on document. You can open an issue to [this document](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support). This is what Roman Kiss found. Please check [this thread](https://social.msdn.microsoft.com/Forums/azure/en-US/dafff4bb-7c59-4ab1-96ed-9f3834488f12/azure-iothub-devicemessage-and-route-filter?forum=azureiothub).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51166935

http://stackoverflow.com/comment/109104441
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51077870
has text: You can follow these steps to get a GPU or TPU in colab:- Runtime-> change Runtime

http://stackoverflow.com/comment/89183354
has text: @Zephyr - I am lost, what is expected output for your another DataFrame?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51096122
type: Comment

http://stackoverflow.com/comment/89198272
comment on: http://stackoverflow.com/q/51045716
score: 0
type: Comment
type: QuestionComment
has text: I'm using a classic load balancer, and everything is communicating well with the flask server, except for the call to `.get()` which freezes the instance. If I don't make the call to `.get()`, the rest of the web app continues to work as expected.

http://stackoverflow.com/q/51125432
linked to: http://stackoverflow.com/q/16176469
linked to: http://stackoverflow.com/q/5008828
has body: I have a method that group a list of dict by a key. To do it I found here that I have to use the groupby function but before I have to sort the list. Here is my method right now: def group_list_by_key(data, key): data.sort(key=lambda x: x[key]) result = [] for k, v in groupby(data, key=lambda x: x[key]): result.append(list(v)) return result This piece of code works only if every key is defined in all the dicts and the values are all of the same type. However, where I use this method I don't know if the key is defined everywhere and if they are of the same type. On Python 2.x I know that exists sorted function with cmp parameter that could do a custom sort but from Python 3.x this isn't possible anymore. Is there a way to make a custom sort? I am thinking about use the classic sort by &lt; and sorting also by typename. By now I thought about use the get function and cast to string in the sort like data.sort(key=lambda x: str(x.get(key))) ... for k, v in groupby(data, key=lambda x: x.get(key)): It only overcomes in case of string, numeric and None content but not a generic object and it breaks easily if for example I execute a = [{'b': 0, 'c': 1}, {'b': '0'}, {'b': 0, 'c': 2}, {'b': 1}, {'c': 3}] group_list_by_key(a, 'b') The output is [[{'b': 0, 'c': 1}], [{'b': '0'}], [{'b': 0, 'c': 2}], [{'b': 1}], [{'c': 3}]] instead of what I expect should be (order of lists is not a problem) [[{'b': 0, 'c': 1}, {'b': 0, 'c': 2}], [{'b': '0'}], [{'b': 1}], [{'c': 3}]]
tagged with: sorting
has comment: http://stackoverflow.com/comment/89235956
has answer: http://stackoverflow.com/a/51125682
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51139725
type: Question
has comment: http://stackoverflow.com/comment/89263026
has comment: http://stackoverflow.com/comment/89236248
tagged with: python
accepted answer: http://stackoverflow.com/a/51125682
possible better answer: http://stackoverflow.com/a/51139725
has comment: http://stackoverflow.com/comment/89236695
upvote count: 3
answer count: 2
has title: Sort list of dict by key with different types in Python 3

http://stackoverflow.com/a/51154374
score: 2
accepted answer of: http://stackoverflow.com/q/51154179
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51154179
has comment: http://stackoverflow.com/comment/89294114
type: Answer
has comment: http://stackoverflow.com/comment/89292719
upvote count: 2
has body: The recommanded (and most readable and portable) solution is to use str.format(): set_drive = "ON" template = """ <?xml version="1.0" encoding="UTF-8"?> setRequest <Mnet Group="18" Drive="{set_drive}" Mode="COOL" SetTemp="19" AirDirection="HORIZONTAL" FanSpeed="HIGH" /> """ soup = post(template.format(set_drive=set_drive))

http://stackoverflow.com/comment/89298401
score: 0
comment on: http://stackoverflow.com/a/51157312
type: Comment
has text: Error i am getting now : `python: can't open file 'server.py': [Errno 2] No such file or directory`. Can you please tell me what is going wrong now.
type: AnswerComment

http://stackoverflow.com/comment/89301034
type: Comment
type: QuestionComment
has text: I am writing list and downloading as csv file. In csv file, I see special character. But, actually there is no special character. I found that \xa0 is coming instead of space. For testing, I have created a list including \xa0 csv_list = [['hfhf\xa0 fsdg','dsf'],['fsdgs fsdfs','fsdfsd'],['dsf\xa0 sf','asfg']]
comment on: http://stackoverflow.com/q/51158537
score: 0

http://stackoverflow.com/comment/89137845
type: Comment
comment on: http://stackoverflow.com/a/51057510
has text: Thought 100 falls into the case of 90-100. Move it along with the 0 condition check will fix that. So if marks == 0 or marks == 100 and elif marks > 0 and marks < 100
type: AnswerComment
score: 0

http://stackoverflow.com/q/51064456
tagged with: python
tagged with: pca
has comment: http://stackoverflow.com/comment/89223126
downvote count: 1
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/89122360
has answer: http://stackoverflow.com/a/51066058
upvote count: 0
has answer: http://stackoverflow.com/a/51066499
tagged with: scikit-learn
score: -1
has title: Principal component analysis dimension reduction in python
favorite count: 0
has body: I have to implement my own PCA function function Y,V = PCA(data, M, whitening) that computes the first M principal components and transforms the data, so that y_n = U^T x_n. The function should further return V that explains the amount of variance that is explained by the transformation. I have to reduce the dimension of data D=4 to M=2 > given function below &lt; def PCA(data,nr_dimensions=None, whitening=False): """ perform PCA and reduce the dimension of the data (D) to nr_dimensions Input: data... samples, nr_samples x D nr_dimensions... dimension after the transformation, scalar whitening... False -&gt; standard PCA, True -&gt; PCA with whitening Returns: transformed data... nr_samples x nr_dimensions variance_explained... amount of variance explained by the the first nr_dimensions principal components, scalar""" if nr_dimensions is not None: dim = nr_dimensions else: dim = 2 what I have done is the following: import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt import scipy.stats as stats from scipy.stats import multivariate_normal import pdb import sklearn from sklearn import datasets #covariance matrix mean_vec = np.mean(data) cov_mat = (data - mean_vec).T.dot((data - mean_vec)) / (data.shape[0] - 1) print('Covariance matrix \n%s' % cov_mat) #now the eigendecomposition of the cov matrix cov_mat = np.cov(data.T) eig_vals, eig_vecs = np.linalg.eig(cov_mat) print('Eigenvectors \n%s' % eig_vecs) print('\nEigenvalues \n%s' % eig_vals) # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))] This is the point where I don't know what to do now and how to reduce dimension. Any help would be welcome! :)
type: UnansweredQuestion
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89122442

http://stackoverflow.com/q/51043847
has answer: http://stackoverflow.com/a/51043970
has comment: http://stackoverflow.com/comment/89079131
has comment: http://stackoverflow.com/comment/89078778
score: -3
downvote count: 4
has comment: http://stackoverflow.com/comment/89079041
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89078762
accepted answer: http://stackoverflow.com/a/51043970
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/41535571
has comment: http://stackoverflow.com/comment/89078700
has title: How to replace characters in strings without the Python re library
has body: I am able to replace characters in strings using the Python re library, but I need to use the pyparsing library (or no library at all) instead. Is there another way to do this without re? import re string = re.sub(r'[\t\r\n]', '', string)
upvote count: 1
answer count: 1

http://stackoverflow.com/a/51391450
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51091250
score: 0
answers question: http://stackoverflow.com/q/51091250
type: Answer
has body: Just to make sure I don't leave everyone hanging, I figured out the solution. It's very strange. All I did was call the parameters in a different order, and now it works every time. They work in any order if I input the command manually, but if I issue the command from python it seems it will only work if I write the output parameter first. Not sure if this is a problem with python or with the application I'm writing the command to.

http://stackoverflow.com/q/51077716
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51085973
possible better answer: http://stackoverflow.com/a/51077717
type: Question
answer count: 2
downvote count: 0
has title: Multi view chart that shares data at the top level in Altair
tagged with: altair
has answer: http://stackoverflow.com/a/51077717
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51085973
has body: How can we create multi-view charts which share data at the top level in Altair? For example, how do we avoid the following situation, in which the dataset is repeated twice in the spec: import altair as alt import pandas as pd data = pd.DataFrame({'x': [1.1, 2.5, 3.2], 'y': [0.8, 1.1, 2.7]}) c1 = alt.Chart(data).mark_point().encode(x='y', y='x') c2 = alt.Chart(data).mark_bar().encode(x='y', y='x') chart = c1 | c2

http://stackoverflow.com/comment/89079017
has text: thanks, but i may not describe my question clearly, however jezrael offer the answer i intend to ask
comment on: http://stackoverflow.com/a/51043377
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/71117815
has body: Adding to the accepted answer : One issue can be user delegation: ie python module installed with userx spark-submit launched by userx but spark is the technical user executing logic on the workers. (behind the scenes, without you noticing). It might be that sparkis not seeing the module. To fix that : su as spark, and install the missing module via pipinstall (on all workers) That fixed it for me. Edit : depending on your settings pyspark shell might still be able to see your module though.
score: 0
answers question: http://stackoverflow.com/q/51084514
type: Answer

http://stackoverflow.com/q/51058880
has answer: http://stackoverflow.com/a/51058966
has answer: http://stackoverflow.com/a/51059180
has comment: http://stackoverflow.com/comment/89108172
has answer: http://stackoverflow.com/a/51059006
type: Question
upvote count: 4
answer count: 8
has answer: http://stackoverflow.com/a/51059150
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52828096
has answer: http://stackoverflow.com/a/51059068
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89108447
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89108007
has answer: http://stackoverflow.com/a/51058983
tagged with: python
has answer: http://stackoverflow.com/a/51059055
has title: Write a for loop to remove punctuation
has body: I've been tasked with writing a for loop to remove some punctuation in a list of strings, storing the answers in a new list. I know how to do this with one string, but not in a loop. For example: phrases = ['hi there!', 'thanks!'] etc. import string new_phrases = [] for i in phrases: if i not in string.punctuation Then I get a bit stuck at this point. Do I append? I've tried yield and return, but realised that's for functions.

http://stackoverflow.com/a/51984340
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51107319
has body: Step1: check http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame to find a Windows installer that matches the version of Python you're running. The current version of pygame is : pygame-1.9.4-cp37-cp37m-win_amd64.whl Move this file to the folder C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts ========================================= Step2: open cmdand then type: cd\ cd /d C:\Windows cd /d C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts and then type the command: pip install pygame Now you have successfully installed pygame package. ========================================= Step3: open PyCharm File >> setting make sure the "Project Interpreter" has the "pygame" package like the following: File>>Setting>> make sure the "pygame" package is there.
score: 2
downvote count: 0

http://stackoverflow.com/q/51105771
answer count: 2
has answer: http://stackoverflow.com/a/59803188
linked to: http://stackoverflow.com/q/3085696
downvote count: 0
favorite count: 0
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/89198714
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51106148
upvote count: 3
has title: Scrolling Notebook Tabs Tkinter
type: Question
has body: I want to make a lot of notebook tabs, and I want to put them in canvas and to add a horizontal scrollbar so that I can scroll trough them. I set the canvas size, but canvas size keep changing when I add new tab. Also, scrollbar does not work, can you tell me what am I doing wrong? The program does not show me any error. This is the code: from tkinter import * from tkinter import ttk myApp = Tk() myApp.title(" Program ") myApp.geometry("900x500") CanvasTabs = Canvas(myApp, width=50, height=50) CanvasTabs.grid(row=0,column=0) tabs = ttk.Notebook(CanvasTabs, width=100, height=100) tab1 = ttk.Frame(tabs) tabs.add(tab1,text=" Tab 1 ") tab2 = ttk.Frame(tabs) tabs.add(tab2,text=" Tab 2 ") tab3 = ttk.Frame(tabs) tabs.add(tab3,text=" Tab 3 ") tab4 = ttk.Frame(tabs) tabs.add(tab4,text=" Tab 4 ") hbar=Scrollbar(CanvasTabs,orient=HORIZONTAL) hbar.pack(side=TOP,fill=X) hbar.config(command=CanvasTabs.xview) CanvasTabs.config(xscrollcommand=hbar.set) tabs.pack(expand=1, fill="both") myApp.mainloop()
has comment: http://stackoverflow.com/comment/89198982
possible better answer: http://stackoverflow.com/a/59803188
accepted answer: http://stackoverflow.com/a/51106148

http://stackoverflow.com/comment/89113316
score: 0
comment on: http://stackoverflow.com/a/51060284
type: AnswerComment
type: Comment
has text: My email is lalakv0824@gmail.com. Thank you very much for your consistent replies!

django-generic-views
type: Tag
tags question: http://stackoverflow.com/q/51050277
tag name: django-generic-views

http://stackoverflow.com/a/63218374
answers question: http://stackoverflow.com/q/51143458
type: Answer
upvote count: 4
score: 4
downvote count: 0
has body: Delay in milliseconds. 0 is the special value that means “forever”. The function waitKey waits for a key event infinitely (when \texttt{delay}\leq 0 ) or for delay milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed. Note: This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing. Note: The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active

http://stackoverflow.com/q/51081451
tagged with: python
has comment: http://stackoverflow.com/comment/89151883
has comment: http://stackoverflow.com/comment/89151278
has body: I have a function into which I pass variables. I do not change the names of the variables. I expect the variable inside the function to be treated as a local variable but in several instances it appears to actually change the variable of the same name outside the function. I don't think this should be happening. Anyone experienced it? So, I have this: def(df1,df2,df3) df1.set_index('A',inplace=True) df2['c'] = df1['B'] * df3['G'] return df2 I am finding that df1.set_index('A',inplace=True) is changing df1 outside the function. So when I call the function again I get an error because the function doesn't "see" df1['A'] in df1. It sees df1 passed from the "outside" as having the index set to 'A' already in an earlier call. Anyone get this kind of memory bleed?
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51082252
linked to: http://stackoverflow.com/q/986006
type: Question
has title: Python Functions Memory Bleed
has comment: http://stackoverflow.com/comment/89153138
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89151363
has comment: http://stackoverflow.com/comment/89151343
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/89099895
score: 1
has text: Thanks for the response, I was able to solve the issue through a combination of your suggestion and what has been discussed in the following link: https://stackoverflow.com/questions/46598341/keras-batchnormalization-population-parameters-update-while-training-in-tensorfl
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51035474

http://stackoverflow.com/q/51140493
has comment: http://stackoverflow.com/comment/89520979
answer count: 1
has title: InvalidArgumentError: Incompatible shapes: [400] vs. [50]
accepted answer: http://stackoverflow.com/a/51492769
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89265618
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51492769
has body: I'm fairly new to tensorflow. I've build a multilayer CNN for binary classification This is code I've done so far # First Layer W_conv1 = weight_variable([11, 11, 1, 32]) b_conv1 = bias_variable([32]) x_image = tf.reshape(x, [-1,64,64,1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) print(h_conv1.shape) print(h_pool1.shape) # Second Layer W_conv2 = weight_variable([7, 7, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) print(h_conv2.shape) print(h_pool2.shape) #Third Layer W_conv3 = weight_variable([5, 5, 64, 128]) b_conv3 = bias_variable([128]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) h_pool3 = max_pool_2x2(h_conv3) print(h_conv3.shape) print(h_pool3.shape) # Fourth Layer W_conv4 = weight_variable([3, 3, 128, 64]) b_conv4 = bias_variable([64]) h_conv4 = tf.nn.relu(conv2d(h_pool3, W_conv4) + b_conv4) h_pool4 = max_pool_2x2(h_conv4) print(h_conv4.shape) print(h_pool4.shape) #Fifth Layer W_conv5 = weight_variable([2, 2, 64, 32]) b_conv5 = bias_variable([32]) h_conv5 = tf.nn.relu(conv2d(h_pool4, W_conv5) + b_conv5) h_pool5 = max_pool_2x2(h_conv5) print(h_conv5.shape) print(h_pool5.shape) # Densely Connected Layer W_fc1 = weight_variable([2 * 2 * 32, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool4, [-1, 2*2*32]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) print(h_pool2_flat.shape) print(h_fc1.shape) The output of the following piece of code is - (?, 64, 64, 32) (?, 32, 32, 32) (?, 32, 32, 64) (?, 16, 16, 64) (?, 16, 16, 128) (?, 8, 8, 128) (?, 8, 8, 64) (?, 4, 4, 64) (?, 4, 4, 32) (?, 2, 2, 32) (?, 256) (?, 1024) When I run the program I'm getting the following error InvalidArgumentError (see above for traceback): Incompatible shapes: [400] vs. [50] [[Node: Equal_4 = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ArgMax_8, ArgMax_9)]] The traceback is really long , i ho…
has comment: http://stackoverflow.com/comment/89521463
has comment: http://stackoverflow.com/comment/89521540
has comment: http://stackoverflow.com/comment/89265248
score: 0

http://stackoverflow.com/q/51111676
has answer: http://stackoverflow.com/a/51111700
downvote count: 5
linked to: http://stackoverflow.com/q/7129285
tagged with: function
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89210410
tagged with: python-3.x
tagged with: calling-convention
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51111711
tagged with: python
has comment: http://stackoverflow.com/comment/89210330
has body: def function_1(): return (5) return (6) return(7) result_1 = function_1() print(result_1) Why is is that when I print the call of function_1(), only the first value, 5, is printed?
score: -5
has comment: http://stackoverflow.com/comment/89210333
has answer: http://stackoverflow.com/a/51111695
type: Question
has title: Python: Multiple return values assigned to each function?
has answer: http://stackoverflow.com/a/51111691
has answer: http://stackoverflow.com/a/51111725

aws-regions
type: Tag
tag name: aws-regions
tags question: http://stackoverflow.com/q/51042824

http://stackoverflow.com/a/51051772
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89158881
accepted answer of: http://stackoverflow.com/q/51046983
upvote count: 8
has comment: http://stackoverflow.com/comment/89094771
answers question: http://stackoverflow.com/q/51046983
type: Answer
score: 8
has body: here is one way to do it: ax=df.plot(kind='bar', stacked=True) #loop to add the text list_values = (dffinal['numPatients6month'].tolist()[::3] + dffinal['numPatients6month'].tolist()[1::3] + dffinal['numPatients6month'].tolist()[2::3]) for rect, value in zip(ax.patches, list_values): h = rect.get_height() /2. w = rect.get_width() /2. x, y = rect.get_xy() ax.text(x+w, y+h,value,horizontalalignment='center',verticalalignment='center') #same than your code plt.xticks(range(0,10), ['6month','1 year','1.5 year','2 year','2.5 year','3 year','3.5 year','4 year','4.5 year','5 year'], fontsize=8, rotation=45) plt.title('Cognitive Impairement-Stack bar') plt.show() The list_values is to get the value from the column 'numPatients6month' in the same order than the rect from ax.patches and the result is: but because some bars are small the results is not really easy to read. EDIT: about the loop, ax.patches contains informations about all the bar you plot, so for each bar that I named rect, with get_xy you get the position of the bottom left corner of the bar, and with get_height (r. get_width) get the height (r. width) of the bar. so (x+w, y+h) gives the coordinates of the middle of the bar, where you add the text value (from list_values) with the function ax.text (parameters horizontalalignment and verticalalignment are to center the text) EDIT 2: more general method, thanks to @SpghttCd for getting list_values list_values = (dffinal.drop('final-formula', 1).groupby(['6month','Question Text']).sum() .unstack('Question Text').fillna(0).astype(int).values.flatten('F')) for rect, value in zip(ax.patches, list_values): if value != 0: h = rect.get_height() /2. w = rect.get_width() /2. x, y = rect.get_xy() ax.text(x+w, y+h,value,horizontalalignment='center',verticalalignment='center')
has comment: http://stackoverflow.com/comment/89094821

http://stackoverflow.com/q/51043560
has answer: http://stackoverflow.com/a/51044817
has comment: http://stackoverflow.com/comment/89078515
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89078663
has comment: http://stackoverflow.com/comment/89078228
has comment: http://stackoverflow.com/comment/89078485
type: Question
score: 0
has title: Not able to get the response from django rest api using requests.get() method
has comment: http://stackoverflow.com/comment/89078818
answer count: 1
has body: I have created a Django Rest Application and exposed one service (To get the User List) Now when I am trying to call thru curl request, I am able to get the User List. curl -v -XGET -i 'http://XXX.XX.XX9.XX1:8000/ebxxx/api/users/' But When I try to call it from another app using requests.get() method , I am getting 504 server error: I am trying : header = {"Content-type":"application/json"} response = requests.get("http://XXX.XX.XX9.XX1:8000/ebxxx/api/users/", headers=header) Error: "response , response&lt;504>"
has comment: http://stackoverflow.com/comment/89079734
accepted answer: http://stackoverflow.com/a/51044817
has comment: http://stackoverflow.com/comment/89080748
has comment: http://stackoverflow.com/comment/89079885
tagged with: django
tagged with: python

http://stackoverflow.com/q/51106830
has answer: http://stackoverflow.com/a/57186157
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/74396607
downvote count: 0
has title: How to call Python functions from JavaScript in Django?
type: Question
has answer: http://stackoverflow.com/a/60029921
has body: I've been struggling on this for a couple days. I've read through many posts, blogs, and watch video demo on Django projects, but nothing quite answers my problem. I have a Django webapp that uses a Python API to connects to a third-party service to analyze text data. The user writes into a text area, presses the button, then the text is sent to the service which returns a list of JSON objects. The API call to this service is a Python function. I'm trying to use Ajax to make an async call to the Python function using the text data as a param when the button is pressed. I'm not at this time trying to invoke my third-party service, yet. I'm just trying to see if I can get a response from Python sending input and receiving output. Most of the examples I've found involve creating a form and submitting it so the Django framework automatically calls it's Python functions. A form is not exactly what I'm trying to build, nor am I wanting to proceed to a new page to see the results or refresh the current one. Test Data # models.py from django.db import models # Function I want to call from Ajax def testcall(): return 'test successfull' EDIT: I almost have it working. I'm just getting syntax errors with ajax I can't figure out. Could not parse the remainder: ' 'ajax-test-view'' from 'url 'ajax-test-view'' EDIT I fixed all the syntax errors but now I'm getting 404 errors when trying to execute the target python script. I now understand how url and pathing works in Django, but using Kostadin Slavov's solution, how can I do this without routing to a specific html? In the ajax, I'm setting the url like this: url: '{{ 'ajax-test-view' }}', And in my python I have the url pattern set like this: path(r'^django-app/$', views.testcall, name = 'ajax-test-view'), It seems like the variable in the ajax url points to the name field in the url pattern, but that also seems to be the name of a specific html file to render(?) Or is it the name of the py function? When I click my button the aj…
accepted answer: http://stackoverflow.com/a/51106920
tagged with: ajax
upvote count: 2
has answer: http://stackoverflow.com/a/74396607
has answer: http://stackoverflow.com/a/51107151
linked to: http://stackoverflow.com/q/47563013
has answer: http://stackoverflow.com/a/51106920
favorite count: 0
answer count: 5

http://stackoverflow.com/comment/89094999
type: QuestionComment
type: Comment
has text: You sure? A str should have double quotes. Please paste as it's shown
comment on: http://stackoverflow.com/q/51051619
score: 0

http://stackoverflow.com/comment/89016083
type: QuestionComment
has text: yes, p is small, 0.01 to 0.1 (1-10% chance of modification)
comment on: http://stackoverflow.com/q/51011601
score: 0
type: Comment

http://stackoverflow.com/comment/89168675
comment on: http://stackoverflow.com/a/51089712
has text: I mean I could be wrong, early days. Just to clarify I mean static as in variables that have only one instance and will contain the same value at a given time no matter where they are called from. The ability to be altered is very much a good thing.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89084825
score: 0
type: Comment
has text: I could also take out *args and list = [*args] on both functions and just say for value in source_list or keyword_list ---- i just realized that
type: AnswerComment
comment on: http://stackoverflow.com/a/51046643

http://stackoverflow.com/q/51061439
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89113187
type: Question
has title: Django unicode of object id raise TypeError: coercing to Unicode
score: 0
has body: I have a django model named UserProfile. Here is my code: user_profile = UserProfile.objects.filter(id = 1).first() if user_profile: user_profile_id = user_profile.id user_details = 'user id: ' + unicode(user_profile_id) The code runs normally fine, but today I got an exception in line 4 (the last line): TypeError: coercing to Unicode: need string or buffer, NoneType found I have no clue what possibly could have gone wrong here.
has comment: http://stackoverflow.com/comment/89112859
has comment: http://stackoverflow.com/comment/89118175
answer count: 1
has answer: http://stackoverflow.com/a/51061566
tagged with: unicode
has comment: http://stackoverflow.com/comment/89112973
has comment: http://stackoverflow.com/comment/89118116
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89113129
has comment: http://stackoverflow.com/comment/89113115
has comment: http://stackoverflow.com/comment/89113382

http://stackoverflow.com/q/51065365
score: 2
has comment: http://stackoverflow.com/comment/89120788
tagged with: regex-lookarounds
type: AnsweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89136634
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51066235
has comment: http://stackoverflow.com/comment/89121237
has body: I am trying to split a comma delimited string using the following code. The regex code for comma-delimited is used in one of my online courses. I am trying to understand the following regex with lookaround how it works but couldn't get it completely. Can someone let me know how it works? I know ?: is for non-capturing group and ?= is for look ahead but not sure how it works in the current context. import re pattern = re.compile(r',(?=(?:[^"]*"[^"]*")*[^"]*$)') text = 'tarcac,"this is, test1","this is, test2", 123566, testdata' results= re.split(pattern, text) for r in results: print(r.strip()) Output is tarcac "this is, test1" "this is, test2" 123566 testdata
upvote count: 3
has comment: http://stackoverflow.com/comment/89120623
accepted answer: http://stackoverflow.com/a/51066235
linked to: http://stackoverflow.com/q/22937618
downvote count: 1
answer count: 1
has title: Python RegEx Comma Delim
duplicate of: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/89125719

http://stackoverflow.com/comment/89154787
has text: Why would anyone want to do something like this aside - you're creating a circular dependency here. How can the Python interpreter import your module which depends on another module which itself depends on the first module - no import can ever be completed in this setting? I'd rethink the design if I were you.
score: 1
comment on: http://stackoverflow.com/q/51082728
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51166970
has answer: http://stackoverflow.com/a/51167051
possible better answer: http://stackoverflow.com/a/51166994
downvote count: 1
accepted answer: http://stackoverflow.com/a/51167051
upvote count: 4
has answer: http://stackoverflow.com/a/51167036
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51167214
favorite count: 0
has body: I have to check in a while loop. I have found the following code it shows the file without while loop. for file in glob.glob("*.txt"): print(file) but it does not work in a while loop if i use the following code a = os.listdir(my_path) #print(a) for file in glob.glob("*.txt"): print(file) I am trying to program a watcher type in python with OS module
has title: How can I check if only txt file exists in a directory with python?
type: Question
has answer: http://stackoverflow.com/a/51166994
score: 3
tagged with: python

http://stackoverflow.com/a/51034440
has body: You should include a specific exception. For example, try: &lt;stuff&gt; except IndexError: &lt;stuff&gt; Instead of try: &lt;stuff&gt; except: &lt;stuff&gt; It helps with debugging - you'll know if an unexpected error pops up, and the error won't fly by possibly messing something else up.
accepted answer of: http://stackoverflow.com/q/51034424
has comment: http://stackoverflow.com/comment/89060912
answers question: http://stackoverflow.com/q/51034424
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/110238838
type: Answer
score: 16
upvote count: 16
has comment: http://stackoverflow.com/comment/110228001

http://stackoverflow.com/q/51087601
type: Question
tagged with: python
has body: At the moment I am using the below code to listen to incoming messages in Outlook from Python. How can I do the same for Outgoing messages from my Outlook? import win32com.client import pythoncom class Handler_Class(object): senders = ['blabla@gmail.com'] def OnNewMailEx(self, receivedItemsIDs): # RecrivedItemIDs is a collection of mail IDs separated by a ",". # You know, sometimes more than 1 mail is received at the same moment. for ID in receivedItemsIDs.split(","): mail = outlook.Session.GetItemFromID(ID) subject = mail.Subject outlook = win32com.client.DispatchWithEvents("Outlook.Application",Handler_Class) # an infinite loop that waits for event pythoncom.PumpMessages()
has title: Pythoncom - How to listen to Outlook Outgoing messages?
upvote count: 1
tagged with: outlook
tagged with: pythoncom
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89164488
tagged with: outgoing-mail
downvote count: 0
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/22813814

http://stackoverflow.com/q/51104612
tagged with: image
has answer: http://stackoverflow.com/a/51105851
accepted answer: http://stackoverflow.com/a/51105851
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89197260
has title: nine point smooth in OpenCV
favorite count: 0
tagged with: python
tagged with: opencv
type: AnsweredQuestion
upvote count: 0
has body: How can i apply nine point smooth using OpenCV? Info : Nine point smooth will take a 3x3 square of 9 pixels each and determine the count of each pixel.The counts per pixel are then averaged, and that value is assigned to the central pixel. Nine Point Smooth : http://www.people.vcu.edu/~mhcrosthwait/clrs322/2DFilteringconcepts.htm
tagged with: smoothing
has comment: http://stackoverflow.com/comment/89197171
type: Question
score: -1

http://stackoverflow.com/q/51107648
downvote count: 3
type: Question
has title: How do you select all strings in between certain substrings in python and create a csv out of the results?
has answer: http://stackoverflow.com/a/51108901
has comment: http://stackoverflow.com/comment/89202341
answer count: 1
score: -1
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
has body: I'm trying to parse the results of an API call in python. {'data': [{'type': 'infra_process_running', 'name': 'Custom Plugin Alert - Stopped Running', 'enabled': True, 'filter': {'and': [{'is': {'entityName': 'SOMEHOSTNAME','SOMEHOSTNAME'}}]}, 'id': 123456, 'created_at_epoch_millis': 1513024072143, 'updated_at_epoch_millis': 1513024072176, 'policy_id': 127350, 'comparison': 'below', 'critical_threshold': {'value': 2, 'duration_minutes': 5}, 'process_filter': {'and': [{'is': {'commandLine': 'java'}}]}}], 'meta': {'limit': 50, 'offset': 0, 'total': 1}, 'links': {}} EDIT: Sorry forgot to say this is output from running print on a request in python which is why it's single quoted and not double like JSON I would like to extract all 'name' and all 'entityName' from this request. I've tried using regex to search for and store those in a list list.append(re.search(r"', 'name': '(.*?)', '", stringInfJSON)) list.append(re.search(r"{'entityName': ['(.*?)']", stringInfJSON)) I would like to extract all 'name' and all 'entityName' from this request. I would then like to insert all those to an excel spreadsheet in the following format +---------------------------------------+---------------------+ | Somehostname(s) | Somehostname2 | +---------------------------------------+---------------------+ | Custom Plugin Alert - Stopped Running | Blah Blah Blah Blah | +---------------------------------------+---------------------+
accepted answer: http://stackoverflow.com/a/51108901
upvote count: 2
tagged with: python
tagged with: python-requests
tagged with: regex
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/51088692
favorite count: 0
has body: This difference can be seen in the documentation. 1.13 docs: X : array_like 1.14 docs: X : 1D or 2D array_like Data to be saved to a text file.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51088793
score: 4
has answer: http://stackoverflow.com/a/51088828
type: Question
tagged with: numpy
downvote count: 0
upvote count: 4
answer count: 2
has title: Why doesn't numpy 1.14 support savetxt for array with dimension more than 2, while 1.13 seems to support that?

http://stackoverflow.com/q/51038719
tagged with: python
tagged with: python-3.x
tagged with: tkinter
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51038876
type: Question
type: AnsweredQuestion
has body: I'm learning Tkinter for GUI. I write the following simple code, I can't change the location of the Textbox even if I try different values in the grid. Whatever value I write, the Textbox always comes at the left up corner. from tkinter import * startingWindow = Tk() startingWindow.title("Hello") startingWindow.geometry("400x300") myEntry = Entry(startingWindow, width=10) myEntry.grid(column=15, row=15) startingWindow.mainloop() Instead, I get the following output. Note: I'm using Python 3.6 under Windows 7
has comment: http://stackoverflow.com/comment/89074304
answer count: 1
has title: How to position a Textbox with Tkinter in Python?
accepted answer: http://stackoverflow.com/a/51038876
tagged with: python-3.6
favorite count: 0
score: 0

http://stackoverflow.com/q/51138004
has answer: http://stackoverflow.com/a/51141194
accepted answer: http://stackoverflow.com/a/51141194
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has body: I recently started looking into SDK for Azure and can't figure out why every single method (tested by me) returns an object rather then something more 'human' friendly i.e. list or dictionary. i.e.: list(compute_client.virtual_machines.list_all()) [&lt;azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c190&gt;, &lt;azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c750&gt;, &lt;azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93cad0&gt;, &lt;azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93ced0&gt;] What is a benefit of returning objects which seem to be awkward to interact with i.e. I need to lookup every single method to find the return values and so on to process a list and then to build a dictionary it seems as more work then needed. I have found this method in one of the Microsoft blogs / githubs: def print_item(group): """Print a ResourceGroup instance.""" print("\tName: {}".format(group.name)) print("\tId: {}".format(group.id)) print("\tLocation: {}".format(group.location)) print("\tTags: {}".format(group.tags)) print_properties(group.properties) This seems so inefficient IMO to be able to print a return value of another method. Can some one advise why an "object list" is better then a "list" why not to return something like json.
downvote count: 0
tagged with: azure
has title: Why azure-sdk-for-python returns objects
answer count: 1

http://stackoverflow.com/comment/89184485
comment on: http://stackoverflow.com/a/51094581
type: Comment
type: AnswerComment
score: 0
has text: I have tried with your code even the testcase failed for the problem statement

gurobi
tags question: http://stackoverflow.com/q/51012131
tag name: gurobi
type: Tag

http://stackoverflow.com/q/51041700
has answer: http://stackoverflow.com/a/51041801
tagged with: python
has comment: http://stackoverflow.com/comment/89074509
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51041972
has comment: http://stackoverflow.com/comment/89074484
has answer: http://stackoverflow.com/a/51042080
upvote count: 1
downvote count: 1
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/51042030
has answer: http://stackoverflow.com/a/51041921
has answer: http://stackoverflow.com/a/51042173
score: 0
has answer: http://stackoverflow.com/a/51042027
has body: I am a beginner programmer and am self learning python programming at home from a book. I am currently learning about strings. There is a question there which i solved it but I was thinking if there are other easier ways to solve it. Q. A certain professor gives 100-point exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, 60-69:D, &lt;60:F. Write a program that accepts an exam score as input and prints out the corresponding grade. def main(): ## making a list from 0-100 num = list(range(0,101)) ## asking for the exam points points = int(input("Enter the exam points 0-100: ")) ## iterating num 0-60 for i in num[0:60]: if i == points: print("Your corresponding grade is F.") ## iterating num 60-70 for i in num[60:70]: if i == points: print("Your corresponding grade is D.") ## iterating num 70-80 for i in num[70:80]: if i == points: print("Your corresponding grade is C.") ## iterating num 80-90 for i in num[80:90]: if i == points: print("Your corresponding grade is B.") ## iterating num 90-100 for i in num[90:101]: if i == points: print("Your corresponding grade is A.") main()
has answer: http://stackoverflow.com/a/51041825
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51041801
has title: beginner programmer here..easier ways to program this?
accepted answer: http://stackoverflow.com/a/51041921

http://stackoverflow.com/q/51132991
score: 0
tagged with: python
tagged with: lambda
answer count: 1
has body: In my Convolution Network, I recently add a Lambda Layer as the input layer for select specific channels of the input images following the answer from this question model.add(Lambda(lambda x: x[:,:,:2], input_shape=(w, h, 3))) When I tried to add the MaxPooling2D Layer, I got the error ValueError: Negative dimension size caused by subtracting 3 from 2 for 'max_pooling2d_14/MaxPool' (op: 'MaxPool') with input shapes: [?,250,2,64] I thought I make some mistakes between Theano and Tensorflow dim order so I edited the Lambda Layer: model.add(Lambda(lambda x: x[:2,:,:], input_shape=(w, h, 3))) This time I got no problem when adding more layer, but when I tried to use fit_generator, it gets the error: InvalidArgumentError: Incompatible shapes: [64] vs. [2] The full trace back is very long, I upload them to here. I'm using on Linux with 4 GPU for calculation, thanks for your help.
has answer: http://stackoverflow.com/a/51147576
linked to: http://stackoverflow.com/q/50434183
tagged with: tensorflow
has title: Tensorflow InvalidArgumentError: Incompatible shapes after slicing input by Lambda Layer
tagged with: keras
accepted answer: http://stackoverflow.com/a/51147576
type: Question
tagged with: gpu
type: AnsweredQuestion

http://stackoverflow.com/comment/120730553
comment on: http://stackoverflow.com/q/51062015
type: QuestionComment
score: 1
has text: This is a tricky problem. I ASSUME you are not literally looking for "Motor101", but that you actually have a set of keywords. If I were doing this, I think I'd search for the keyword ("motor"), then search for the item numbers, and if I found a keyword within a certain number of characters of an item number, then that was probably a match.
type: Comment

http://stackoverflow.com/comment/89264814
comment on: http://stackoverflow.com/a/51140337
score: 0
type: AnswerComment
has text: That much isn't the problem, but how do I go from that list to to adding back the associated paths?
type: Comment

http://stackoverflow.com/comment/95096535
type: Comment
has text: and how would you do if the name `A_attack` is in a variable?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51152186

http://stackoverflow.com/q/51161348
has answer: http://stackoverflow.com/a/51164051
accepted answer: http://stackoverflow.com/a/51164051
has answer: http://stackoverflow.com/a/51200624
downvote count: 1
has body: I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
has answer: http://stackoverflow.com/a/64267411
has title: Quadratic Programming in Python using Numpy?
favorite count: 0
tagged with: quadratic-programming
tagged with: python
linked to: http://stackoverflow.com/q/17009774
has answer: http://stackoverflow.com/a/74421937
answer count: 4
tagged with: matlab
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/89306266
possible better answer: http://stackoverflow.com/a/64267411
upvote count: 8
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/121939250
has comment: http://stackoverflow.com/comment/89306208
has comment: http://stackoverflow.com/comment/89306306
tagged with: optimization

http://stackoverflow.com/a/51050165
upvote count: 9
has comment: http://stackoverflow.com/comment/89091373
answers question: http://stackoverflow.com/q/51050146
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51050146
score: 9
has body: '{value:.2f}'.format(value=pi)

http://stackoverflow.com/comment/89164282
type: Comment
comment on: http://stackoverflow.com/a/51086176
score: 0
type: AnswerComment
has text: So I got it to work using something similar to this: Popen([cmd, "-T", "testing title", output], stdin=PIPE, stdout=PIPE, stderr=PIPE), but I had to create a new variable called cmd = [example] before that, if not it wouldn't work... and now the cmd window shows up when my script runs vs. before it would do it behind the scene, any way to resolve that? does that have to do with the shell=true parameter?!

http://stackoverflow.com/comment/89211252
type: QuestionComment
has text: when trying to run with the script via `python3.6 pymysql.py` now i get the error `ModuleNotFoundError: No module named 'pymysql.cursors'; 'pymysql' is not a package`... lol
score: 0
comment on: http://stackoverflow.com/q/51111464
type: Comment

http://stackoverflow.com/comment/89167096
type: Comment
has text: please post Traceback of error
comment on: http://stackoverflow.com/q/51089206
score: 1
type: QuestionComment

http://stackoverflow.com/comment/89202854
type: Comment
type: QuestionComment
has text: for heaven's sake, include some of your code and the source HTML of what you're trying to scrape...
comment on: http://stackoverflow.com/q/51106207
score: 0

http://stackoverflow.com/q/51075588
type: UnansweredQuestion
has body: I'm trying to recreate Plotly's county choropleth example in offline mode. The example works fine when passing my credentials to the plot online: import plotly import plotly.figure_factory as ff fips = ['06021', '06023', '06027', '06029', '06033', '06059', '06047', '06049', '06051', '06055', '06061'] values = range(len(fips)) plotly.tools.set_credentials_file(username='MaxGhenis', api_key=KEY) fig = ff.create_choropleth(fips=fips, values=values) plotly.plotly.iplot(fig, filename='online choropleth') But when it's offline it doesn't show up: plotly.offline.init_notebook_mode(connected=True) fig = ff.create_choropleth(fips=fips, values=values) plotly.offline.iplot(fig, filename='offline choropleth') I'm using Google's Colaboratory cloud Jupyter service (here's the notebook). Any ideas how to fix this? Update: Filed https://github.com/plotly/plotly.py/issues/1045.
has title: Plotly choropleth works in online but not offline mode
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/47230817
type: Question
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/47230817
tagged with: plotly
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/89133524
type: AnswerComment
comment on: http://stackoverflow.com/a/51051538
type: Comment
has text: Did you try `pip install PyMuPDF` instead of `pip install fitz`?
score: 0

http://stackoverflow.com/q/51150232
has comment: http://stackoverflow.com/comment/89284287
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89284590
accepted answer: http://stackoverflow.com/a/51150852
has comment: http://stackoverflow.com/comment/89284523
tagged with: numpy
has body: Let's say that I have an array something like: foo = np.random.rand(2, 5) and I've been given a slice like [:, [2, 4]]. What I'd like to do is to efficiently be able to delete the slice out of the array, so basically leaving me with: foo[:, [0, 1, 3]] Here foo could be an arbitrary rank tensor with the slice in each dimension being either a : or a list of non-repeating positive indices. Is there an efficient way of implementing this without using np.delete and a complicated (slow) loop?
has title: Negating a slice in Numpy?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89284639
has comment: http://stackoverflow.com/comment/89284768
favorite count: 0
has comment: http://stackoverflow.com/comment/89285091
tagged with: python
has answer: http://stackoverflow.com/a/51150852
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89284750

http://stackoverflow.com/a/51124428
answers question: http://stackoverflow.com/q/51124019
upvote count: 3
has body: one way could be to use \S* matching all non withespaces after A/P_ and also add \s to remove the whitespace after the string to remove, such as: df_sess['COL'] = df_sess['col'].str.replace(r'A/P_\S*\s', '') In you input, it seems there is an typo error (or at least I think so), so with this input: df_sess = pd.DataFrame({'col':['hi A/P_90890 how A/P_True A/P_/93290 are A/P_wueiwo A/P_|iwoeu you A/P_?9028k ?', 'Im fine, what A/P_49 A/P_0.0309 about you?']}) print (df_sess['col'].str.replace(r'A/P_\S*\s', '')) 0 hi how are you ? 1 Im fine, what about you? Name: col, dtype: object you get the expected output
accepted answer of: http://stackoverflow.com/q/51124019
score: 3
has comment: http://stackoverflow.com/comment/89234303
has comment: http://stackoverflow.com/comment/89234185
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89022260
score: 0
has text: @phd any suggestions?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51014497

http://stackoverflow.com/comment/89188855
comment on: http://stackoverflow.com/a/51089161
type: Comment
type: AnswerComment
has text: Welcome to Stack Exchange Kiera. Don't neglect to accept the answer if it answered your question. That's how respondents are rewarded for taking the time to answer your question :)
score: 0

http://stackoverflow.com/q/51045894
tagged with: numpy
has comment: http://stackoverflow.com/comment/89083065
has comment: http://stackoverflow.com/comment/89083509
answer count: 1
downvote count: 0
has title: Clean way to create column based on multiple conditions
accepted answer: http://stackoverflow.com/a/51046331
has comment: http://stackoverflow.com/comment/89083127
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51046331
has body: My question is simple - I have the following table: +----------+-------+------------+--------+ | industry | class | occupation | value | +----------+-------+------------+--------+ | 170 | 4 | 1000 | 123.3 | | 180 | 7 | 3600 | 4543.8 | | 570 | 5 | 990 | 657.4 | +----------+-------+------------+--------+ I'd like to create a new column called "type". The value of this column is based on these multiple conditions Class = 7 : QWE Class = 8 : ASD Class = 1 or 2 : ZXC Class = 4, 5, or 6 AND Industry = 170-490 or 570-690 AND Occupation >=1000 : IOP Class = 4, 5, or 6 AND Industry = 170-490 or 570-690 AND Occupation between 10-3540 : JKL Anything else : BNM The resulting table will look like this: +----------+-------+------------+--------+------+ | industry | class | occupation | value | type | +----------+-------+------------+--------+------+ | 170 | 4 | 1000 | 123.3 | IOP | | 180 | 7 | 3600 | 4543.8 | QWE | | 570 | 5 | 990 | 657.4 | JKL | +----------+-------+------------+--------+------+ My first approach to this was basically creating multiple dataframes of each type using the dataframe query method. However, I found out about the numpy "where" method and I am currently using a nested version of that to create the "type" column in one step. However, I feel like it's un-readable and I can imagine a situation where there are even more conditions that would make this process look really messy. Is there a cleaner way of doing this? Maybe with a dictionary or something?
has comment: http://stackoverflow.com/comment/89083525
upvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17071871
score: 1
tagged with: dataframe
type: Question

http://stackoverflow.com/comment/89299467
type: Comment
has text: @Tim no i mean visual studio include directory
comment on: http://stackoverflow.com/q/51157679
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89164070
type: QuestionComment
comment on: http://stackoverflow.com/q/51087484
score: 1
has text: It'd be super useful to share what you have written to get as far as you have.
type: Comment

http://stackoverflow.com/a/51110564
accepted answer of: http://stackoverflow.com/q/51109245
has body: Here's a solution using groupby + set. This should be extendable and does not require ordering: s = df.groupby('make')['sale'].apply(set) res = df[df['make'].map(s) &gt;= {0, 1}] print(res) make country other_columns sale 0 honda tokyo data 1 1 honda hirosima data 0 2 toyota tokyo data 1 3 toyota hirosima data 0 6 ferrari tokyo data 1 7 ferrari hirosima data 0 8 nissan tokyo data 1 9 nissan hirosima data 0
upvote count: 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51109245
score: 2
downvote count: 0

http://stackoverflow.com/a/51033045
type: AcceptedAnswer
has body: Use get_level_values() &gt;&gt;&gt; mask = (df.index.get_level_values(0)=='b') | (df.index.get_level_values(1)=='b') &gt;&gt;&gt; df[mask] # same as df.loc[mask] x y i0 i1 a b 2 5 b a 4 3 b 5 2 c 6 1
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/51032985
accepted answer of: http://stackoverflow.com/q/51032985
score: 7
downvote count: 1

http://stackoverflow.com/a/51160472
has comment: http://stackoverflow.com/comment/89304546
has comment: http://stackoverflow.com/comment/89304717
type: Answer
has comment: http://stackoverflow.com/comment/89304320
has comment: http://stackoverflow.com/comment/89304948
has comment: http://stackoverflow.com/comment/89304878
answers question: http://stackoverflow.com/q/51160368
has body: Actually my old answer was wrong. In the python shell you can do: &gt;&gt;&gt; import time &gt;&gt;&gt;time.localtime() here it will show a result &gt;&gt;&gt; _.tm_isdst This question is actually a duplicate but the old post can be found here: Python daylight savings time
has comment: http://stackoverflow.com/comment/89304600
has comment: http://stackoverflow.com/comment/89304813
score: 0

drf-queryset
type: Tag
tag name: drf-queryset
tags question: http://stackoverflow.com/q/51062823

http://stackoverflow.com/a/51146119
has comment: http://stackoverflow.com/comment/89276517
has comment: http://stackoverflow.com/comment/89276876
has body: Use re.findall to tokenize the parts. import re string_list = [' \n \n \n ', ' '] for string in string_list: output = '' for pre, attrs, post in re.findall(r'([^<]*</?\w+)\b(.*?)(/?>[^<]*)', string, re.DOTALL): output += pre + ''.join([attr[0] for attr in re.findall(r'(\s+\w+=(?:([\'"]).*?\2|\S+))|\S+', attrs)]) + post print(output) This outputs:
has comment: http://stackoverflow.com/comment/89294528
score: 0
upvote count: 1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89277601
has comment: http://stackoverflow.com/comment/89276635
has comment: http://stackoverflow.com/comment/89286325
has comment: http://stackoverflow.com/comment/89276644
has comment: http://stackoverflow.com/comment/89277705
answers question: http://stackoverflow.com/q/51145994
has comment: http://stackoverflow.com/comment/89276491

http://stackoverflow.com/q/51036832
has comment: http://stackoverflow.com/comment/89068614
type: Question
tagged with: cron
has body: I followed this link to schedule a cron job: https://github.com/kraiz/django-crontab However, it is not working. Here are snippets of my code. settings.py: CRONJOBS = [ ('2 * * * *', 'LeaveManagement.cron.team_notification' , ' &gt;&gt; /home/nineleaps/Nineleaps/LeaveTracking/cronLog.log')] cron.py: def team_notification(): send_mail("Test", "Hey", 'settings.EMAIL_HOST_USER', ['mahima@nineleaps.com'],fail_silently=False) Running crontab -l command gives this: 2 * * * * /home/nineleaps/Nineleaps/LeaveTracking/venv/bin/python /home/nineleaps/Nineleaps/LeaveTracking/manage.py crontab run 5f84ef47012b65076a7f598581193a10 >> /home/nineleaps/Nineleaps/LeaveTracking/cronLog.log 2>&amp;1 # django-cronjobs for LeaveTracking
answer count: 0
has title: Not able to run cron jobs with django
score: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89066554

http://stackoverflow.com/comment/89250264
score: 1
has text: I recommend you to hide the API key from the code.
comment on: http://stackoverflow.com/q/51132802
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89058006
has text: @Solaiman Please make sure that: 1) `parsed` is 2D dictionary so this is valid string `parsed['links']['next']` and this is a list `parsed['products']` 2) `product` is a 2D dictionary so these are valid: `product['id']`, ..., `product['nl']['title']`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51032809
type: Comment

http://stackoverflow.com/q/51118407
has answer: http://stackoverflow.com/a/51118455
has title: Memory error when running k_cliques_community
has answer: http://stackoverflow.com/a/67491468
answer count: 3
score: 1
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90426780
has answer: http://stackoverflow.com/a/51126060
tagged with: python
tagged with: networkx
type: AnsweredQuestion
tagged with: anaconda
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51118455
accepted answer: http://stackoverflow.com/a/51126060
has body: I run k_cliques_community on my network data and received a memory error after a long respond time. The code works perfectly fine for my other data but not this one. c = list(k_clique_communities(G_fb, 3)) list(c[0]) Here is a snap shot of the trace error

http://stackoverflow.com/q/51093906
has title: Find the F-statistic value for ANOVA first linear model
tagged with: statistics
type: Question
has body: I am going through stats with python topics. I am struck with one hands on. Problem statement: Perform ANOVA on the first linear model obtained while working with mtcars data set. Display the F-statistic value. What i did for the problem statement: import statsmodels.api as sm import statsmodels.formula.api as smf from statsmodels.stats import anova mtcars_data = sm.datasets.get_rdataset("mtcars").data print(mtcars_data.columns) mt_model1 = smf.ols('mpg ~ cyl', mtcars_data ).fit() print(anova.anova_lm(mt_model1)) How can I display the F-statistic for the above problem?
has answer: http://stackoverflow.com/a/64821705
has answer: http://stackoverflow.com/a/64822487
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51094581
answer count: 5
has answer: http://stackoverflow.com/a/51095966
tagged with: python
has comment: http://stackoverflow.com/comment/89178821
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53856639
tagged with: machine-learning
tagged with: statsmodels

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

http://stackoverflow.com/comment/89212728
type: Comment
score: 0
has text: Have you tried executing these two statements with two separate `execute` calls?
comment on: http://stackoverflow.com/q/51112813
type: QuestionComment

http://stackoverflow.com/q/51133962
has answer: http://stackoverflow.com/a/51134741
favorite count: 0
has answer: http://stackoverflow.com/a/51161469
tagged with: python
upvote count: 2
type: UnansweredQuestion
tagged with: computer-vision
type: Question
tagged with: opencv
has body: I created one task, where I have white background and black digits. I need to take the largest by thickness digit. I have made my picture bw, recognized all symbols, but I don't understand, how to scale thickness. I have tried arcLength(contours), but it gave me the largest by size. I have tried morphological operations, but as I undestood, it helps to remove noises and another mistakes in picture, right? And I had a thought to check the distance between neighbour points of contours, but then I thought that it would be hard because of not exact and clear form of symbols(I draw tnem on paint). So, that's all Ideas, that I had. Can you help me in this question by telling names of themes in Comp. vision and OpenCV, that could help me to solve this task? I don't need exact algorithm of solution, only themes. And if that's not OpenCV task, so which is? What library? Should I learn some pack of themes and basics before the solution of my task?
has comment: http://stackoverflow.com/comment/89309642
tagged with: image
has title: How can i scale a thickness of a character in image using python OpenCV?
answer count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/89153643
has text: You may only use a number once. If a number appears many times, you may use like you described to form 5.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51080191
type: Comment

http://stackoverflow.com/comment/103992552
score: 0
type: Comment
type: QuestionComment
has text: To check for Tensorflow, Keras and PyTorch, see https://stackoverflow.com/a/53244520/420400
comment on: http://stackoverflow.com/q/51114771

http://stackoverflow.com/a/51035208
downvote count: 0
has comment: http://stackoverflow.com/comment/89089503
type: Answer
has body: The Http 500 exception (Internal Server Error) raises because you may be defined DEBUG = False in your settings.py. You could see the original exception and traceback if you set it to DEBUG = True in settings.py file Your serializer seems fine, but views don't. So change your views as below def list(self, request, city=None): queryset= address.objects.all() if city is not None: queryset = queryset.filter(city__icontains=city) serializer = ResultSerializer(queryset, many=True) return Response(serializer.data)
answers question: http://stackoverflow.com/q/51033887
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89088491

http://stackoverflow.com/q/51070904
answer count: 2
tagged with: data-visualization
tagged with: python
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51072527
score: 2
has body: I am trying to plot a 3D plot in Matplotlib from a Pointcloud data which is essentially extracted from two different classes. However, I cannot differentiate the classes into different colors. My code is below. x=pd.DataFrame(np.array(x).reshape(-1,1)) y=pd.DataFrame( np.array(y).reshape( -1, 1 ) ) z=pd.DataFrame(np.array(z).reshape(-1,1)) target=pd.DataFrame(np.array(target).reshape(-1,1)) new_data=[x,y,z,target] new_data = pd.concat(new_data, axis=1, ignore_index=True ) new_data.columns = ['x','y','z','target'] colors=[] fig=plt.figure(figsize=(8,8)) ax=fig.add_subplot(111,projection='3d') ax.scatter(new_data.x,new_data.y,new_data.z,color='target') The color argument cannot be linked to the class in the "Target" column in my dataframe. Is there something that I am missing?
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51071502
has title: Matplotlib 3D plot colors from different classes from Dataframe
favorite count: 0
possible better answer: http://stackoverflow.com/a/51071502
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51072527

http://stackoverflow.com/q/51110020
downvote count: 1
score: 3
type: Question
upvote count: 4
answer count: 1
tagged with: django-staticfiles
favorite count: 0
has title: django ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' runserver
tagged with: angular
has answer: http://stackoverflow.com/a/53876443
tagged with: python
has body: when I run python manage.py runserver and I try to visit my site on my local I get the following error: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 432, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' my settings file in full: """ Django settings for suitsandtables project. Generated by 'django-admin startproject' using Django 1.11.10. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from decouple import config, Csv import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=True, cast=bool) DEBUG_PROPAGATE_EXCEPTIONS = config('DEBUG_PROPAGATE_EXCEPTIONS', default=True, cast=bool) BLOCKEMAIL = config('BLOCKEMAIL', default=True, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # send grid email code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool) EMAIL_HOST = config('EMAIL_HOST') EMAIL_PORT = config('EMAIL_PORT') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Amazon S3 code AWS_UPLOAD_BUCKET = config('AWS_UPLOAD_BUCKET') AWS_UPLOAD_USERNAME = config('AWS_UPLOAD_USERNAME') AWS_UPLOAD_GROUP = config…
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/51148234
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51147715
type: Answer
has body: Just a code example. You can call to your own function using apply and lambda functions. You can access any column in your df using the parameter "axis=1". You con store the result of any transformation in a new column returning the desired value in the function and storing it in a new column. def your_function(row): if row[your_column]: return row[your_column].split() else: return None df['new_column'] = pandas.apply(lambda row: your_function(row),axis=1)
downvote count: 0

http://stackoverflow.com/q/51146279
has body: When I try to start a new thread, my entire program stops until the thread's function finishes. I am trying to make the thread start and continue while my program runs at the same time. Code: def do_python(string): while True: exec(string, globals()) time.sleep(0.1) getKeyThread = threading.Thread(target=do_python("key = cpc.get_key()"), daemon=True).start() time.sleep(0.2) while True: if key == 9: print("Tab pressed.") exit() I have imported all of the required modules, so that is not the problem. Any functions used in here that aren't defined have been defined elsewhere and work perfectly fine. I haven't included my entire program here, because it is far too big to paste here.
tagged with: python
accepted answer: http://stackoverflow.com/a/51146346
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89276721
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89276698
has answer: http://stackoverflow.com/a/51146346
answer count: 1
has title: Python: I start a new thread, and my program pauses until the thread is finished
tagged with: python-multithreading

http://stackoverflow.com/a/65063266
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Note: this answer is for pandas version 1.0.5 . Things might be different for other versions. tl;dr pandas describe() method will always be slower than your version, because under the hood it's using almost the exact same logic, plus some other things like making sure the data has the right dimensions, ordering the results, and checking for NaNs and the correct data types. Longer Answer Taking a look at the source code of the describe method, we can see a few things: pandas uses the same logic as your code to compute the statistics. See this line inside the describe() method for an example of how it's using the same logic. This means that pandas describe will always be slower. pandas counts non-NaN values using s.count(), but your code counts all values. Let's try and modify your code to use that same method instead of len(): def summarize_numeric_3(df, filt, groups, values, quantiles): dfg = df[mask].groupby(groups)[values] dfg_stats = dfg.agg([np.mean, np.std, pd.Series.count]).stack() dfg_quantiles = dfg.quantile(all_quantiles) return dfg_stats.append(dfg_quantiles).sort_index() %timeit -n 10 summarize_numeric_3(df, mask, groups, values, all_quantiles) # outputs # 48.9 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) it takes ~49 ms, vs 42 ms for your version on my machine. It took 7 more ms just for this relatively small modification! pandas does a lot more than your code to ensure the data has the correct type and shape, and to present it in a pretty format. I've extracted the pandas describe method code into a "self-contained"* version that you can profile and tinker with here (too long to be posted in this answer). Profiling that, I see that a very large portion of the time is taken to "set a convenient order for rows". Removing that ordering improved the describe timing by ~8%, from 530 ms down to 489 ms.
answers question: http://stackoverflow.com/q/51014376

http://stackoverflow.com/q/51016482
type: AnsweredQuestion
has body: I am not sure if the title of this question is appropriate, so anyone is welcome to edit it. Thank you! My question is that if I have a string of a protein sequence: seq='MIGQFGL' How can I convert it to something like this: MET 1 ILE 2 GLY 3 GLN 4 PHE 5 GLY 6 LEU 7 This is what I have tried: f= open("protein.seq", "w") seq = 'MIGQFGL' d = {'C': 'CYS', 'D': 'ASP', 'S': 'SER', 'Q': 'GLN', 'K': 'LYS', 'I': 'ILE', 'P': 'PRO', 'T': 'THR', 'F': 'PHE', 'N': 'ASN', 'G': 'GLY', 'H': 'HIS', 'L': 'LEU', 'R': 'ARG', 'W': 'TRP', 'A': 'ALA', 'V':'VAL', 'E': 'GLU', 'Y': 'TYR', 'M': 'MET'} sp = list(seq) rep = '\n'.join(d.get(e,e) for e in sp) #to replace the items in list 'sp' with corresponding dictionary values no = list(range(1,8)) n = '\n'.join(str(x) for x in no) line = "{}\t{}\n".format(rep,n) f.write(line) But this is what I got: MET ILE GLY GLN PHE GLY LEU 1 2 3 4 5 6 7 So, I changed this line: line = "{}\t{}\n".format(rep,n) to: line = "{}\t{}\n".format(zip(rep,n)) But I got: Traceback (most recent call last): File "protein.py", line 15, in &lt;module&gt; line = "{}\t{}\n".format(zip(rep,n)) IndexError: tuple index out of range What am I doing wrong? Thanks in advance! NB: I use Python 3.
score: 1
has comment: http://stackoverflow.com/comment/89025469
type: Question
has comment: http://stackoverflow.com/comment/89025521
tagged with: string
has answer: http://stackoverflow.com/a/51016519
has answer: http://stackoverflow.com/a/51016524
favorite count: 0
has answer: http://stackoverflow.com/a/51016533
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51016503
has title: How to separate a string into multiple lines of individual characters
upvote count: 2
accepted answer: http://stackoverflow.com/a/51016533
downvote count: 1
possible better answer: http://stackoverflow.com/a/51016503

http://stackoverflow.com/a/51056624
type: Answer
has body: A bit of google can help here that article has all you need as far as opening and writing to files. To set you on the right path: You can just call f=open("fileName.txt","w+") which will open up your existing file for you and store it into a variable. Then you can file_line=f.readlines() to grab one line at a time. Manipulate the result as you need. Recreate a new string variable with the result of your manipulation result= "My data" and then use f2=open("newFileName.txt","w+") with a new file name to create a new file on which you will use f2.write(result) in order to write to the file. Make sure to close our your files f.close(),f2.close() The data manipulation portion is up to you!
answers question: http://stackoverflow.com/q/51056172
score: 0

http://stackoverflow.com/a/51012151
has body: Put the with open('results.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(['company', 'followers', 'result']) outside (above) the loop, and call writer.writerow inside the loop. The loop must be inside the with block.
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51012134

snap-python
tags question: http://stackoverflow.com/q/51046217
tag name: snap-python
type: Tag

http://stackoverflow.com/comment/89021191
type: Comment
score: 0
has text: That's ok, but how to add a formula field in a form, can you help me completely, please
comment on: http://stackoverflow.com/a/51014211
type: AnswerComment

http://stackoverflow.com/comment/89149358
has text: Are you using this operation iterating though a number of points?
score: 0
comment on: http://stackoverflow.com/q/51077418
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89246934
has text: python doc says that object.__call__ is : "Called when the instance is “called” as a function". However objectclasses are not instances of class type, are they ?
comment on: http://stackoverflow.com/a/51124294
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/89135864
type: Comment
has text: Thanks All, unfortunately I can’t use pip to install new packages (shared hosting). @dfundako thanks for this tip, basic stuff to add to the knowledge bank, much appreciated.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51046480

http://stackoverflow.com/comment/89216007
score: 0
comment on: http://stackoverflow.com/a/51114867
type: AnswerComment
type: Comment
has text: Interesting, how do I correct for that in python? (I need to do this in both directions -- from UUID to converted value, from converted value back to UUID)

http://stackoverflow.com/q/51072814
accepted answer: http://stackoverflow.com/a/51178450
linked to: http://stackoverflow.com/q/25023233
type: AnsweredQuestion
downvote count: 2
has title: how should I print my output result in python2.7
type: Question
has body: I am storing some data like temperature,humidity and Intensiy in array which is my arduino output and input for my python2.7 and I am plotting graphs from that data. I want to store the arduino output into text file also but i am unable to do it as i am new to python. This is my python code import serial import numpy as np import matplotlib.pyplot as plt from drawnow import * l=[] t = [] h = [] arduinoData = serial.Serial('com3',115200) plt.ion() count=0 def makeFig(): ax1 = plt.subplot(211) plt.ylim(0,100) plt.title('Temperature and Humidity') plt.grid(True) plt.ylabel('temp in C') plt.plot(t, 'ro-', label='Drgrees Celsius') plt.legend(loc='upper left') plt2=plt.twinx() plt.ylim(0,100) plt2.plot(h,'b^-',label='Humidity in %') plt2.legend(loc='upper right') ax2 = plt.subplot(212, sharex=ax1) plt.ylim(0,100) plt.grid(True) plt.ylabel('Intensity in Lux') plt.plot(l, 'ro-', label='Lux') plt.legend(loc='upper left') while True: while (arduinoData.inWaiting()==0): pass arduinoString = arduinoData.readline() dataArray = arduinoString.split(',') lux = float (dataArray[0] ) humd = float ( dataArray[1]) temp = float ( dataArray[2]) t.append(temp) h.append(humd) l.append(lux) drawnow(makeFig) plt.pause(.000001) count=count+1 if(count&gt;60): t.pop(0) h.pop(0) l.pop(0) I want to store t , h , l in text file as an output Help will be appreciated....
score: -2
possible better answer: http://stackoverflow.com/a/51072913
has answer: http://stackoverflow.com/a/51072913
has answer: http://stackoverflow.com/a/51178450
answer count: 2
has comment: http://stackoverflow.com/comment/89135278
upvote count: 0
has comment: http://stackoverflow.com/comment/89135299
favorite count: 0
has comment: http://stackoverflow.com/comment/89135248
tagged with: python

http://stackoverflow.com/a/55327882
has body: I had that same coremltools==0.8 error running pip install turicreate on Mac 10.11 (El Capitan). I was able to solve it fool myself into thinking I'd solved it by compiling and installing coremltools from source. See https://stackoverflow.com/a/55327526/1014857 for those steps. But turicreate didn't actually work at that point. Running import turicreate in python gave an error (from turicreate's cypython files) about linking to a library built for 10.12. I even tried building turicreate from source, but there was a dense thicket of dependencies. Eventually I came to my senses and just upgraded to Mac OSX >= 10.12, which was a much easier route.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51113821
answers question: http://stackoverflow.com/q/51113821

http://stackoverflow.com/q/51162754
has answer: http://stackoverflow.com/a/51162856
has comment: http://stackoverflow.com/comment/89308830
favorite count: 0
has comment: http://stackoverflow.com/comment/89308802
has comment: http://stackoverflow.com/comment/89308880
answer count: 1
has body: What is the naming convention for the names of a choice field. class Student(models.Model): ACTIVE= 'active' INACTIVE= 'inactive' NOT_AVAILABLE= 'not-available' STATUS_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (NOT_AVAILABLE, 'Not available'), ) status = models.CharField( max_length=15, choices=STATUS_CHOICES , default=INACTIVE, ) What naming convention should I choose for the NOT_AVAILABLE field? not-available or not_available
score: 1
accepted answer: http://stackoverflow.com/a/51162856
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89308972
tagged with: naming-conventions
type: Question
has title: Django model choice field naming convention
downvote count: 0

http://stackoverflow.com/q/51081841
tagged with: set
possible better answer: http://stackoverflow.com/a/51081897
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51081894
has comment: http://stackoverflow.com/comment/89152318
has answer: http://stackoverflow.com/a/51082069
has title: Efficient Way of making a set of tuple in which the order of tuple doesn't matters
score: 15
tagged with: tuples
has answer: http://stackoverflow.com/a/51081897
favorite count: 0
has comment: http://stackoverflow.com/comment/89152214
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51121714
tagged with: python
upvote count: 16
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51081894
tagged with: list
has body: I want to make a set of tuples in which the order of tuples shouldn't matter. For eg.- If the tuples I want to add is : [(1,2),(1,3),(2,1)] It should output like this: {(1,2),(1,3)} Is there any efficient way of doing this in python?

http://stackoverflow.com/q/51039268
has comment: http://stackoverflow.com/comment/89069980
has title: python 3 descriptor 'to_bytes' requires a 'int' object but received a 'list'
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89070056
tagged with: byte
has comment: http://stackoverflow.com/comment/89070178
type: UnansweredQuestion
tagged with: python
has body: I am trying to do a request with pyrogram libary but in the data field I get an error TypeError: descriptor 'to_bytes' requires a 'int' object but received a 'list' Code : app.send( functions.messages.GetBotCallbackAnswer( peer=app.resolve_peer("Tgr_review_bot"), msg_id=msgid, // Not important its working data=b"seller_start_page" ## Thats breaks. I tried with b and without b. ), retries=0, timeout=10) TraceBack Traceback (most recent call last): File "C:\Users\maorb\OneDrive\Desktop\Maor\python\tele\reviews\reviewbot.py", line 50, in &lt;module&gt; timeout=10 File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\client\client.py", line 869, in send r = self.session.send(data, retries, timeout) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\session\session.py", line 413, in send return self._send(data, timeout=timeout) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\session\session.py", line 379, in _send message = self.msg_factory(data) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\session\internals\msg_factory.py", line 37, in __call__ len(body) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\api\core\object.py", line 47, in __len__ return len(self.write()) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\api\functions\messages\get_bot_callback_answer.py", line 72, in write b.write(Int(self.msg_id)) File "C:\Program Files (x86)\Python36-32\lib\site-packages\pyrogram\api\core\primitives\int.py", line 32, in __new__ return int.to_bytes(value, cls.SIZE, "little", signed=signed) TypeError: descriptor 'to_bytes' requires a 'int' object but received a 'list'
answer count: 0
type: Question
tagged with: pyrogram
score: 0

http://stackoverflow.com/a/51153222
has body: Another way to do it is: desired_cols = ['c1', 'c2', 'c3'] df_final = df_final.reindex(columns = desired_cols)
answers question: http://stackoverflow.com/q/51152657
score: 0
type: Answer

http://stackoverflow.com/comment/89284475
has text: With sorted lists you should be able to do this much, much faster. The question is whether sorting the lists is going to cost you more time than it saves in the faster comparison.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51149735
score: 0

http://stackoverflow.com/a/51150300
has body: As you're using == the script is checking for the string in the cell to match exactly that. Instead use in. Your code should be: import openpyxl bid = openpyxl.load_workbook('C:/Users/User/Desktop/bidding.xlsx', data_only=True) for sheet in bid.worksheets: for row in sheet.iter_rows(): for entry in row: try: if 'Company_A' in entry.value: print(entry.offset(row=1).value) print(round(entry.offset(row=8).value/100,5)) except (AttributeError, TypeError): continue
has comment: http://stackoverflow.com/comment/89315454
has comment: http://stackoverflow.com/comment/89322007
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51147054
answers question: http://stackoverflow.com/q/51147054

http://stackoverflow.com/comment/122614935
score: 1
type: AnswerComment
type: Comment
has text: Just a small detail, the last parameter in fillPoly must be (255,255,255) to fill the polygon with white color, instead it will represent only Blue channel.
comment on: http://stackoverflow.com/a/51122043

http://stackoverflow.com/a/51127881
type: Answer
answers question: http://stackoverflow.com/q/51127872
has body: You could use zip(): &gt;&gt;&gt; a = [23, 43, 32, 27, 11] &gt;&gt;&gt; b = [3, 5, 4, 3, 2] &gt;&gt;&gt; c = [x**y for x, y in zip(a, b)] &gt;&gt;&gt; c [12167, 147008443, 1048576, 19683, 121] or map() and operator.pow(): &gt;&gt;&gt; from operator import pow &gt;&gt;&gt; d = list(map(pow, a, b)) &gt;&gt;&gt; d [12167, 147008443, 1048576, 19683, 121]
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51127872
score: 7
has comment: http://stackoverflow.com/comment/89240659
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89240665

http://stackoverflow.com/comment/89323843
comment on: http://stackoverflow.com/a/51161549
score: 0
type: AnswerComment
type: Comment
has text: Thanks! I used this code to make the colorbar horizontal: `cbar = plt.colorbar(sm, orientation='horizontal', pad=0.1, aspect=40, shrink=0.9);`

http://stackoverflow.com/q/51090211
answer count: 1
has answer: http://stackoverflow.com/a/51090823
has title: Psycopg2 INSERT variables, string format error
has comment: http://stackoverflow.com/comment/89168926
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89169717
tagged with: python
tagged with: psycopg2
type: Question
has body: I am trying to update a row of a Postgresql table. I am using Psycopg2 and Python3. I receive the error: "TypeError: not all arguments converted during string formatting" code: self.cursor.executemany("INSERT INTO blacklisted_ips (ip, source_id, date_created, date_modified) VALUES (%s, %s, %s, %s);", ["address_list"]) ip, source_id, date_created, date_modified are the column names. passing a list of tuples address_list sample data: ('223.223.202.183', 29, '2018-06-28 12:32:02', '2018-06-28 12:32:02') I can't figure out why I get this error. I'm guessing it is centered around the place holders after "VALUES". Any help is greatly appreciated.
score: 0

http://stackoverflow.com/q/51165089
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/51168009
has comment: http://stackoverflow.com/comment/89313590
has body: I am trying to display the value A,B,C or D as per the total of a blogger. But I am getting the error - Cannot resolve keyword 'total' into field.Can someone suggest the correct way of doing it. Thanks models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs') likes = models.ManyToManyField(User, blank=True, related_name='blog_likes') title = models.CharField(max_length=100) def total_likes_received(user): return user.blogs.aggregate(total_likes=Count('likes'))['total_likes'] or 0 @property def total(self): return count(self.author.title) + count(self.author.likes) views.py def get_queryset(self): return (Blog.objects.filter(date__lte=timezone.now()) .order_by('date') .annotate( name=Case( When(total__gt=0,total__lte=11, then=Value('B')), When(total__gt=10,total__lte=21, then=Value('C')), When(total__gt=20,total__lte=31, then=Value('D')), default=Value('A'), output_field=CharField(), ), ).values_list('name') )
type: Question
has comment: http://stackoverflow.com/comment/89313733
downvote count: 0
has comment: http://stackoverflow.com/comment/89313837
accepted answer: http://stackoverflow.com/a/51168009
has title: using Case in django
answer count: 1
has comment: http://stackoverflow.com/comment/89313612
favorite count: 0
has comment: http://stackoverflow.com/comment/89313663
has comment: http://stackoverflow.com/comment/89313848
has comment: http://stackoverflow.com/comment/89313684
tagged with: django
tagged with: python
score: 14

http://stackoverflow.com/q/51082518
has answer: http://stackoverflow.com/a/51082812
has title: Python: Finite sum with variable range "TypeError: only integer scalar arrays can be converted to a scalar index"
has comment: http://stackoverflow.com/comment/89153971
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89164613
has comment: http://stackoverflow.com/comment/89167074
has body: Aim: plot V vs. MF import numpy as np V = np.arange(3,46, step = 6) A = 3 # 'n' is a sequence of odd numbers (i.e. 1,3,5,7, ...) n = V/A mm = (n+1)/2 MF = sum((np.power(-1, m)) * np.exp(m * m * (V/n)) for m in range(1,mm)) I want m to form a sequence of 1, 2, 3, ... (n+1)/2. The problem I'm having is with the final line range(1,mm) which returns TypeError: only integer scalar arrays can be converted to a scalar index Seems to me the problem is that m cannot be variable for different numbers in the same sequence. Is there a way around this?
possible better answer: http://stackoverflow.com/a/51082812
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/51189281
accepted answer: http://stackoverflow.com/a/51189281
score: 0
tagged with: python

http://stackoverflow.com/comment/89386681
score: 1
comment on: http://stackoverflow.com/q/51164091
has text: @dirn I thought streams were only for TCP not UDP?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89276727
has text: `@app.route('/index')` and do `curl -X POST http://127.0.0.15000/index -d'test'` I've gotta 405 method not allowed response
comment on: http://stackoverflow.com/a/51146293
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89164437
type: Comment
type: QuestionComment
has text: You might be able to get an exact integral with a symbolic math package in Python, but in general any Python library that calculates the integral of a function will do so numerically. That goes for just about every computational package out there, including Wolfram, although Wolfram will try to give you the exact expression as well, which you could evaluate. That numeric method may be more or less accurate than MC, but regardless, it is necessarily not *exact*.
comment on: http://stackoverflow.com/q/51086879
score: 1

http://stackoverflow.com/comment/89039867
has text: This is smart :)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51023678
type: AnswerComment

http://stackoverflow.com/q/51079503
has answer: http://stackoverflow.com/a/75492633
has answer: http://stackoverflow.com/a/59824846
has answer: http://stackoverflow.com/a/61480946
type: Question
has answer: http://stackoverflow.com/a/78584062
downvote count: 0
upvote count: 104
favorite count: 0
has answer: http://stackoverflow.com/a/75946560
accepted answer: http://stackoverflow.com/a/51080197
has comment: http://stackoverflow.com/comment/122378488
has answer: http://stackoverflow.com/a/79019004
tagged with: python-3.7
has body: I've been reading up on Python 3.7's dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if dataclass is compatible with the property decorator to define getter and setter functions for the data elements of the dataclass. If so, is this described somewhere? Or are there examples available?
score: 104
answer count: 21
has answer: http://stackoverflow.com/a/58278544
has answer: http://stackoverflow.com/a/68488125
has answer: http://stackoverflow.com/a/69855789
tagged with: python-dataclasses
has answer: http://stackoverflow.com/a/78691915
has answer: http://stackoverflow.com/a/73902301
has answer: http://stackoverflow.com/a/65127702
possible better answer: http://stackoverflow.com/a/66412774
has comment: http://stackoverflow.com/comment/116793440
has answer: http://stackoverflow.com/a/66412774
has answer: http://stackoverflow.com/a/60262167
has answer: http://stackoverflow.com/a/66053802
has answer: http://stackoverflow.com/a/69499175
tagged with: python
has answer: http://stackoverflow.com/a/61709025
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51080197
has title: Dataclasses and property decorator
has answer: http://stackoverflow.com/a/64876093
has answer: http://stackoverflow.com/a/61191878
has answer: http://stackoverflow.com/a/59036206

gmail
type: Tag
tags question: http://stackoverflow.com/q/51057304
tags question: http://stackoverflow.com/q/51130087
tag name: gmail

http://stackoverflow.com/comment/103529662
type: AnswerComment
comment on: http://stackoverflow.com/a/51142533
type: Comment
has text: @ZaneHitchcox I was thinking about the equivalent of `python-dev` packages, but I am fairly sure it's not possible.
score: 0

http://stackoverflow.com/q/51101519
possible better answer: http://stackoverflow.com/a/51102187
has title: How do I reverse the strings contained in each pair of matching parentheses, starting from the innermost pair? CodeFights
score: 7
has answer: http://stackoverflow.com/a/51102359
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/89191385
has answer: http://stackoverflow.com/a/51102187
has answer: http://stackoverflow.com/a/51101654
has body: So far I have done this. I am stuck on recursion. I have no idea how to move forward, joining and reversing etc. def callrecursion(s): a=s.index('(') z=len(s) - string[::-1].index(')') -1 newStr=s[a+1:z] # Something is missing here i cant figure it out print(newStr) return newStr def reverseParentheses(s): if '(' in s: return reverseParentheses(callrecursion(s)) print('wabba labba dub dub') else: return s string='a(bcdefghijkl(mno)p)q' reverseParentheses(string) EXPECTED OUTPUT : "apmnolkjihgfedcbq"
has comment: http://stackoverflow.com/comment/89190247
answer count: 6
has comment: http://stackoverflow.com/comment/89191257
has answer: http://stackoverflow.com/a/71316719
downvote count: 0
has comment: http://stackoverflow.com/comment/89191167
has answer: http://stackoverflow.com/a/51102284
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/72228517
accepted answer: http://stackoverflow.com/a/51102359
has comment: http://stackoverflow.com/comment/89190327
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89086880
score: 0
type: Comment
type: QuestionComment
has text: where would #000000 fall?
comment on: http://stackoverflow.com/q/51047829

http://stackoverflow.com/comment/89301278
comment on: http://stackoverflow.com/q/51158998
type: Comment
type: QuestionComment
score: 1
has text: You're going to have to make very significant additions if you want to be able to store each user's basket.

http://stackoverflow.com/a/51132060
type: Answer
has comment: http://stackoverflow.com/comment/89276566
has comment: http://stackoverflow.com/comment/89322779
score: 0
has comment: http://stackoverflow.com/comment/89250873
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89276579
accepted answer of: http://stackoverflow.com/q/51131937
has comment: http://stackoverflow.com/comment/89249808
has comment: http://stackoverflow.com/comment/89307050
has comment: http://stackoverflow.com/comment/89321738
answers question: http://stackoverflow.com/q/51131937
has comment: http://stackoverflow.com/comment/89320742
has body: In your current example, it would be sufficient to store the values into a list. Later, when you need these values, iterate over the list and get each cell name one by one. #!/usr/bin/python import os import os.path myPWD = os.getcwd() # Implement functions get_test_directory and get_library_directory # to retrieve correct directory paths test_directory = get_test_directory(myPWD) library_directory = get_library_directory(myPWD) cell_names_file = os.path.join(test_directory, "c_name.txt") with open(cell_names_file, "r+") as f1: cell_names = [line.strip() for line in f1] for cell_name in cell_names: cell_directory = "ce_" if cell_name.startswith("ce_") else "cell" floc2 = os.path.join(library_directory, cell_directory, "{0}.rpt".format(cell_name)) EDIT: The code was updated to account for the new information from the question. There is no precise information about the directory structure, so I'm using dummy placeholders.
has comment: http://stackoverflow.com/comment/89324002
has comment: http://stackoverflow.com/comment/89313500

http://stackoverflow.com/comment/89160499
type: QuestionComment
comment on: http://stackoverflow.com/q/51064746
score: 1
has text: If a question is related to RStudio, please state its version. Without that information, a blind guess is that the latest (preview) version might have fixed your problem: https://www.rstudio.com/products/rstudio/download/preview/
type: Comment

http://stackoverflow.com/comment/89091375
has text: I have a question, for the column AREA after running your code once, you have 5 for the second row. It means that it uses the value of AREA at the first row already updated right and equal to 2, not 1 anymore?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51045848
score: 0

http://stackoverflow.com/comment/89043042
comment on: http://stackoverflow.com/q/51025252
score: 0
type: QuestionComment
has text: @HarvIpan ValueError: No axis named user_Id for object type <class 'pandas.core.frame.DataFrame'>
type: Comment

bidirectional
tags question: http://stackoverflow.com/q/51064016
tag name: bidirectional
type: Tag

http://stackoverflow.com/q/51060126
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89110792
has title: Writing formulas with Python Doxygen
has body: I am trying to write a formula into the doxygen output file using the latest version of doxygen (1.8.14). I tried: # @f$(@sum_{sc=1}^{3} @sum_{n=1}^{24} pENSCost * ENS_sc,n)@f$ But doing so does not give me the desired output, but instead of the sigmas (the sum sign) it just gives me @sum , even though with the desired indices, but I don´t get any error messages. Does anybody know what I did wrong?
accepted answer: http://stackoverflow.com/a/51063769
has comment: http://stackoverflow.com/comment/89110311
answer count: 1
tagged with: doxygen
tagged with: latex
tagged with: python
has comment: http://stackoverflow.com/comment/89110925
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51063769
has comment: http://stackoverflow.com/comment/89116988

http://stackoverflow.com/comment/89128817
type: Comment
comment on: http://stackoverflow.com/a/51069443
has text: @StephenGonzalez, yes, usually like that
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89284226
has text: Do you have a minimal reproducible git repo?
score: 0
comment on: http://stackoverflow.com/q/51098037
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89282937
type: QuestionComment
has text: Which button are you trying to click?
comment on: http://stackoverflow.com/q/51149507
score: 0
type: Comment

http://stackoverflow.com/comment/89417245
comment on: http://stackoverflow.com/a/51169674
type: AnswerComment
score: 0
type: Comment
has text: Tried it, but it seems to just reverse the direction of the roll-up. I improved my code example so you can see it better in action.

http://stackoverflow.com/a/51168705
has comment: http://stackoverflow.com/comment/89322455
has body: The output seems to be a tab separated string/list of tab separated strings. I would change the complete string to a list of strings def make_dict(input_list): final_output = [] headers = input_list[0].strip().split("\t") for line in input_list[1:]: line = line.strip().split("\t") final_output.append({key: value for key,value in zip(headers, line)} ) return final_output Input_str = """Filesystem Type 1K-blocks Used Available Use% Mounted on /dev/sda ext4 245671 47009 181459 21% /initlo /dev/loop7 squashfs 39552 39552 0 100% / none tmpfs 65536 1064 64472 2% /tmp none aufs 65536 1064 64472 2% /dev none tmpfs 510184 24 510160 0% /dev/shm none aufs 65536 1064 64472 2% /etc none aufs 65536 1064 64472 2% /var none aufs 65536 1064 64472 2% /www none aufs 65536 1064 64472 2% /mcl none aufs 65536 1064 64472 2% /eds """ input_list = Input_str.split("\n") print(make_dict(input_list)) Output: [{'Filesystem': '/dev/sda', 'Type': '', '1K-blocks': 'ext4', 'Used': ' 245671', 'Available': '47009', 'Use%': '181459', 'Mounted on': '21%'}, {'Filesystem': '/dev/loop7', 'Type': 'squashfs', '1K-blocks': '39552', 'Used': '39552', 'Available': '0', 'Use%': '100%', 'Mounted on': '/'}, {'Filesystem': 'none', 'Type': 'tmpfs', '1K-blocks': ' 65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%', 'Mounted on': '/tmp'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%', 'Mounted on': '/dev'}, {'Filesystem': 'none', 'Type': 'tmpfs', '1K-blocks': '510184', 'Used': '', 'Available': '24', 'Use%': '510160', 'Mounted on': '0%t/dev/shm'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%', 'Mounted on': '/etc'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%', 'Mounted on': '/var'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%', 'Mounted on': '/www'}…
answers question: http://stackoverflow.com/q/51167361
downvote count: 0
has comment: http://stackoverflow.com/comment/89323399
has comment: http://stackoverflow.com/comment/89323577
type: Answer
has comment: http://stackoverflow.com/comment/89321579
upvote count: 1
has comment: http://stackoverflow.com/comment/89322014
score: 1

http://stackoverflow.com/comment/89285026
type: QuestionComment
comment on: http://stackoverflow.com/q/51144462
has text: maya is compiled with a version of python 2.7 and VS2012, you might to have to compile it with the same version as maya. see there http://around-the-corner.typepad.com/adn/2016/08/compiler-versions-for-maya-2017.html
score: 0
type: Comment

http://stackoverflow.com/q/51090505
tagged with: bootstrap-4
has answer: http://stackoverflow.com/a/52021082
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89205815
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I've been searching for an answer but any of them are useful for me. The problem is that I want to show a non_field_error with the following code in HTML: {% if form.non_field_errors %} &lt;div class="alert alert-danger"&gt;{{ form.non_field_errors|join:"&lt;br \&gt;" }}&lt;/div&gt; {% endif %} This, produces the following result: The duplicated error, one formatted and the other not This is my forms.py code: user = authenticate(username=username, password=password) if not user or not user.is_active: self.add_error(None, "Incorrect credentials") How can I show only the formatted field instead of both? UPDATE: If I try with this approach: {% if form.non_field_errors %} {% for error in form.non_field_errors %} &lt;div class="alert alert-danger"&gt;{{ error }}&lt;/div&gt; {% endfor %} {% endif %} I have more or less the same problem: The same error. It appears twice
has title: Django Non_Field_Error shown duplicated Bootstrap
tagged with: django-forms
type: Question
has answer: http://stackoverflow.com/a/51090745
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89169682

http://stackoverflow.com/a/51082635
has comment: http://stackoverflow.com/comment/102011724
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/102011386
downvote count: 0
answers question: http://stackoverflow.com/q/51064157
score: 5
has body: Use bfill and ffill with axis=1: dfs = dfs.bfill(axis=1).ffill(axis=1) Part of the problem are the inplace=True and chaining methods. inplace=True returns a null object so, there is nothing to call chained methods from. The second part is that fillna(method='ffill') can be shortened to just ffill().
accepted answer of: http://stackoverflow.com/q/51064157
type: AcceptedAnswer

http://stackoverflow.com/a/51109935
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51109208
has body: IsocurveItem inherited .scale() and .translate() methods through GraphicsObject, of which it is a subclass. So, just add these lines to the example after defining c: c.translate(x.min(), y.min()) c.scale((x.max() - x.min()) / np.shape(z)[0], (y.max() - y.min()) / np.shape(z)[1]) To make the test more rigorous, I also changed x so it doesn't start at 0: x = np.linspace(10, 16.28, 30) The output is now It may be a little easier to visualize with an ImageItem in the mix (also translated and scaled):
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51109208

http://stackoverflow.com/a/51089382
has body: 1st issue - firewall or some other services may be blocking your port. 2nd Issue - you are running in interactive terminal. Please execute the command in command prompt.
answers question: http://stackoverflow.com/q/51089257
score: 0
type: Answer

http://stackoverflow.com/comment/89230820
comment on: http://stackoverflow.com/a/51118807
type: Comment
score: 0
has text: That helped so much thank you!
type: AnswerComment

http://stackoverflow.com/comment/89267855
comment on: http://stackoverflow.com/q/51140916
type: QuestionComment
type: Comment
has text: Okay, your dataframe structure is still somewhat ambitious. Wouldyou mind doing a df.head(10).to_dict and posting to the question.
score: 0

http://stackoverflow.com/q/51069236
has title: R equivalent of Python's dask
has answer: http://stackoverflow.com/a/51832984
has answer: http://stackoverflow.com/a/75161066
score: 15
has comment: http://stackoverflow.com/comment/89128369
has comment: http://stackoverflow.com/comment/127136547
has answer: http://stackoverflow.com/a/51072309
type: Question
has body: Is there an equivalent package in R to Python's dask? Specifically for running Machine Learning algorithms on larger-than-memory data sets on a single machine. Link to Python's Dask page: https://dask.pydata.org/en/latest/ From the Dask website: Dask natively scales Python Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love Dask's schedulers scale to thousand-node clusters and its algorithms have been tested on some of the largest supercomputers in the world. But you don't need a massive cluster to get started. Dask ships with schedulers designed for use on personal machines. Many people use Dask today to scale computations on their laptop, using multiple cores for computation and their disk for excess storage.
upvote count: 15
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/89133429
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/71432325
tagged with: dask
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/109051429
tagged with: python
has comment: http://stackoverflow.com/comment/89134500
answer count: 4

http://stackoverflow.com/comment/89039765
has text: note you aren't actually closing the file here, change file.close to read 'file.close()'.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51021826

http://stackoverflow.com/comment/89230704
type: QuestionComment
type: Comment
has text: Don't understand what you want! Do you want non-linear regression? or do you want to know how to fir your output to `fit my output to the X_train and Y_train data` because you already seem to have done that!
comment on: http://stackoverflow.com/q/51120555
score: 0

http://stackoverflow.com/comment/89192925
has text: Fantastic, Thanks a lot @PaulPanzer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51100284
type: AnswerComment

http://stackoverflow.com/a/51067184
score: 0
has comment: http://stackoverflow.com/comment/89124655
has body: It looks like all you are trying to do is rename the column. I would try it like this. tableOne = df.loc[df['table'].isin(['t1','t2'])] tableOne.rename(index=str, columns={"pd_date": "BaseDate") tableTwo = df.loc[df['table'].isin(['t1','t2'])] tableTwo.rename(index=str, columns={"nd_date": "BaseDate") df = pd.concat([tableOne,tableTwo])
answers question: http://stackoverflow.com/q/51066832
type: Answer

http://stackoverflow.com/q/51143556
tagged with: python-module
has comment: http://stackoverflow.com/comment/89274591
has comment: http://stackoverflow.com/comment/89272149
answer count: 0
type: UnansweredQuestion
tagged with: google-app-engine
has title: Google Cloud - Node jS + Python. How to install requirements.txt?
tagged with: python
tagged with: node.js
has comment: http://stackoverflow.com/comment/89274800
has comment: http://stackoverflow.com/comment/89274792
type: Question
has body: I have a Google Cloud Node project, which runs some python code through child_process The code in my machine runs well, however when the code is run in the server it fails because the python modules are not found. I'm trying to install the modules in requirements.txt but setting it up on root folder doesn't work as it isn't a python env in the yaml file. Testing is really slow (about 20 minutes to deploy) so I am wondering if anyone knows how to install those modules.
score: 0
has comment: http://stackoverflow.com/comment/89507396
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/89274831

http://stackoverflow.com/comment/89247798
has text: I think the sample code in your question is not the same you are using with your local script. The DataFrame is created just with the numbers as shown in the answer. The other numbers are not part of your dictionary, and therefor not part of the created DataFrame. And please rename the variable 'dict' to 'mydict' or something else. 'dict' is a reserved keyword of Python itself. When using it to assign a variable you get funny side effects.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51104145
type: AnswerComment

http://stackoverflow.com/comment/89318092
comment on: http://stackoverflow.com/a/51167257
score: 1
type: AnswerComment
has text: You have to navigate it atleast once to find the length of longest element. Something like this might work `max([len(e) for d in data for k,v in d.items() for e in v])`
type: Comment

http://stackoverflow.com/comment/89233742
score: 2
has text: You can't do that. There are no hooks in Python that let you adjust assignments.
comment on: http://stackoverflow.com/q/51124328
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51114445
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51114738
favorite count: 0
score: 4
linked to: http://stackoverflow.com/q/11528078
tagged with: python
has body: So I am trying to solve a problem which makes you compare numbers in the 9x9 sudoku grid so see if the game of Sudoku has a valid/solvable grid of numbers (Meaning that the rules of Sudoku apply to the given grid). I have pretty much solved the problem, but I am stuck on this last part. I have figured out how sum up each element on each column/row, but I am not able to completely solve this problem until I can actually check each 3x3 grid to see if there are no duplicate numbers in them. This is where I am stuck because I cannot seem to get the right algorithm to iterate through the matrix in a 3x3 fashion. I tried to control the iteration completely by using a series of for loops that increase the certain index number so it moves along the matrix. Let me know what I am doing wrong--or if there are any other possible, more elegant ways to solve this problem (using so many for loops makes my code look long and ugly/less efficient). def sudoku(grid): grid = [[1,3,2,5,4,6,9,8,7], [4,6,5,8,7,9,3,2,1], [7,9,8,2,1,3,6,5,4], [9,2,1,4,3,5,8,7,6], [3,5,4,7,6,8,2,1,9], [6,8,7,1,9,2,5,4,3], [5,7,6,9,8,1,4,3,2], [2,4,3,6,5,7,1,9,8], [8,1,9,3,2,4,7,6,5]] duplicate = set() numHolder = 0 for a in range(0,9): for b in range(0,9): numHolder+=grid[b][a] if numHolder!=45: return False numHolder=0 for b in range(0,9): for x in range(0, 9): numHolder += grid[b][x] if numHolder != 45: return False numHolder = 0 for b in range(0,3): for c in range(0,3): if grid[b][c] in duplicate: return False else: duplicate.add(grid[b][c]) duplicate.clear() for d in range(0,3): for e in range(0,3): if grid[d][c+3] in duplicate: return False else: duplicate.add(grid[d][c+3]) duplicate.clear() for d in range(0,3): for e in range(0,3): if grid[b][c+6] in duplicate: return False else: duplicate.add(grid[d][c+6]) duplicate.clear() for d in range(0,3): for e in range(0,3): if grid[d+3][c] in duplicate: return False else: duplicate.add(grid[d+3][c]) duplicate.clear() for d in range(0,3): for e in range(0,3): i…
answer count: 5
has answer: http://stackoverflow.com/a/51114738
has title: Trying to figure out a way to compare numbers in a 9x9 matrix by using 3x3 matrices
upvote count: 4
possible better answer: http://stackoverflow.com/a/51114940
has answer: http://stackoverflow.com/a/51114940
downvote count: 0
has answer: http://stackoverflow.com/a/51115550
has answer: http://stackoverflow.com/a/69625598
has answer: http://stackoverflow.com/a/51115455

http://stackoverflow.com/comment/89250388
comment on: http://stackoverflow.com/q/51132454
score: 0
type: Comment
type: QuestionComment
has text: @tobias_k Good remark, didn't even noticed it. Distanc of 1, should have been outputted.

http://stackoverflow.com/a/51081584
downvote count: 0
has body: I'm unable to reproduce your problem in my Pandas version (0.23.1), but it's possible to be explicit about the types when reading the CSV file by using the dtype parameter. Like this: import pandas as pd import numpy as np from io import StringIO def read_data(): return StringIO("""IntNumber\n3.0\n45.0\n\n123.0""") df = pd.read_csv(read_data(), dtype={'IntNumber': np.float32}) print(df.dtypes) # Output: # IntNumber float32 # dtype: object df = pd.read_csv(read_data(), dtype={'IntNumber': np.int32}) print(df.dtypes) # Output: # IntNumber int32 # dtype: object
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51080943
score: 1

http://stackoverflow.com/a/51096570
score: 0
type: AcceptedAnswer
has body: I suggest use GroupBy.any with transform for check at least one Trues per groups and then for column by conditions numpy.select: Use: print (df) Invoice # Invoice sub Number Amount 0 123 1234 100 1 123 2345 200 2 123 3456 300 3 123 1200 400 4 123 2100 500 5 1234 1245 600 6 1234 2344 700 7 1234 1200 800 8 2345 345 900 9 2345 2100 1000 10 2345 2458 1100 11 6789 2345 1200 12 6789 3421 1300 13 6789 1234 1400 m1 = df['Invoice sub Number'].astype(str).str.startswith('1200') m2 = df['Invoice sub Number'].astype(str).str.startswith('2100') m11 = m1.groupby(df['Invoice #']).transform('any') m22 = m2.groupby(df['Invoice #']).transform('any') masks =[ m11 &amp; m22 , m11, m22] vals = ['Contains both 1200 and 2100', 'Contains 1200 only','Contains 2100 only'] default = 'Contains neither 1200 nor 2100' df['dummy'] = np.select(masks, vals, default=default) print (df) Invoice # Invoice sub Number Amount dummy 0 123 1234 100 Contains both 1200 and 2100 1 123 2345 200 Contains both 1200 and 2100 2 123 3456 300 Contains both 1200 and 2100 3 123 1200 400 Contains both 1200 and 2100 4 123 2100 500 Contains both 1200 and 2100 5 1234 1245 600 Contains 1200 only 6 1234 2344 700 Contains 1200 only 7 1234 1200 800 Contains 1200 only 8 2345 345 900 Contains 2100 only 9 2345 2100 1000 Contains 2100 only 10 2345 2458 1100 Contains 2100 only 11 6789 2345 1200 Contains neither 1200 nor 2100 12 6789 3421 1300 Contains neither 1200 nor 2100 13 6789 1234 1400 Contains neither 1200 nor 2100
type: Answer
has comment: http://stackoverflow.com/comment/89189519
has comment: http://stackoverflow.com/comment/89192935
has comment: http://stackoverflow.com/comment/89186117
has comment: http://stackoverflow.com/comment/89188776
answers question: http://stackoverflow.com/q/51096308
has comment: http://stackoverflow.com/comment/89189339
has comment: http://stackoverflow.com/comment/89196387
has comment: http://stackoverflow.com/comment/89189555
has comment: http://stackoverflow.com/comment/89188988
accepted answer of: http://stackoverflow.com/q/51096308
has comment: http://stackoverflow.com/comment/89185021
has comment: http://stackoverflow.com/comment/89188372
has comment: http://stackoverflow.com/comment/89194708

http://stackoverflow.com/a/51114199
has comment: http://stackoverflow.com/comment/89214726
has body: I am not very experienced with numpy, but based on the comments of @hpaulj I can suggest the following: If you don't want to be subject to the limitations of numpy.matrix objects (see warning here), you can define your own function for doing a conjugate transpose. All you need to do is transpose your array, then subtract the imaginary part of the result, times 2, from the result. I am not sure how computationally efficient this is, but it should definitely give the correct result. I'd expect something like this to work: Y = C * ctranspose(Up[:, 0:p-1]) * Y ... def ctranspose(arr: np.ndarray) -&gt; np.ndarray: # Explanation of the math involved: # x == Real(X) + j*Imag(X) # conj_x == Real(X) - j*Imag(X) # conj_x == Real(X) + j*Imag(X) - 2j*Imag(X) == x - 2j*Imag(X) tmp = arr.transpose() return tmp - 2j*tmp.imag (Solution is for Python 3) A more elegant solution based on the comment by @AndrasDeak: Y = C * Up[:, 0:p-1].conj().T * Y Note also, two differences related to indexing between python and MATLAB: Python is 0-based (i.e. the first index of an array is 0, unlike in MATLAB where it's 1) The indexing in Python is inclusive:exclusive unlike in MATLAB where it's inclusive:inclusive. Therefore, when we want to access the first 3 elements of a vector in MATLAB we'd write: res = vec(1:3); In Python we'd write: res = vec[0:3] # or [:3] (Again, credits to @Andras for this explanation)
score: 5
has comment: http://stackoverflow.com/comment/89305873
type: Answer
accepted answer of: http://stackoverflow.com/q/51106981
answers question: http://stackoverflow.com/q/51106981
upvote count: 5
has comment: http://stackoverflow.com/comment/89214703
has comment: http://stackoverflow.com/comment/89214679
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51153175
score: 1
tagged with: mongodb
answer count: 1
downvote count: 0
has title: How to safe encode a random byte array into textual format
has answer: http://stackoverflow.com/a/51153555
tagged with: python
accepted answer: http://stackoverflow.com/a/51153555
favorite count: 0
tagged with: python-3.x
has body: Mongo Change Stream is retuned in a binary format To be able to script a mongo change stream I want to encode the byte array into a format that would be command line parameter safe. pprint.pprint(change['_id']['_data']) (b'\x82[8\x92G\x00\x00\x00\x01Fd_id\x00d[8\x91\xf2.\xc2\xd4\x00\x0b\xabO\x98' b'\x00Z\x10\x04\x16,\x92\xf8\xbf\x92G\x87\x8d1\xff(\x1a\x1b{\xc8\x04') What would be a safe format to convert the binary array text that would be accepted as a parameter? Example for conversion from binary to given format, and from given format input str() back into binary would be helpful. Attempt 1 base64.b85encode(change['_id']['_data']).decode('ascii') 'f?GI}M*si-0Y+qBX=DIoTR4&amp;OF2d9R3#(6&lt;09p_P7A%tZzmi9XjWPcy8XJ4a1O' Going from binary to base85 works, but I can't seem to figure the way back. EDIT: Reopening Rational I think this question should not be marked as duplicate as this question targets conversion of random byte arrays which do not represent a human readable character / encoding. As follows the previous question focuses on converting a string into binary array and back, which is a special case of binary to string representation while my use case calls for a generic solution.
upvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/89199428
comment on: http://stackoverflow.com/q/51105996
score: 0
type: Comment
type: QuestionComment
has text: Would that be best done with a try catch? `if(str(type(tcp_connect_scan_resp))=="<type 'NoneType'>"): print ('dead')` This is a method I've seen online but it doesn't seem to work for me yet

http://stackoverflow.com/q/51057351
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89106033
has comment: http://stackoverflow.com/comment/89107389
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89105223
has comment: http://stackoverflow.com/comment/89105390
has body: I have a set of data for my vehicle tracking system that requires me to calculate the distance base on lat and long. Understand that by using haversine formula can help getting distance between rows but I'm sort of stucked as I need my distance based on 2 field(Model type and mode). As shown below is my code: def haversine(lat1,lon1,lat2,lon2, to_radians = True, earth_radius =6371): if to_radians: lat1,lon1,lat2,lon2 = np.radians([lat1,lon1,lat2,lon2]) a = np.sin((lat2-lat1)/2.0)**2+ np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2 return earth_radius *2 * np.arcsin(np.sqrt(a)) mydataset = pd.read_csv(x + '.txt') print (mydataset.shape) mydataset = mydataset.sort_values(by=['Model','timestamp']) #sort mydataset['dist'] = np.concatenate(mydataset.groupby(["Model"]).apply(lambda x: haversine(x['Latitude'],x['Longitude'], x['Latitude'].shift(),x['Longitude'].shift())).values) With this, I am able to calculate the distance based on the model(by using sorting) between the rows. But I would like to take it a step further to calculate based on both Mode and model. My fields are "Index, Model, Mode, Lat, Long, Timestamp" Please advice! Index, Model, Timestamp, Long, Lat, Mode(denote as 0 or 2), Distance Calculated 1, X, 2018-01-18 09:16:37.070, 103.87772815, 1.35653496, 0, 0.0 2, X, 2018-01-18 09:16:39.071, 103.87772815, 1.35653496, 0, 0.0 3, X, 2018-01-18 09:16:41.071, 103.87772815, 1.35653496, 0, 0.0 4, X, 2018-01-18-09:16:43.071, 103.87772052, 1.35653496, 0, 0.0008481795 5, X, 2018-01-18 09:16:45.071, 103.87770526, 1.35653329, 0, 0.0017064925312804799 6, X, 2018-01-18 09:16:51.070, 103.87770526, 1.35653329, 2, 0.0 7, X, 2018-01-18 09:16:53.071, 103.87770526, 1.35653329, 2, 0.0 8, X, 2018-01-18 09:59:55.072, 103.87770526, 1.35652828, 0, 0.0005570865824842293 I need it to calculate distance of total journey of a model and also distance of total journey of a model in whichever mode
tagged with: distance
score: 0
has comment: http://stackoverflow.com/comment/89111972
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89107485
has comment: http://stackoverflow.com/comment/89107344
favorite count: 0
has answer: http://stackoverflow.com/a/51058864
has comment: http://stackoverflow.com/comment/89107276
has comment: http://stackoverflow.com/comment/89109142
tagged with: pandas
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/89105601
has title: Calculate distance based on lat long, groupby 2 field in python

http://stackoverflow.com/a/51040956
upvote count: 4
has body: Here: form = EmailPostForm(data=request.method) you want request.POST, not request.method. As a side note: a successful post should be followed by a redirect (to prevent page reload to repost the same data). You can use the contrib.messages app to set a message in session, that will then be displayed on the next page.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51040726
score: 4

http://stackoverflow.com/comment/89149864
comment on: http://stackoverflow.com/q/51080681
has text: This may be a design choice or an oversight. Unless you can catch the guy wrote the library, you are likely to only find opinions here (not too helpful).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51036950
type: AcceptedAnswer
has body: Here is the issue related to this behavior: https://github.com/pandas-dev/pandas/issues/20675. In short, if argument passed to notnull is of type list, internally it is converted to np.array with np.asarray method. This bug occured, because, if no dtype specified, numpy converts np.nan to string(which is not recognized by pd.isnull as null value): a = ['A4', np.nan] np.asarray(a) # array(['A4', 'nan'], dtype='&lt;U3') This problem was fixed in version 0.23.0, by calling np.asarray with dtype=object.
answers question: http://stackoverflow.com/q/51035790
type: Answer
score: 3
downvote count: 0
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51035790

http://stackoverflow.com/comment/89128244
has text: @Mike-SMT ok thank you, sorry for disturbing
score: 0
comment on: http://stackoverflow.com/q/51068931
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51143458
downvote count: 2
has answer: http://stackoverflow.com/a/62620348
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65867103
has title: Difference in output with waitKey(0) and waitKey(1)
type: Question
has answer: http://stackoverflow.com/a/51143586
upvote count: 84
answer count: 6
has answer: http://stackoverflow.com/a/63218374
favorite count: 0
has answer: http://stackoverflow.com/a/51143583
possible better answer: http://stackoverflow.com/a/52379508
score: 82
has body: I've just begun using the OpenCV library for Python and came across something I didn't understand. cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() #returns ret and the frame cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break When I use cv2.waitKey(1), I get a continuous live video feed from my laptops webcam. However when I use cv2.waitKey(0), I get still images. Every time I close the window, another one pops up with another picture taken at the time. Why does it not show as a continuous feed?
tagged with: python
has answer: http://stackoverflow.com/a/52379508
accepted answer: http://stackoverflow.com/a/51143586

http://stackoverflow.com/q/51134084
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51136604
accepted answer: http://stackoverflow.com/a/51136604
has body: I try to use a prototype python code in an Android app and I found Chaquopy as a possible library. The documentation is a little sparse, so I want to clarify: Can I call my self-written python methods (incl. passing variables) in Android Java code with Chaquopy? If yes, would it be possible to see an example how this works? Seeing an example which especially passes complex objects (so not only strings) I would really appreciate. Thanks!
upvote count: 5
tagged with: java
type: Question
tagged with: chaquopy
answer count: 1
tagged with: android
has title: Self-written python code in Android with Chaquopy
favorite count: 0
downvote count: 2
tagged with: python

http://stackoverflow.com/a/51155189
answers question: http://stackoverflow.com/q/51154674
type: Answer
has body: hard to tell what you're trying to do....but a simple getattr might help child_var = 'child1' qs = getattr(ParentModelInstance, child_var+'_set').all()
score: 0

http://stackoverflow.com/a/51159820
downvote count: 0
has body: Pandas can likely handle this on its own with read_html. You can then cleanup data types, etc. within the resulting frame. Returns an array of matches - here's the general idea: import pandas as pd url = 'https://azure.microsoft.com/en-us/pricing/details/virtual-machines/windows/' dfs = pd.read_html(url, attrs={'class':'sd-table'}) print dfs[0] Hope that helps!
has comment: http://stackoverflow.com/comment/89303736
type: Answer
answers question: http://stackoverflow.com/q/51159585
upvote count: 1
score: 1

http://stackoverflow.com/comment/89170152
comment on: http://stackoverflow.com/q/51090894
type: Comment
type: QuestionComment
has text: that happens if `3_54_7__B_1\\Application_Release_Note.doc` is write-protected. can you check that point?
score: 1

http://stackoverflow.com/q/51108227
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
linked to: http://stackoverflow.com/q/17597424
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39928515
has title: Not able to parse table data beautifulsoup from website bseindia.com
has answer: http://stackoverflow.com/a/51141766
linked to: http://stackoverflow.com/q/22130109
upvote count: 1
downvote count: 1
type: Question
has body: I have a situation where I am not able to parse data from following link for example: https://www.bseindia.com/stock-share-price/avanti-feeds-ltd/avanti/512573/ From this webpage I want to populate High Lows table. I tried many combinations of table and div but in vain. Below is my python beautifulsoup code (BS4) import csv import requests import urllib.request import urllib.parse from bs4 import BeautifulSoup f = open('bse.csv', 'w', newline = '') writer = csv.writer(f) with open("bselist.csv") as f: for row in csv.reader(f): for stock in row: url = "https://www.bseindia.com/stock-share-price/{}".format(stock) soup = BeautifulSoup(urllib.request.urlopen(url).read(), "lxml") mydivs = soup('div', {"class": "newscripcotent5"})[0].find_all('span') writer.writerow([stock] + mydivs) print([stock] + mydivs) URL for simplicity I have given direct link to one of the records contained in the file bselist.csv. I am looking for div id "highlow" It just gives me following output avanti-feeds-ltd/avanti/512573/ without any table I am looking for. Output should be ideally somewhat like following: avanti-feeds-ltd/avanti/512573/ 52 Week High (adjusted) 999.00(13/11/2017) avanti-feeds-ltd/avanti/512573/ 52 Week Low (adjusted) 410.26(05/06/2018) avanti-feeds-ltd/avanti/512573/ 52 Week High (Unadjusted) 3,000.00(13/11/2017) avanti-feeds-ltd/avanti/512573/ 52 Week Low (Unadjusted) 535.50(29/06/2018) avanti-feeds-ltd/avanti/512573/ Month H/L 659.34/410.26 avanti-feeds-ltd/avanti/512573/ Week H/L 625.25/508.82
score: 0
accepted answer: http://stackoverflow.com/a/51141766
answer count: 1
favorite count: 0
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/40373801

http://stackoverflow.com/comment/89135751
has text: @CDNthe2nd, I have update a new method, hope it helps.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51072933
type: Comment

http://stackoverflow.com/q/51144059
tagged with: asynchronous
tagged with: discord
favorite count: 0
accepted answer: http://stackoverflow.com/a/51144281
has comment: http://stackoverflow.com/comment/89272838
has comment: http://stackoverflow.com/comment/89272757
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: How to rate limit a coroutine and re-call the coroutine after the limit?
has body: I've been reading through the responses here: What&#39;s a good rate limiting algorithm? The reply from Carlos A. Ibarra works great without asynchronous capabilities, but is there any way I can amend it to work asynchronously? import time def RateLimited(maxPerSecond): minInterval = 1.0 / float(maxPerSecond) def decorate(func): lastTimeCalled = [0.0] def rateLimitedFunction(*args,**kargs): elapsed = time.clock() - lastTimeCalled[0] leftToWait = minInterval - elapsed if leftToWait&gt;0: time.sleep(leftToWait) ret = func(*args,**kargs) lastTimeCalled[0] = time.clock() return ret return rateLimitedFunction return decorate @RateLimited(2) # 2 per second at most def PrintNumber(num): print num if __name__ == "__main__": print "This should print 1,2,3... at about 2 per second." for i in range(1,100): PrintNumber(i) Changing time.sleep(leftToWait) to await asyncio.sleep(leftToWait) and awaiting PrintNumber(i) works for the first instance, but none thereafter. I'm really new at Python and trying my best to obey an API's rate limit. My implementation: def rate_limited(max_per_second): min_interval = 1.0 / float(max_per_second) def decorate(func): last_time_called = [0.0] async def rate_limited_function(*args, **kargs): elapsed = time.clock() - last_time_called[0] left_to_wait = min_interval - elapsed if left_to_wait &gt; 0: await asyncio.sleep(left_to_wait) ret = func(*args, **kargs) last_time_called[0] = time.clock() return ret return rate_limited_function return decorate class Test: def __init__(self, bot): self.bot = bot @commands.command(hidden=True, pass_context=True) @checks.serverowner() async def test1(self, ctx): await self.print_number() @rate_limited(0.1) def print_number(self): print("TEST")
score: 1
has comment: http://stackoverflow.com/comment/89272306
linked to: http://stackoverflow.com/q/667508
type: Question
has answer: http://stackoverflow.com/a/51144510
tagged with: rate-limiting
answer count: 2
has comment: http://stackoverflow.com/comment/89273237
tagged with: discord.py
has answer: http://stackoverflow.com/a/51144281
has comment: http://stackoverflow.com/comment/89272521
downvote count: 0
possible better answer: http://stackoverflow.com/a/51144510
has comment: http://stackoverflow.com/comment/89272895

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/51090894

mysql
tags question: http://stackoverflow.com/q/51144779
tags question: http://stackoverflow.com/q/51106422
tags question: http://stackoverflow.com/q/51157481
tags question: http://stackoverflow.com/q/51092894
tags question: http://stackoverflow.com/q/51066637
tags question: http://stackoverflow.com/q/51050791
tags question: http://stackoverflow.com/q/51093010
tags question: http://stackoverflow.com/q/51014628
tags question: http://stackoverflow.com/q/51106189
tag name: mysql
tags question: http://stackoverflow.com/q/51018536
tags question: http://stackoverflow.com/q/51129452
tags question: http://stackoverflow.com/q/51013108
tags question: http://stackoverflow.com/q/51059005
tags question: http://stackoverflow.com/q/51052244
tags question: http://stackoverflow.com/q/51098959
tags question: http://stackoverflow.com/q/51112813
tags question: http://stackoverflow.com/q/51062223
tags question: http://stackoverflow.com/q/51014594
tags question: http://stackoverflow.com/q/51080432
tags question: http://stackoverflow.com/q/51029955
tags question: http://stackoverflow.com/q/51075852
tags question: http://stackoverflow.com/q/51134744
tags question: http://stackoverflow.com/q/51030253
tags question: http://stackoverflow.com/q/51141989
tags question: http://stackoverflow.com/q/51117503
tags question: http://stackoverflow.com/q/51117208
tags question: http://stackoverflow.com/q/51152490
tags question: http://stackoverflow.com/q/51073229
tags question: http://stackoverflow.com/q/51058007
tags question: http://stackoverflow.com/q/51163233
tags question: http://stackoverflow.com/q/51159566
tags question: http://stackoverflow.com/q/51137970
tags question: http://stackoverflow.com/q/51101082
type: Tag
tags question: http://stackoverflow.com/q/51037625
tags question: http://stackoverflow.com/q/51060165
tags question: http://stackoverflow.com/q/51087968
tags question: http://stackoverflow.com/q/51164606
tags question: http://stackoverflow.com/q/51152183
tags question: http://stackoverflow.com/q/51102643
tags question: http://stackoverflow.com/q/51089621
tags question: http://stackoverflow.com/q/51028906
tags question: http://stackoverflow.com/q/51014687
tags question: http://stackoverflow.com/q/51074933
tags question: http://stackoverflow.com/q/51034637
tags question: http://stackoverflow.com/q/51040054
tags question: http://stackoverflow.com/q/51107799
tags question: http://stackoverflow.com/q/51089141
tags question: http://stackoverflow.com/q/51118963
tags question: http://stackoverflow.com/q/51109303
tags question: http://stackoverflow.com/q/51058587
tags question: http://stackoverflow.com/q/51158299
tags question: http://stackoverflow.com/q/51082256
tags question: http://stackoverflow.com/q/51117782
tags question: http://stackoverflow.com/q/51062920
tags question: http://stackoverflow.com/q/51155556
tags question: http://stackoverflow.com/q/51089821
tags question: http://stackoverflow.com/q/51015379
tags question: http://stackoverflow.com/q/51050948
tags question: http://stackoverflow.com/q/51107699
tags question: http://stackoverflow.com/q/51067226
tags question: http://stackoverflow.com/q/51083092

http://stackoverflow.com/q/51163112
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89309598
tagged with: python
downvote count: 6
has comment: http://stackoverflow.com/comment/89309838
has answer: http://stackoverflow.com/a/51163210
has answer: http://stackoverflow.com/a/69986809
type: Question
upvote count: 5
score: -1
has comment: http://stackoverflow.com/comment/89309560
has comment: http://stackoverflow.com/comment/89309633
has answer: http://stackoverflow.com/a/54189443
answer count: 3
has comment: http://stackoverflow.com/comment/89309641
tagged with: directory
has body: In the current working directory: import os print( os.listdir() ) will list the files and directories. However, I could also get a list of the files and directories in the current working directory of a Linux machine using the system command: import os print( os.system('ls') ) Which command is better: os.listdir() or os.system('ls') and why?
has title: which command is better: os.listdir() or os.system('ls') and WHY?
favorite count: 0

http://stackoverflow.com/comment/89223126
type: QuestionComment
comment on: http://stackoverflow.com/q/51064456
type: Comment
has text: see my answer cheers
score: 0

http://stackoverflow.com/a/51112558
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51112474
has comment: http://stackoverflow.com/comment/89278421
answers question: http://stackoverflow.com/q/51112474
type: Answer
upvote count: 4
has body: If you look at gitignore.io/python, you will find in the generated .gitignore file ### Python ### # Byte-compiled / optimized / DLL files __pycache__/ However, you won't find flask_session, not even in flask-common/.gitignore. The Flask documentation mentions: SESSION_FILE_DIR The directory where session files are stored. Default to use flask_session directory under current working directory. If that is something private to the user and the flask execution, then add to your .gitignore: /*_session/ But considering a Flask session stores secrets, the best practice would be to configure Flask to store its session outside the Git repository: that way, no risk to add by mistake anything, .gitignore or not.
downvote count: 0
score: 4

http://stackoverflow.com/q/51065287
accepted answer: http://stackoverflow.com/a/51066162
tagged with: opencv
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: image-processing
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/89120644
favorite count: 0
has body: I have two images one is the document image and the other image is the template image. I am performing OpenCV image subtraction between document image and template image. from matplotlib import pyplot as plt import numpy as np import cv2 template_img = cv2.imread('data_3/template.png') document_img = cv2.imread('data_3/document.png') result_img = cv2.subtract(template_img,document_img) plt.imshow(result_img) plt.title('Result Image') plt.show() The Output of the above Program: Here the background noise is Apt.no. OpenCV image subtraction has not performed well. One thing I notice why the image subtraction does not perform well because the quality of both images is not the same. Is there any way to remove the background noise that occurred during image subtraction?
has comment: http://stackoverflow.com/comment/89121474
has title: How to remove background noise while performing OpenCV Image subtraction?
tagged with: python
has answer: http://stackoverflow.com/a/51066162

http://stackoverflow.com/q/51110726
type: Question
tagged with: python
answer count: 1
tagged with: conditional-statements
tagged with: list
score: 0
has comment: http://stackoverflow.com/comment/89208627
has comment: http://stackoverflow.com/comment/89208542
has comment: http://stackoverflow.com/comment/89208495
has body: I'm trying to use a conditional comprehesion and the re.search function to find all the strings in DNA_list that start with 'ATG' and end with 'TAG' DNA_list = ['GTCTCTCGA', 'ATGCCTGAAGCATTCTAG', 'GCTGCCCACAAG', 'ATGACTGTAAAACCCTAG'] import re dna=[print(element)for element in DNA_list if re.search(r'(^ATG)(TAG$)',str(DNA_list))] But I don't get an output. What am I missing?
type: UnansweredQuestion
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/89208478
has comment: http://stackoverflow.com/comment/89208498
has answer: http://stackoverflow.com/a/51110823
has title: Using a conditional comprehesion and the re.search function to find all the strings in a list?

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/51090321
tags question: http://stackoverflow.com/q/51148821
tags question: http://stackoverflow.com/q/51164020
tags question: http://stackoverflow.com/q/51163941
type: Tag

http://stackoverflow.com/comment/89236748
type: Comment
comment on: http://stackoverflow.com/a/51125129
type: AnswerComment
score: 0
has text: IMO, the easiest thing to do right now for you is to delete the whole `D:\Python` folder and uninstall python itself, and reinstall a clean version of Python and/or Pycharm (if you have your own scripts in there, copy it elsewhere). Since (I don't know how, but you managed) the Python folder is very messed up, when only the essentials should be in the base folder. Note when you install the fresh versions: don't put everything in the Python folder, and perhaps have a read of http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv/.

http://stackoverflow.com/a/51144627
answers question: http://stackoverflow.com/q/51144561
accepted answer of: http://stackoverflow.com/q/51144561
has body: This is "argsort". I would do it just how you called the "traditional way", for what it's worth. The date strings will sort correctly using lexicographical order, assuming they are all in %Y-%m%-%d format. &gt;&gt;&gt; null = None &gt;&gt;&gt; mylist = [ ... { ... 'date': '2018-07-02', ... 'sequence': null ... }, ... ... { ... 'date': '2015-01-03', ... 'sequence': null ... }, ... { ... 'date': '2017-05-12', ... 'sequence': null ... }, ... ] &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; for i, d in enumerate(sorted(mylist, key=itemgetter('date')), start=1): ... d['sequence'] = i # mutate dicts in place ... &gt;&gt;&gt; mylist [{'date': '2018-07-02', 'sequence': 3}, {'date': '2015-01-03', 'sequence': 1}, {'date': '2017-05-12', 'sequence': 2}] numpy.argsort might give you a speedup if you have huge data and performance is critical, but don't bother otherwise.
type: AcceptedAnswer
upvote count: 3
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/comment/89127090
type: QuestionComment
comment on: http://stackoverflow.com/q/51068554
type: Comment
has text: when rocksmith.pyw try to open a file, sorry I'm not familiar with stackoverflow :/
score: 0

http://stackoverflow.com/a/51117677
downvote count: 0
has comment: http://stackoverflow.com/comment/89221579
accepted answer of: http://stackoverflow.com/q/51117661
has body: Use: df['date'].dt.year.value_counts().sort_index().plot.bar() Detail: print (df['date'].dt.year.value_counts().sort_index()) 2015 3 2016 5 2017 3 Name: date, dtype: int64 Explanation: First convert values to years by dt.year Count by value_counts with sort_index because default sorting in value_counts by top values Last plot by Series.plot.bar
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51117661
type: AcceptedAnswer

http://stackoverflow.com/a/51141753
score: 4
has comment: http://stackoverflow.com/comment/89268000
has body: It depends. Python 2 used ASCII as default encoding for source files. Python 3's default is UTF-8. So, if you intend to only support Python 3+ then you don't have to declare the utf-8 encoding as it is already the default. If you intend to support Python 2 as well and you have non-ASCII string literals then you should declare an encoding. If your text editor also needs a coding declaration (e.g., if your Unix locale is set to, say, Latin-1, but your code is UTF-8), Python's lenient syntax allows a single declaration to be used for both—e.g., # -*- coding: utf-8 -*- is recognized by both emacs and Python. Some official information: Python 3's docs about unicode support: https://docs.python.org/3/howto/unicode.html#python-s-unicode-support PEP 263 that introduced the encoding declaration syntax: https://www.python.org/dev/peps/pep-0263/ PEP 3210 about changing the default encoding from ASCII to UTF-8 starting from Python 3.0: https://www.python.org/dev/peps/pep-3120/
has comment: http://stackoverflow.com/comment/89267773
has comment: http://stackoverflow.com/comment/89267866
accepted answer of: http://stackoverflow.com/q/51141720
has comment: http://stackoverflow.com/comment/89267964
has comment: http://stackoverflow.com/comment/89268032
answers question: http://stackoverflow.com/q/51141720
upvote count: 4
has comment: http://stackoverflow.com/comment/89267726
has comment: http://stackoverflow.com/comment/89268026
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89267877
type: Answer

http://stackoverflow.com/a/51055941
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89103081
answers question: http://stackoverflow.com/q/51055696
type: Answer
has body: Just to make the difference between __repr__ and __str__ extra clear (: class Repr: def __repr__(self): return 'Here I am with __repr__' class Str: def __str__(self): return 'Here I am with __str__' print('Plain:') print(Repr(), Str()) print('In list:') print([Repr(), Str()]) > Plain: Here I am with __repr__ Here I am with __str__ In list: [Here I am with __repr__, &lt;__main__.Str object at 0x00000216BC2940F0&gt;]
score: 1

http://stackoverflow.com/comment/89249572
type: AnswerComment
comment on: http://stackoverflow.com/a/51126605
has text: Done, the edit should be visible soon. Ok like that?
type: Comment
score: 0

http://stackoverflow.com/comment/89175010
type: QuestionComment
comment on: http://stackoverflow.com/q/51091680
has text: @martineau, of course the mode can be enabled at runtime via ctypes or PyWin32, if that's what the OP wants.
score: 0
type: Comment

http://stackoverflow.com/comment/89217808
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51115442
has text: @dmitryro I'm not sure if I can login using OOOF with phone+special code(not password) and get token for authentification
score: 0

http://stackoverflow.com/comment/89182779
has text: @jezrael, sir, the Part-time: 165 from your answer is wrong. could you please have a look?
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51097276

http://stackoverflow.com/comment/92718616
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52836866
type: Comment
has text: Thanks for your detailed comment. I already did what you have said (reading more about how to use PyTorch, RL, ...) and started implementing from scratch.. . Because there wasn't any interest in this question I did not update it but your comment is a good summary!

http://stackoverflow.com/comment/89080096
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51044183
has text: I would advise rising the same error that you get so that you can see actual error message instead of "Could not set environment variable" in all cases. Or at least print/log/write it somewhere - it could save some time when debugging.
score: 0

http://stackoverflow.com/q/51071734
type: UnansweredQuestion
tagged with: python
tagged with: visual-studio
answer count: 0
type: Question
has body: I created a folder within a cloned repository named GlobalMacroPy. I added those files and created a test folder as well. I'm trying to run the module on my command line but turns out the folder wasn't created locally, the files are there. There's just not GlobalMacroPy folder. NOTE: It's not GlobalMacro I can't really understand why, did create a folder the wrong way?
score: 0
has comment: http://stackoverflow.com/comment/89133470
has title: Folder not showing up in my local directory but it is in my editor
has comment: http://stackoverflow.com/comment/89133307
has comment: http://stackoverflow.com/comment/89133319

http://stackoverflow.com/comment/89226565
score: 0
type: Comment
has text: The second bit of code you suggested, `(//div[.='All'])[2]`, worked perfectly. Strangely, `(//div[contains(., 'All')])[2]` selected "Bronze" instead of "All". The HTML containing "Bronze" is identical in structure to the code shown above for "Platinum". The `div` that contains "Bronze" (within a `span`) is located immediately below the `div` that contains "All".
comment on: http://stackoverflow.com/a/51120263
type: AnswerComment

http://stackoverflow.com/a/51131639
type: Answer
answers question: http://stackoverflow.com/q/51131461
type: AcceptedAnswer
score: 0
has body: The simplest solution is to use a loop (you need Jinja2 2.10 for assignments to work): - set_fact: my_sum: "{% set ns = namespace(sum=0) %}{% for e in var %}{% set ns.sum = ns.sum + e.value * e.oper %}{% endfor %}{{ ns.sum }}"
accepted answer of: http://stackoverflow.com/q/51131461

http://stackoverflow.com/a/51050187
score: 3
downvote count: 0
has body: &gt;&gt;&gt; pi=3.14159 &gt;&gt;&gt; print('{number:.2f}'.format(number=pi)) 3.14 &gt;&gt;&gt;
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51050146

http://stackoverflow.com/q/51092421
accepted answer: http://stackoverflow.com/a/51235894
downvote count: 0
answer count: 1
tagged with: keras
has body: Error from importing keras &gt;&gt;&gt; import keras /Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/daal/__init__.py:19: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/__init__.py", line 3, in &lt;module&gt; from . import utils File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/utils/__init__.py", line 6, in &lt;module&gt; from . import conv_utils File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/utils/conv_utils.py", line 9, in &lt;module&gt; from .. import backend as K File "/Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/keras/backend/__init__.py", line 98, in &lt;module&gt; raise ValueError('Invalid backend. Missing required entry : ' + e) ValueError: Invalid backend. Missing required entry : placeholder I installed mxnet correctly: &gt;&gt;&gt; import mxnet as mx /Users/ray_zhang/anaconda3/envs/idp3/lib/python3.6/site-packages/daal/__init__.py:19: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp &gt;&gt;&gt; a = mx.nd.ones((2,3)) &gt;&gt;&gt; b = a*2+1 &gt;&gt;&gt; b.asnumpy() array([[3., 3., 3.], [3., 3., 3.]], dtype=float32) My keras in pip (idp3) ❯ pip freeze | grep keras keras-mxnet==2.2.0 ~/.keras/keras.json (idp3) ❯ cat ~/.keras/keras.json { "floatx": "float32", "epsilon": 1e-07, "backend": "mxnet", "image_data_format": "channels_last" } It appears that my __init__.py in my keras site packages is not the same as the current github version's: My keras/backend/__init__.py # Import backend functions. if _BACKEND == 'cntk': sys.stderr.write('Using CNTK backend\n') from .cntk_backend import * elif _BACKEND == 'theano': sys.stderr.write('Using T…
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51235894
tagged with: pip
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: mxnet
has title: keras-mxnet not pulling properly from pip
type: Question

http://stackoverflow.com/comment/89312807
score: 0
comment on: http://stackoverflow.com/q/51164758
has text: You should at least post the full error and describe what about it you're having trouble fixing.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51022700
favorite count: 0
tagged with: python
score: -2
has title: Can't import my own file python, Flask pycharm
tagged with: pycharm
type: UnansweredQuestion
downvote count: 2
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/51022933
tagged with: flask
has comment: http://stackoverflow.com/comment/89058786
upvote count: 0
has body: Image of project structure: I have got this kind of files. I want to import write_block function from block.py in main.py through from block import *. It says name error and write_block is not defined.
answer count: 1

http://stackoverflow.com/comment/89099648
has text: `my_friends` is a dictionary. When you say `x in my_friends`, it will check if `x` is a key in the dictionary. Now `'Jose'` does exist as a key in `my_friends`, hence `'Jose' in my_friends` returns `True`. While `my_friends.items()` will return a list of tuples as explained in the previous comment.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51054262
type: Comment

http://stackoverflow.com/q/51058879
has comment: http://stackoverflow.com/comment/89108749
has comment: http://stackoverflow.com/comment/89113757
duplicate of: http://stackoverflow.com/q/47900844
has comment: http://stackoverflow.com/comment/89113946
has comment: http://stackoverflow.com/comment/89109460
score: 0
has title: Selenium screen shot generation using Python script for the remote web page - getting error as about:neterror
has comment: http://stackoverflow.com/comment/89113467
has body: Tools used : Geckodriver : 0.11.1 Mozilla Firefox : 52.8.0 Xvfb, python 2.7.5 Error Msg : Traceback (most recent call last): File "/apps/app/wordpress/take-screenshot-2.py", line 37, in &lt;module&gt; browser.get(feed_item_url) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 326, in get self.execute(Command.GET, {'url': url}) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) WebDriverException: Message: Reached error page: about:neterror?e=inadequateSecurityError&amp;u=https%3A//www.sysadmit.com/2018/06/veeam-backup-exclusiones-antivirus-Windows-Defender-PowerShell.html&amp;c=UTF-8&amp;f=regular&amp;d=The%20website%20tried%20to%20negotiate%20an%20inadequate%20level%20of%20security.
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: python
has comment: http://stackoverflow.com/comment/89348494
linked to: http://stackoverflow.com/q/47900844
type: Question

http://stackoverflow.com/comment/89190424
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51093056
type: Comment
has text: What is "AdjointLayout" ? It's not any class that's part of Bokeh

http://stackoverflow.com/comment/89285003
has text: Why do you want to do this?
comment on: http://stackoverflow.com/q/51150676
type: Comment
type: QuestionComment
score: 3

image-processing
tags question: http://stackoverflow.com/q/51128826
tags question: http://stackoverflow.com/q/51094687
tags question: http://stackoverflow.com/q/51095013
tags question: http://stackoverflow.com/q/51127257
tags question: http://stackoverflow.com/q/51050047
tags question: http://stackoverflow.com/q/51077990
tags question: http://stackoverflow.com/q/51073913
tags question: http://stackoverflow.com/q/51065287
tags question: http://stackoverflow.com/q/51020105
tags question: http://stackoverflow.com/q/51164645
tags question: http://stackoverflow.com/q/51082703
tags question: http://stackoverflow.com/q/51117956
tags question: http://stackoverflow.com/q/51057793
tags question: http://stackoverflow.com/q/51050784
tags question: http://stackoverflow.com/q/51023214
tags question: http://stackoverflow.com/q/51124738
tags question: http://stackoverflow.com/q/51084289
tags question: http://stackoverflow.com/q/51121978
tags question: http://stackoverflow.com/q/51065823
tags question: http://stackoverflow.com/q/51119801
tags question: http://stackoverflow.com/q/51034209
type: Tag
tags question: http://stackoverflow.com/q/51018135
tags question: http://stackoverflow.com/q/51039788
tags question: http://stackoverflow.com/q/51092720
tags question: http://stackoverflow.com/q/51028456
tags question: http://stackoverflow.com/q/51014439
tags question: http://stackoverflow.com/q/51084825
tags question: http://stackoverflow.com/q/51022577
tag name: image-processing
tags question: http://stackoverflow.com/q/51039275
tags question: http://stackoverflow.com/q/51056148
tags question: http://stackoverflow.com/q/51143340
tags question: http://stackoverflow.com/q/51097659

http://stackoverflow.com/comment/89049974
comment on: http://stackoverflow.com/q/51025716
score: 0
type: Comment
has text: You've not quite posted enough code for this to be a runnable example. Flush it out so that it runs with some sample data so we can see the behaviour you are seeing.
type: QuestionComment

http://stackoverflow.com/q/51059053
has title: Selecting rows where column is not null and equal to a (string) value
type: UnansweredQuestion
tagged with: python
has body: So basically I want select all rows where Col A is equal to the string 'hey'. My problem is that Col A can contain null/nan's therefore I get a TypeError: invalid type comparison. When executing: df.loc[df['A'] == 'hey'] I then made another condition: df.loc[df['A'].notnull() &amp; (df['A'] == 'hey')] Here i get the same error. I made a hack where I change all the null values in Col A to '' but thats not beautiful is there anyway nice to first choose all the rows where Col A isn't null and then from there all the ones who are equal to 'hey'?
has comment: http://stackoverflow.com/comment/89108630
tagged with: dataframe
score: -1
tagged with: selection
type: Question
favorite count: 0
has answer: http://stackoverflow.com/a/51059135
tagged with: pandas-loc
answer count: 3
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/51059664
upvote count: 0
has answer: http://stackoverflow.com/a/51059103

http://stackoverflow.com/comment/132417155
comment on: http://stackoverflow.com/q/51019965
has text: Does this answer your question? [C function called from Python via ctypes returns incorrect value](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51131461
accepted answer: http://stackoverflow.com/a/51131639
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: jinja2
has body: I am working on ansible 2.5, python 2.7. I have to execute a calculation on a dynamic json variable. The variable is dynamic; it can contain from 1 to 1000 objects: example: var: [ { "name": "object1", "value": 1, "oper": 2 }, { "name": "objectN", "value": 40, "oper": 8 } ] The operation I have to execute is quite basic: result = (var.object_1.value * var.object_1.oper) + (var.object_2.value * var.object_2.oper) + (var.object_N.value * var.object_N.oper) ... How to deal with this operation? Is there a jinja function the work with json structure or do I have to create a custom "ansible filter" to work with python functions? Thanks all for your advises!
type: Question
has title: ansible jinja or python; calculation on a dynamic json structure
score: 0
tagged with: ansible
answer count: 1
has answer: http://stackoverflow.com/a/51131639
tagged with: python

spell-checking
tags question: http://stackoverflow.com/q/51057842
tags question: http://stackoverflow.com/q/51052785
type: Tag
tag name: spell-checking

http://stackoverflow.com/comment/89225765
type: Comment
type: QuestionComment
score: 0
has text: @I'LI Nice, very cool! [Too wide now ](https://imgur.com/TY6HEv3)
comment on: http://stackoverflow.com/q/51120072

http://stackoverflow.com/q/51112867
favorite count: 0
has answer: http://stackoverflow.com/a/51112901
has body: import random fruits = ['Apple','Mango','Banana','Grapes','Guava'] random.seed(500) low =0 high = len(fruits) random_fruits = [fruits[random.randint(low,high)] for i in range(1000)] This is my code and following is the error what I am getting? IndexError: list index out of range
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: Index error when drawing elements by index from list using random.randint()'s
upvote count: 1
has answer: http://stackoverflow.com/a/51113782
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89212464
accepted answer: http://stackoverflow.com/a/51113782
has comment: http://stackoverflow.com/comment/89213965
score: 0
answer count: 2
tagged with: random
possible better answer: http://stackoverflow.com/a/51112901

http://stackoverflow.com/comment/89254240
comment on: http://stackoverflow.com/q/51134668
has text: Your data set is not very clear. Can you please format it.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/89084737
type: Comment
has text: Thank you very much
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51044771

http://stackoverflow.com/comment/89137991
has text: You could call `nunique()` instead of `size()` in your `groupby`, however I believe this would bug out in a situation like @ALollz describes.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51073813
type: Comment

http://stackoverflow.com/a/51077562
has body: No. Decorator is basically a function that takes another function as an argument and returns "decorated" function. @decorator is just a syntactic sugar.
upvote count: 2
answers question: http://stackoverflow.com/q/51077539
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/51045526
type: Answer
has comment: http://stackoverflow.com/comment/89083476
has comment: http://stackoverflow.com/comment/89083431
has comment: http://stackoverflow.com/comment/89083209
answers question: http://stackoverflow.com/q/51045382
has comment: http://stackoverflow.com/comment/89082655
has comment: http://stackoverflow.com/comment/89082335
has comment: http://stackoverflow.com/comment/89082406
has comment: http://stackoverflow.com/comment/89084893
has comment: http://stackoverflow.com/comment/89083251
has comment: http://stackoverflow.com/comment/89082726
score: 0
has comment: http://stackoverflow.com/comment/89103625
has body: You can drastically simplify your file collection code by using os.walk() to do the collecting; you could use fnmatch.filter() to filter down the filenames to only *.shp files: import os import fnmatch def new_file_paths(rootdir): for dirpath, dirnames, filenames in os.walk(rootdir): if dirpath == rootdir: continue. # ignore files in the root yield dirpath, [os.path.join(dirpath, fname) for fname in fnmatch.filter(filenames, '*.shp')] This is a generator function that yields a list of files per directory, so you can print information per directory to give to your users. ‘os.walk()` will traverse all subdirectories, at any depth, starting at the root. If this is an issue, and further nested directories are to be ignored, then using glob.iglob() with grouping on the directory name would be simpler: from glob import iglob from itertools import groupby def new_file_paths(rootdir): # only .shp files in direct subfolders results = igblob(os.path.join(rootdir, '*', '*.shp')) return ((d, list(p)) for d, p in groupby(results, key=os.path.dirname)) When you loop over the generator object, you can take the relative path name of each file in a directory, and check if there is a corresponding file in the other location: rootdir_new = r'C:\Users\user\Desktop\a' rootdir_old = r'C:\Users\user\Desktop\k' for directory, paths in new_file_paths(rootdir_new)): if not paths: print('{} is empty, no new files found'.format(directory)) continue for path in paths: relative_path = os.path.relpath(path, rootdir_new) old_path = os.path.join(rootdir_old, relative_path) if not os.path.exists(old_path): # no corresponding old file print('No matching previous version of {}' 'found, skipping'.format(relative_path)) continue # compare `path` with `old_path` As for your comparison code, you can make use of the fact that the dict.items() dictionary view object is a set, so you can use set operations on those directly without having to call set() on them, and sets natively support producing differences…
has comment: http://stackoverflow.com/comment/89122946

http://stackoverflow.com/a/51436313
answers question: http://stackoverflow.com/q/51149185
accepted answer of: http://stackoverflow.com/q/51149185
type: Answer
upvote count: 1
score: 1
has body: I once again deleted all libraries and reinstalled them and also ran the code in Chrome. It is working fine now.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51106441
has answer: http://stackoverflow.com/a/51106481
has body: I need to merge two data frames. In df_A the key is an int. In df_B the key is a string ending in .0 e.g. '10003.0'. I would like to convert the string in df_B to an int for merging. Is there a better way than mapping twice as seen below? df_B['key'].map(float).map(int) The syntax seems awkward to me. Is there a better solution?
tagged with: python
type: AnsweredQuestion
has title: Is there a better method than mapping str to float then mapping to int?
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51106481
has comment: http://stackoverflow.com/comment/89199918
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89173337
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51084666
has text: I wrote that as *once instance* of the error, and I also wrote that there is another instance of the error. I assumed that whatever fixed one would fix the other, but that turned out to be not so. I appreciate you help. Can you please look at the edited question? Thanks.
type: AnswerComment

http://stackoverflow.com/a/51148817
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51147751
has body: Thanks guys I solved the problem by removing the file 5,6,7 and made migration and it worked
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51147751

http://stackoverflow.com/a/51145436
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: My answer is a translation of this example: http://doc.qt.io/qt-5/qtwidgets-mainwindows-dockwidgets-example.html, so future readers can use it to make a translation from the C++ code to Python. from PyQt4 import QtCore, QtGui class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.textEdit = QtGui.QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createStatusBar() self.createDockWindows() self.setWindowTitle("Dock Widgets") self.newLetter() self.setUnifiedTitleAndToolBarOnMac(True) def newLetter(self): self.textEdit.clear() cursor = QtGui.QTextCursor(self.textEdit.textCursor()) cursor.movePosition(QtGui.QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) textFormat = QtGui.QTextCharFormat() boldFormat = QtGui.QTextCharFormat() boldFormat.setFontWeight(QtGui.QFont.Bold) italicFormat = QtGui.QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QtGui.QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(QtCore.Qt.AlignRight) cursor.insertTable(1, 1, tableFormat) cursor.insertText("The Firm", boldFormat) cursor.insertBlock() cursor.insertText("321 City Street", textFormat) cursor.insertBlock() cursor.insertText("Industry Park") cursor.insertBlock() cursor.insertText("Some Country") cursor.setPosition(topFrame.lastPosition()) cursor.insertText(QtCore.QDate.currentDate().toString("d MMMM yyyy"), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Dear ", textFormat) cursor.insertText("NAME", italicFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Yours sincerely,", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("The Boss", textFormat) cursor.insertBlock() cursor.insertText("ADDRESS", italicFormat) def print_(self): document = sel…
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51144569
accepted answer of: http://stackoverflow.com/q/51144569

http://stackoverflow.com/a/75364419
score: 0
type: Answer
has body: Probably you are trying to use jpg or other type of file, like jpeg..., check this or change the type of file to png.
answers question: http://stackoverflow.com/q/51106995

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/51165305

http://stackoverflow.com/a/51081189
type: Answer
has comment: http://stackoverflow.com/comment/89151806
answers question: http://stackoverflow.com/q/51080451
downvote count: 1
upvote count: 0
score: -1
has body: import os files = os.listdir(r'C:/testdeletefolder') fileslist=[] for file in files: print file fileslist.append(file) for i in range(0,2): os.remove(fileslist[i]) But ensure that you if condition to not to delete the python file which has code.this will delete 2 files you can change the counter in range

http://stackoverflow.com/comment/89209816
comment on: http://stackoverflow.com/q/51111398
type: QuestionComment
has text: `df.head()` only shows the first 5 rows just `print(df)`
type: Comment
score: 0

http://stackoverflow.com/q/51118551
score: 1
upvote count: 1
type: Question
tagged with: python-imaging-library
tagged with: affinetransform
has comment: http://stackoverflow.com/comment/89223329
has body: I was thinking, that I could shear an image around center by first translating it, then shearing, then translating back. def translate(im: Image.Image, tx: float=0, ty: float=0): return im.transform(im.size, Image.AFFINE, (1, 0, tx, 0, 1, ty)) def shear(im: Image.Image, cx=0, cy=0): center = [xy/2 for xy in im.size] im = translate(im, center[0], center[1]) im = im.transform(im.size, Image.AFFINE, (1, cx, 0, cy, 1, 0)) im = translate(im, -center[0], -center[1]) return im Unfortunately, translation looses information and I get the following
downvote count: 0
has comment: http://stackoverflow.com/comment/89236294
has title: How to shear image around a center in PIL?
favorite count: 0
linked to: http://stackoverflow.com/q/11142851
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89223672
answer count: 0

http://stackoverflow.com/a/51106514
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51106131
type: AcceptedAnswer
has body: One of the most important details of working with sparse matrices is to never use dense matrix intermediates! It seems that the memory problem occurs when you call toarray(). This is because you are converting a scipy.sparse matrix into a dense numpy.array. Instead of using the numpy module for calculating the eigenvalues on the dense matrix, try using the scipy.sparse.linalg function eigs to find the eigenvalues of your sparse matrix.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51106131

partial-application
type: Tag
tag name: partial-application
tags question: http://stackoverflow.com/q/51063250

http://stackoverflow.com/q/51015563
has answer: http://stackoverflow.com/a/51016946
type: Question
score: 3
tagged with: pairwise
upvote count: 3
has body: I have a 1D vector having N dimension in TensorFlow, how to construct sum of a pairwise squared difference? Example Input Vector [1,2,3] Output 6 Computed As (1-2)^2+(1-3)^2+(2-3)^2. if I have input as an N-dim vector l, the output should be sigma_{i,j}((l_i-l_j)^2). Added question: if I have a 2d matrix and want to perform the same process for each row of the matrix, and then average the results from all the rows, how can I do it? Many thanks!
has title: How to construct square of pairwise difference from a vector in tensorflow?
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51016946
type: AnsweredQuestion
downvote count: 0
tagged with: tensor
tagged with: vectorization
tagged with: tensorflow

http://stackoverflow.com/q/51078117
score: 1
tagged with: timestamp
type: Question
has answer: http://stackoverflow.com/a/51078201
accepted answer: http://stackoverflow.com/a/51078201
tagged with: dataframe
has title: How to make day-hour count on pandas dataframe
tagged with: pandas
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/51036672
favorite count: 0
has comment: http://stackoverflow.com/comment/89145114
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89145208
downvote count: 0
has body: I did multi-day observation, one customer can be observed in more few days, Here's my data, customer_id value timestamp 1 1000 2018-05-28 03:40:00.000 1 1450 2018-05-28 04:40:01.000 1 1040 2018-05-28 05:40:00.000 1 1500 2018-05-29 02:40:00.000 1 1090 2018-05-29 04:40:00.000 3 1060 2018-05-18 03:40:00.000 3 1040 2018-05-18 05:40:00.000 3 1520 2018-05-19 03:40:00.000 3 1490 2018-05-19 04:40:00.000 Based on previous question How do I building dt.hour in 2 days the first customer appear is 2018-05-28 03:40:00.000 and labelled as Day1 - 3, but for another purpose is should be Day1 - 0, so the output would be customer_id value timestamp hour 1 1000 2018-05-28 03:40:00.000 Day1 - 0 1 1450 2018-05-28 04:40:01.000 Day1 - 1 1 1040 2018-05-28 05:40:00.000 Day1 - 2 1 1500 2018-05-29 02:40:00.000 Day1 - 23 1 1090 2018-05-29 04:40:00.000 Day2 - 1 3 1060 2018-05-18 03:40:00.000 Day1 - 0 3 1040 2018-05-18 05:40:00.000 Day1 - 2 3 1520 2018-05-19 03:40:00.000 Day2 - 0 3 1490 2018-05-19 04:40:00.000 Day2 - 1

dataframe
tags question: http://stackoverflow.com/q/51123230
tags question: http://stackoverflow.com/q/51109245
tags question: http://stackoverflow.com/q/51053301
tags question: http://stackoverflow.com/q/51071758
tags question: http://stackoverflow.com/q/51028364
tags question: http://stackoverflow.com/q/51062526
tags question: http://stackoverflow.com/q/51154350
tags question: http://stackoverflow.com/q/51092336
tags question: http://stackoverflow.com/q/51045848
tags question: http://stackoverflow.com/q/51119315
tags question: http://stackoverflow.com/q/51043841
tags question: http://stackoverflow.com/q/51080943
tags question: http://stackoverflow.com/q/51081568
tags question: http://stackoverflow.com/q/51165370
tags question: http://stackoverflow.com/q/51091931
tags question: http://stackoverflow.com/q/51039441
tags question: http://stackoverflow.com/q/51036402
tags question: http://stackoverflow.com/q/51020192
tags question: http://stackoverflow.com/q/51129662
tags question: http://stackoverflow.com/q/51071927
tags question: http://stackoverflow.com/q/51049414
tags question: http://stackoverflow.com/q/51102883
tags question: http://stackoverflow.com/q/51145940
tags question: http://stackoverflow.com/q/51107284
tags question: http://stackoverflow.com/q/51013520
tags question: http://stackoverflow.com/q/51012614
tags question: http://stackoverflow.com/q/51026581
tags question: http://stackoverflow.com/q/51036644
tags question: http://stackoverflow.com/q/51116473
tags question: http://stackoverflow.com/q/51094273
tags question: http://stackoverflow.com/q/51121097
tags question: http://stackoverflow.com/q/51064346
tags question: http://stackoverflow.com/q/51030205
tags question: http://stackoverflow.com/q/51133424
tags question: http://stackoverflow.com/q/51161506
tags question: http://stackoverflow.com/q/51089318
tags question: http://stackoverflow.com/q/51097981
tags question: http://stackoverflow.com/q/51018104
tags question: http://stackoverflow.com/q/51049326
tags question: http://stackoverflow.com/q/51031857
tags question: http://stackoverflow.com/q/51120293
tags question: http://stackoverflow.com/q/51137594
tags question: http://stackoverflow.com/q/51015855
tags question: http://stackoverflow.com/q/51087854
tags question: http://stackoverflow.com/q/51088119
tags question: http://stackoverflow.com/q/51015583
tags question: http://stackoverflow.com/q/51028703
tags question: http://stackoverflow.com/q/51139825
tags question: http://stackoverflow.com/q/51020928
tags question: http://stackoverflow.com/q/51051834
tags question: http://stackoverflow.com/q/51060996
tags question: http://stackoverflow.com/q/51150011
tags question: http://stackoverflow.com/q/51087484
tags question: http://stackoverflow.com/q/51141875
tags question: http://stackoverflow.com/q/51049985
tags question: http://stackoverflow.com/q/51128396
tags question: http://stackoverflow.com/q/51064157
tags question: http://stackoverflow.com/q/51070781
tags question: http://stackoverflow.com/q/51054844
tags question: http://stackoverflow.com/q/51129987
tags question: http://stackoverflow.com/q/51107460
tags question: http://stackoverflow.com/q/51031680
tags question: http://stackoverflow.com/q/51077458
tags question: http://stackoverflow.com/q/51079621
tags question: http://stackoverflow.com/q/51053644
tags question: http://stackoverflow.com/q/51100406
tags question: http://stackoverflow.com/q/51052506
tags question: http://stackoverflow.com/q/51093175
tags question: http://stackoverflow.com/q/51059190
tags question: http://stackoverflow.com/q/51099576
tags question: http://stackoverflow.com/q/51123926
tags question: http://stackoverflow.com/q/51018739
tags question: http://stackoverflow.com/q/51157284
tags question: http://stackoverflow.com/q/51016106
tags question: http://stackoverflow.com/q/51117844
tags question: http://stackoverflow.com/q/51049897
tags question: http://stackoverflow.com/q/51046983
tags question: http://stackoverflow.com/q/51129229
tags question: http://stackoverflow.com/q/51023642
tags question: http://stackoverflow.com/q/51054497

http://stackoverflow.com/comment/89126978
type: AnswerComment
score: 0
type: Comment
has text: Oh damn, You might be actually right. if you check the `new_list = resp.json()['threads']`that would print out the whole json file while I add into the `old_list` only the seoTitle.. Should that matter?
comment on: http://stackoverflow.com/a/51068419

http://stackoverflow.com/q/51099197
score: 0
has comment: http://stackoverflow.com/comment/89186099
has comment: http://stackoverflow.com/comment/89186002
has comment: http://stackoverflow.com/comment/89186081
type: Question
has comment: http://stackoverflow.com/comment/89186320
has comment: http://stackoverflow.com/comment/89186060
has comment: http://stackoverflow.com/comment/89186208
has comment: http://stackoverflow.com/comment/89186127
has answer: http://stackoverflow.com/a/51099616
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89186683
has answer: http://stackoverflow.com/a/51099470
tagged with: python-3.x
has body: I have a very large dataframe which is like the first four column of this dataframe. I am trying to generate the 5th i.e. DataType column which corresponds to the datatype of the "Word" column. Note that datatype corresponds to "WEEKDAY", "DATE" etc. not the python datatype. Page LineNum Word Line DataType 1 1 Today Today is 5th Sept 2015 NULL 1 1 is Today is 5th Sept 2015 NULL 1 1 5th Today is 5th Sept 2015 DATE 1 1 Sept Today is 5th Sept 2015 DATE 1 1 2015 Today is 5th Sept 2015 DATE ... 1 4 Sunday Sunday will be Sept 8th WEEKDAY 1 4 will Sunday will be Sept 8th NULL 1 4 be Sunday will be Sept 8th NULL 1 4 Sept Sunday will be Sept 8th DATE 1 4 8th Sunday will be Sept 8th DATE I have separate functions which extracts list of all sub-string of a particular datatype from a string. Say isit_date returns ['5th Sept 2015'] for Page 1 Line 1. To get the DataType column I am using a groupby and lambda function. There are many pages and many lines. I am trying this with the following code: file_dataframe['DataType'] = 'NULL' for name, groups in file_dataframe.groupby(['Page', 'LineNum']): list_of_dates = isit_date(str(groups['Line'][0])) groups['DataType'] = groups['Word'].apply(lambda x: "DATE" if x in list_of_dates else 'NULL') I can see many faults in this. The groups won't write into the initial dataframe... but however am getting error in this code. Can someone suggest the correct and efficient approach. I am trying to use groupby because- isit_date() function take some time to execute and I don't want to repeat that for every group since the Line for every group is same. I am using python 3 and pandas. Please comment if there is something more I need to explain about my question. Here is the isit_date code import datetime import datefinder as dt from dateutil.parser import parse from commonregex import CommonRegex class FindDates: def __init__(self): pass def isit_date(self, s): commonregex_object = CommonRegex(s) dates_list = commonregex_object.dates additional_date…
type: UnansweredQuestion
has title: Making separate column in a dataframe after groupby function iteration
has comment: http://stackoverflow.com/comment/89186215
has comment: http://stackoverflow.com/comment/89186067
has comment: http://stackoverflow.com/comment/89186216
tagged with: python
has answer: http://stackoverflow.com/a/51099657
has comment: http://stackoverflow.com/comment/89187160

http://stackoverflow.com/comment/89123762
score: 0
type: Comment
type: QuestionComment
has text: What is `s`? Do you mean `enumerate(d)`?
comment on: http://stackoverflow.com/q/51066851

http://stackoverflow.com/a/76269459
score: 0
has body: Here's one I personally use that works with Java 17. FROM eclipse-temurin:17-jre-alpine # Install Python and pip, can modify with a specific version of python too RUN apk add --no-cache python3 py3-pip # Add your own commands, you can add python packages with pip install Skipped the security best practices to keep this short.
type: Answer
answers question: http://stackoverflow.com/q/51121875

http://stackoverflow.com/a/51036119
has comment: http://stackoverflow.com/comment/89100246
type: Answer
has comment: http://stackoverflow.com/comment/89089705
score: 0
has comment: http://stackoverflow.com/comment/89099339
has body: The solution is to use the public REST API for the site. If the web site does not provide a REST API for interacting with it you should not be surprised that your attempt at simulating a human is difficult. Web scraping is generally only possible for pages that do not require authentication or utilize the standard HTTP 401 status response to tell the client that it should prompt the user to respond with the correct credentials. If the site is using a different mechanism, most likely based on AJAX, then the solution is going to be specific to that web site or other sites using the same mechanism. Which means that no one can answer your question since you did not tell us which web site you are interacting with.
has comment: http://stackoverflow.com/comment/89100410
answers question: http://stackoverflow.com/q/51019623

http://stackoverflow.com/comment/89148141
type: QuestionComment
has text: @andrew input: Pratap pandey age 25 student, and if it founds keyword age then print line
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51079333

http://stackoverflow.com/a/51104883
downvote count: 0
has body: This would be enough: import string var = 95 ## chr(95)='_' if chr(var) not in string.ascii_letters+' ': print 'worked' ## not an alphabetic nor space character EDIT: added space to the list (ascii_letters is a string containing... letters)
type: Answer
answers question: http://stackoverflow.com/q/51104530
upvote count: 2
score: 2

http://stackoverflow.com/a/51081190
accepted answer of: http://stackoverflow.com/q/51081084
answers question: http://stackoverflow.com/q/51081084
score: 4
type: AcceptedAnswer
has body: Using only once with advanced-indexing - sidx = np.argsort(x, axis=1) # Store shape info m,n = x.shape # Initialize output array out = np.empty((m,n),dtype=int) # Use sidx as column indices, while a range array for the row indices # to select one element per row. Since sidx is a 2D array of indices # we need to use a 2D extended range array for the row indices out[np.arange(m)[:,None], sidx] = np.arange(n) For getting the ranks along each column, simply change the indexing step to use sidx as the row indices, while the range array for the column indices automatically broadcasts. Also, the values to be assigned are to be extended to 2D for the values to be broadcasted before assignments : sidx = np.argsort(x, axis=0) out[sidx, np.arange(n)] = np.arange(m)[:,None] Timings on 5k x 5k array To see the improvements with the proposed method, since both are using the result of the first argsort, let's pre-compute it and then time rest of the steps - In [248]: x = np.random.rand(5000,5000) In [249]: axis = 1 In [250]: sidx = np.argsort(x, axis=1) In [251]: %timeit np.argsort(sidx, axis=axis) 1 loop, best of 3: 1.31 s per loop In [252]: %%timeit ...: m,n = x.shape ...: out = np.empty((m,n),dtype=int) ...: out[np.arange(m)[:,None], sidx] = np.arange(n) 10 loops, best of 3: 156 ms per loop Seeing a speedup of 8x+ with the proposed one for such an array.
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/51015217
has answer: http://stackoverflow.com/a/51015607
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89023694
accepted answer: http://stackoverflow.com/a/51015607
linked to: http://stackoverflow.com/q/24250832
tagged with: python
has title: groupby to get the average, using dynamic condition
type: AnsweredQuestion
has body: I have been searching about groupby using conditions and found many posts about that. This one for example: Pandas: conditional group-specific computations However, I couldn't find any where the condition is applied over itself. In my case I'd like to get the average (or count or any other formula for that matter) but the thing that I couldn't find is to filter the dataset over a dynamic condition. To illustrate this, this is the summarized dataset: ID | Seq | Total 1 | 1 | 1 1 | 2 | 2 1 | 3 | 3 2 | 1 | 1 2 | 2 | 2 2 | 3 | 1 If I want to get the mean grouped by ID, but with the additional condition that for each record within the group, only those where the Seq is smaller must be computed. This should be the result ID | Seq | Total | x 1 | 1 | 1 | 1 &lt;-- mean of 1 1 | 2 | 2 | 1.5 &lt;-- mean of 1 and 2 1 | 3 | 3 | 2 &lt;-- mean of 1,2 and 3 2 | 1 | 1 | 1 &lt;-- mean of 1 2 | 2 | 2 | 1.5 &lt;-- mean of 1 and 2 2 | 3 | 1 | 1.33 &lt; mean of 1, 2 and 1 Any help will be appreciated!
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89023454

http://stackoverflow.com/comment/89274453
type: AnswerComment
has text: Thanks, interesting solution. But yea, that numpy will blow up with the actual data
comment on: http://stackoverflow.com/a/51139530
type: Comment
score: 0

http://stackoverflow.com/comment/89299683
has text: I think it was the timing. It seems to be working now. I had to add `time.sleep(60)` after the the first Request, to wait for the data to download, before the next Request.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51139009

http://stackoverflow.com/comment/89072390
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51037937
has text: In your case the eparameters are slightly different. Your payload should look like: [click the link](https://www.dropbox.com/s/y0udggzu2u0pdm3/login%20payload.txt?dl=0).

rename
tags question: http://stackoverflow.com/q/51013938
type: Tag
tags question: http://stackoverflow.com/q/51138165
tag name: rename

http://stackoverflow.com/q/51076123
possible better answer: http://stackoverflow.com/a/60823397
type: AnsweredQuestion
score: 1
has title: Django REST Framework generics.RetrieveUpdateDestroyAPIView return all records instead of one
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51076150
tagged with: django-rest-framework
tagged with: drf-nested-routers
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51076150
tagged with: python-3.x
has answer: http://stackoverflow.com/a/60823397
tagged with: django
upvote count: 1
tagged with: python
has body: I'm new to DRF and trying to build a rest API, I have set up my models, URLs, views, and serializers as: model.py: services = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class DeploymentOnUserModel(models.Model): deployment_name = models.CharField(max_length=256, ) credentials = models.TextField(blank=False) project_name = models.CharField(max_length=150, blank=False) project_id = models.CharField(max_length=150, blank=True) cluster_name = models.CharField(max_length=256, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=150, choices=services) configuration = models.TextField() routing = models.TextField() def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing and not self.configuration: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) From urls.py: from django.urls import path, include # from .routers import router from . import apiview app_name = 'deployments' urlpatterns = [ # path('', include(router.urls), name='deployments'), path('deployments/', apiview.DeploymentsList.as_view(), name='deployment-list'), path('deployments/&lt;int:pk&gt;/', apiview.DeploymentDetail.as_view(), name='deployment_detail') ] From apiview.py: class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView): def retrieve(self, request, *args, **kwargs): pk = self.kwargs.get('pk') return Response(DeploymentOnUserModel.objects.get(pk=kwargs['pk'])) From serializers.py: class DeploymentOnUserSerializer(serializers.ModelSerializer): class Meta: model = DeploymentOnUserModel fields = '__all__' When I try access: http://127.0.0.1:8000/api/v1/deployments/?pk=1/ it should return a single object of id=1 but it returns all objects.

http://stackoverflow.com/comment/89175373
score: 0
type: Comment
type: QuestionComment
has text: Why you do reduce_mean() and sqrt(). It looks like you should optimize (minimize) sum of squared differences tf.reduce_sum(tf.squared_difference(...)). I would also compare with MLE to see the baseline.
comment on: http://stackoverflow.com/q/51088830

http://stackoverflow.com/comment/89110535
type: QuestionComment
comment on: http://stackoverflow.com/q/51059862
has text: I have updated the question hope the requirement is clear.
score: 0
type: Comment

http://stackoverflow.com/q/51043841
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/89079395
has body: I have a data frame like this and I would like to multiply the rows by its references value in another data frame using pandas. After that I would like to add all products from those rows and store it in a column called Pro_Sum. I know Python doesn't pass things by reference, but I can name-bind in here so I'm trying to create a dictionary to multiply the values according to its name, but I haven't been successful. df = pd.read_excel (C:/"dummy") d = {"C1": 2, "C2": 5,"C3":4, "C4":1} df.mul(pd.Series(d), axis=1) prod = d.keys() df[prod] = df[prod].mul(pd.Series(d), axis=1)[prod] to_sum_t = list(df) #.sum ignores the none numeric values. df['Pro_sum'] = df[to_sum_t].sum(axis=1) Input ID AU HP Name1 Value1 CHC1 Name2 Value2 CHC2 Name3 Value3 CHC3 1 4 3 C1 10 100 0 0 0 0 0 0 2 6 2 C2 20 95 C1 6 5 0 0 0 3 2 7 C3 4 40 C4 6 60 0 0 0 4 8 9 C1 8 100 0 0 0 0 0 0 5 2 6 C1 6 10 C2 15 86 C4 1 4 Reference column Names Values C1 2 C2 5 C3 4 C4 1 Example row 5 Pro_Sum = 6*2 + 15*5 + 1*1 = 88 Minimal Output ID AU HP Name1 Value1 CHC1 Name2 Value2 CHC2 Name3 Value3 CHC3 Pro_Sum 1 4 3 C1 10 100 0 0 0 0 0 0 20 2 6 2 C2 20 95 C1 6 5 0 0 0 112 5 2 6 C1 6 10 C2 15 86 C4 1 4 88
linked to: http://stackoverflow.com/q/51025752
upvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: reference
tagged with: python
has answer: http://stackoverflow.com/a/51044297
has comment: http://stackoverflow.com/comment/89079076
accepted answer: http://stackoverflow.com/a/51044297
has title: Using dictionaries to multiply columns like by reference Pandas
type: AnsweredQuestion
score: 2
tagged with: name-binding
downvote count: 0

http://stackoverflow.com/a/51087125
has comment: http://stackoverflow.com/comment/89163011
answers question: http://stackoverflow.com/q/51086772
has comment: http://stackoverflow.com/comment/89162966
type: Answer
has body: It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly. Otherwise, in Python 3, input() always returns a string. So if the user enters "3@!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)). If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses). Because these methods operate on characters, you need to use a for loop: YourName ="" while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName): #You can pass a string as a prompt for the user here name = input("please enter name") print (YourName) However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89163461
has comment: http://stackoverflow.com/comment/89163395
has comment: http://stackoverflow.com/comment/89162887
upvote count: 1

http://stackoverflow.com/q/51142026
answer count: 2
upvote count: 0
score: -2
tagged with: arrays
has answer: http://stackoverflow.com/a/51142172
favorite count: 0
has answer: http://stackoverflow.com/a/51142078
has comment: http://stackoverflow.com/comment/89268162
tagged with: python
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89268210
has title: Multiply two arrays and find the summation of the result
has body: I have two arrays: x = [[1, 2, 3]] y = [[0, 1, 5], [2, 4, 6],[4, 5, 6]] how to multiply all the elements in y array by each element in x array and find the summation of the result as below: 1*0 + 1*1+ 1*5 2*0 + 2*1+ 2*5 3*0 + 3*1+ 3*5 1*2 + 1*4+ 1*6 2*2 + 2*4+ 2*6 3*2 + 3*4+ 3*6 1*4 + 1*5+ 1*6 2*4 + 2*5+ 2*6 3*4 + 3*5+ 3*6
type: Question

http://stackoverflow.com/comment/89068746
has text: What's the size of your file?
type: QuestionComment
comment on: http://stackoverflow.com/q/51038626
type: Comment
score: 0

http://stackoverflow.com/q/51160647
has comment: http://stackoverflow.com/comment/89304782
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89304797
has comment: http://stackoverflow.com/comment/89304821
has title: How to retrieve these values from a json object in Python?
has comment: http://stackoverflow.com/comment/89304701
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89305353
tagged with: python
linked to: http://stackoverflow.com/q/15479928
has comment: http://stackoverflow.com/comment/89305960
has body: I'm a beginner Python coder. I've been trying to get the opening stock price for a range of dates using the IEX API. My json values are showing: {'AAPL': {'2017-02-09': {'open': 129.1019, 'high': 129.8815, 'low': 128.5821, 'close': 129.8569, 'volume': 28349859.0}, '2017-02-10': {'open': 129.8962, 'high': 130.3669, 'low': 129.4941, 'close': 129.5628, 'volume': 20065458.0}, '2017-02-13': {'open': 130.5042, 'high': 131.2299, 'low': 130.1806, 'close': 130.7101, 'volume': 23035421.0}}} If I only want to show only the 'open' prices for all the dates, how do I do that? I've been googling lists and dictionaries but couldn't find anything useful... from iexfinance import get_historical_data from datetime import datetime import json start = datetime(2017, 2, 9) end = datetime(2017, 2, 13) f = get_historical_data("AAPL", start, end, output_format='json') json_string = json.dumps(f) json_read = json.loads(json_string) print(json_read)
has answer: http://stackoverflow.com/a/51160857
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51160745
has comment: http://stackoverflow.com/comment/89304730
type: Question
has answer: http://stackoverflow.com/a/51161285
linked to: http://stackoverflow.com/q/5147292

http://stackoverflow.com/comment/89228190
comment on: http://stackoverflow.com/a/51121366
type: AnswerComment
type: Comment
has text: len(forwards), len(lefts), len(rights) is [32000, 0, 0] which is strange since it should mean in the dataset there are only forwards.
score: 0

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/51018501
tags question: http://stackoverflow.com/q/51160345
tag name: multi-gpu

http://stackoverflow.com/a/51035623
upvote count: 4
answers question: http://stackoverflow.com/q/51035431
has comment: http://stackoverflow.com/comment/89114543
has comment: http://stackoverflow.com/comment/89063075
has comment: http://stackoverflow.com/comment/89063152
downvote count: 0
has comment: http://stackoverflow.com/comment/89063116
has comment: http://stackoverflow.com/comment/89122239
has comment: http://stackoverflow.com/comment/89063370
has comment: http://stackoverflow.com/comment/89063134
has body: This should work: for k,v in dict_cg.items(): if np.isnan(v[1]): dict_cg.pop(k) print dict_cg Output: OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0))])
has comment: http://stackoverflow.com/comment/89063439
score: 4
has comment: http://stackoverflow.com/comment/89084531
has comment: http://stackoverflow.com/comment/89063344
has comment: http://stackoverflow.com/comment/89063057
type: Answer

http://stackoverflow.com/comment/89165583
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51088188
has text: I hope you didnt misunderstood new_test as a name for count_vectorizer

http://stackoverflow.com/comment/89117704
score: 1
has text: Using string formatting `%` in sql is really really not recommended. This kind of thing opens up a whole class of security vulnerabilities called SQL injection. The database library should should provide a safe alternative to raw string formatting.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51063711

http://stackoverflow.com/a/51145079
score: 0
accepted answer of: http://stackoverflow.com/q/51144474
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51144474
type: Answer
has comment: http://stackoverflow.com/comment/89314255
has comment: http://stackoverflow.com/comment/89277323
has body: The import keyword was only introduced in ES6 (ECMAScript 6), so it's likely that you're using an older version. Update Node and see how you go.

http://stackoverflow.com/a/51027867
downvote count: 0
has body: You can use enumerate: l = [[1, 2, 3], [4, 5, 6]] new_l = [[c+i for c in a] for i, a in enumerate(l, 1)] Output: [[2, 3, 4], [6, 7, 8]]
upvote count: 3
answers question: http://stackoverflow.com/q/51027813
type: Answer
score: 3

http://stackoverflow.com/q/51123147
type: Question
answer count: 2
downvote count: 0
tagged with: dataset
possible better answer: http://stackoverflow.com/a/66296620
has body: I am trying to find databases like the LJ Speech Dataset made by Keith Ito. I need to use these datasets in TacoTron 2 (Link), so I think datasets need to be structured in a certain way. the LJ database is linked directly into the tacotron 2 github page, so I think it's safe to assume it's made to work with it. So I think Databases should have the same structure as the LJ. I downloaded the Dataset and I found out that it's structured like this: main folder: -wavs -001.wav -002.wav -etc -metadata.csv: This file is a csv file which contains all the things said in every .wav, in a form like this **001.wav | hello etc.** So, my question is: Are There other datasets like this one for further training? But I think there might be problems, for example, the voice from one dataset would be different from the one in one another, would this cause too much problems? And also different slangs or things like that can cause problems?
has answer: http://stackoverflow.com/a/66296620
accepted answer: http://stackoverflow.com/a/55297534
favorite count: 0
upvote count: 2
has title: Datasets like "The LJ Speech Dataset"
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/94860446
has answer: http://stackoverflow.com/a/55297534

http://stackoverflow.com/comment/101898620
type: Comment
type: AnswerComment
has text: For me the 'find_longest_match()' doesn't give the longest match at all even with 'autojunk=False'. So I had to get all the matchings and pick the largest one with a loop.
comment on: http://stackoverflow.com/a/51063000
score: 0

http://stackoverflow.com/a/51372230
accepted answer of: http://stackoverflow.com/q/51074441
upvote count: 3
answers question: http://stackoverflow.com/q/51074441
has comment: http://stackoverflow.com/comment/127193982
has body: How about something like the following? Save the code as file_converter.py and run the script with arguments: python file_converter.py -h python file_converter.py &lt;path-to-input-dir&gt; -o &lt;path-to-output-dir&gt; And here the code for the converter. #!/usr/bin/env python import os import vtk import argparse def convertFile(filepath, outdir): if not os.path.isdir(outdir): os.makedirs(outdir) if os.path.isfile(filepath): basename = os.path.basename(filepath) print("Copying file:", basename) basename = os.path.splitext(basename)[0] outfile = os.path.join(outdir, basename+".stl") reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filepath) reader.Update() writer = vtk.vtkSTLWriter() writer.SetInputConnection(reader.GetOutputPort()) writer.SetFileName(outfile) return writer.Write()==1 return False def convertFiles(indir, outdir): files = os.listdir(indir) files = [ os.path.join(indir,f) for f in files if f.endswith('.vtk') ] ret = 0 print("In:", indir) print("Out:", outdir) for f in files: ret += convertFile(f, outdir) print("Successfully converted %d out of %d files." % (ret, len(files))) def run(args): convertFiles(args.indir, args.outdir) if __name__ == '__main__': parser = argparse.ArgumentParser(description="VTK to STL converter") parser.add_argument('indir', help="Path to input directory.") parser.add_argument('--outdir', '-o', default='output', help="Path to output directory.") parser.set_defaults(func=run) args = parser.parse_args() ret = args.func(args)
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/127193737

http://stackoverflow.com/q/51122781
linked to: http://stackoverflow.com/q/61965489
upvote count: 3
tagged with: import
type: Question
has title: Convert SAV into CSV
has answer: http://stackoverflow.com/a/51122951
tagged with: spss-files
has comment: http://stackoverflow.com/comment/89230880
has comment: http://stackoverflow.com/comment/89230886
accepted answer: http://stackoverflow.com/a/51122951
tagged with: converters
has body: I tried to convert a SAV file into CSV by using the following code data = pd.io.stata.read_stata("C:/Users/Nicola/Desktop/Relevant projects activities ACF/BRACED Final Evaluation/Evaluations/CSI_compil_2017.sav") writer = pd.ExcelWriter('C:/Users/Nicola/Desktop/Baseline.xlsx') data.to_excel(writer, 'data') data.to_csv('changed_to_csv.csv') writer.save() The output I am getting is the following ValueError: Version of given Stata file is not 104, 105, 108, 111 (Stata 7SE), 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12), 117 (Stata 13), or 118 (Stata 14) Is there a better snippet I could use to perform this conversion more efficiently? Thanks
downvote count: 0
has comment: http://stackoverflow.com/comment/89230679
has answer: http://stackoverflow.com/a/67937318
favorite count: 0
has answer: http://stackoverflow.com/a/57769724
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/14647006
tagged with: python
has comment: http://stackoverflow.com/comment/89230746
possible better answer: http://stackoverflow.com/a/51122943
answer count: 4
has answer: http://stackoverflow.com/a/51122943
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89230757

http://stackoverflow.com/a/51047883
has comment: http://stackoverflow.com/comment/89127226
type: Answer
has comment: http://stackoverflow.com/comment/89127102
has comment: http://stackoverflow.com/comment/89127269
answers question: http://stackoverflow.com/q/51047718
score: 0
has body: I think this is a correct logic. Since you have to keep the level of the skill for each employee. Lets say you have created three models. Employee skill Result when you do to get the skills of employee with id = 37 emp = Employee.objects.get(pk=37) #here we will get an array which has tuple all the skills and its level for employee skill_level_array = [(Skill.objects.filter(pk=x.skill), x.level) for x in Result.objects.filter(employee=emp)] To get skills for all empoyees all_emp = Employee.objects.all() grand_array = {} for emp in all_emp: skill_level_array = [(Skill.objects.filter(pk=x.skill), x.level) for x in Result.objects.filter(employee=emp)] grand_array[emp] = skill_level_array Now grand_array has an array of dictionary, with key as employee and value as array of tuple

http://stackoverflow.com/a/59923651
answers question: http://stackoverflow.com/q/51045911
type: Answer
upvote count: 1
score: 1
has body: I realize this question was probably based in a miss-diagnosed firewall or NAT issue, but in case people come here actually wanting to serve a Flask app with waitress on windows properly (as a service), I want to point to my answer here, so that it can be of use and receive some feedback.
downvote count: 0

http://stackoverflow.com/comment/89313590
comment on: http://stackoverflow.com/q/51165089
has text: a property method can't act as a field, and will not be possible to filter with it in django ORM
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51029419
has comment: http://stackoverflow.com/comment/89052751
tagged with: python
has comment: http://stackoverflow.com/comment/89051475
has comment: http://stackoverflow.com/comment/89051931
has comment: http://stackoverflow.com/comment/89053900
has comment: http://stackoverflow.com/comment/89051292
has comment: http://stackoverflow.com/comment/89051963
accepted answer: http://stackoverflow.com/a/51029632
downvote count: 2
has comment: http://stackoverflow.com/comment/89051652
has title: Python create 3 files from 1 file based on strings
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89051252
has comment: http://stackoverflow.com/comment/89052453
score: -2
has comment: http://stackoverflow.com/comment/89051270
type: Question
has comment: http://stackoverflow.com/comment/89054394
has comment: http://stackoverflow.com/comment/89051371
has comment: http://stackoverflow.com/comment/89051989
upvote count: 0
has comment: http://stackoverflow.com/comment/89052034
answer count: 1
has answer: http://stackoverflow.com/a/51029632
has body: I have a large dataset that is stored in a file on Linux. I would like to write a python script that will take this file and write it to 3 files based on the first occurrence of 3 specific strings. My dataset looks like this: Handle: A1 OrgID: AA Name: Name1 Handle: A2 OrgID: BB Name: Name2 OrgID: 1111 OrgName: Name1 Street: 1111 Street OrgID: 2222 OrgName: Name2 Street: 2222 Street NetHandle: Net1 OrgID: AA Parent: Net1 NetHandle: Net2 OrgID: BB Parent: Net2 I want the first file to have all of the entries that start with "Handle" and stop before the entries that start with OrgID". The second file with entries that start with "OrgID" and the third file that starts with "NetHandle". The tricky part is that OrigID is in all three. I have tried a few ways from examples on stack and other sites but I have not been able to accomplish this yet. Any help would be greatly appreciated.
favorite count: 0
has comment: http://stackoverflow.com/comment/89054667
tagged with: linux

http://stackoverflow.com/comment/89212139
type: AnswerComment
has text: ok after getting an heart attack from the new shape it does able to make an histogram. but, it puted every subject in it own bar and not by average of the 4 groups
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51112605

http://stackoverflow.com/comment/138656163
comment on: http://stackoverflow.com/a/58830320
type: AnswerComment
has text: Though I could download wheels file from here https://github.com/cgohlke/python-ldap-build/releases
score: 0
type: Comment

matlab
tags question: http://stackoverflow.com/q/51093355
tags question: http://stackoverflow.com/q/51139899
tags question: http://stackoverflow.com/q/51117956
tags question: http://stackoverflow.com/q/51149865
tags question: http://stackoverflow.com/q/51047069
tags question: http://stackoverflow.com/q/51043819
tags question: http://stackoverflow.com/q/51154680
tags question: http://stackoverflow.com/q/51033026
tags question: http://stackoverflow.com/q/51161348
type: Tag
tag name: matlab
tags question: http://stackoverflow.com/q/51072573
tags question: http://stackoverflow.com/q/51106981
tags question: http://stackoverflow.com/q/51088131
tags question: http://stackoverflow.com/q/51092529
tags question: http://stackoverflow.com/q/51070397
tags question: http://stackoverflow.com/q/51064328
tags question: http://stackoverflow.com/q/51121678

http://stackoverflow.com/q/51014804
favorite count: 0
tagged with: beautifulsoup
upvote count: 2
accepted answer: http://stackoverflow.com/a/51014929
tagged with: python
tagged with: nextsibling
has title: BeautifulSoup finding nested tags, children
type: AnsweredQuestion
score: 2
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51014929
tagged with: findall
has body: I see a bunch of info on finding tags and info within tags, but I can't seem to find something similarly simple. What I'm trying to do is access the text or title of the "a" element(in this case, "United States") in the 3rd "td" element. The problem I'm running into is that the "style" of the 3rd "td" element is the same as the first "td" element("text-align: left") so I can't filter with that, and nextSibling only let me go one level down, to the 2nd "td" element. The rest of my code works(though it makes me use what I believe is outdated BeautifulSoup syntax, even though I have Python 3.6.5 and BS 4.6 installed. That's another issue, I guess). I'm trying to get the "country" variable to work and I've tried multiple things, but nothing I've tried works, except putting a bunch of .next.next.next at the end. The HTML(https://en.wikipedia.org/wiki/Toronto_FC#Current_roster): Goalkeeper ... ... United States My Code: vcard = page_soup.findAll("tr", {"class": "vcard agent"}) cards = vcard[0] for cards in vcard: league = page_soup.find("a", {"title": "Major League Soccer"}) league_name = league.text team = page_soup.find("h1", {"class": "firstHeading"}) team_name = team.text position = cards.a.text name = cards.findAll("span", {"class": "fn"}) player_name = unidecode(name[0].text) ***this variable not working*** country = cards.find("td", {"style": "text-align: left")
answer count: 1

scintilla
type: Tag
tag name: scintilla
tags question: http://stackoverflow.com/q/51113112

http://stackoverflow.com/a/51033242
score: 1
has comment: http://stackoverflow.com/comment/89071638
has comment: http://stackoverflow.com/comment/89078232
has comment: http://stackoverflow.com/comment/89073729
answers question: http://stackoverflow.com/q/51032453
has comment: http://stackoverflow.com/comment/89073899
has comment: http://stackoverflow.com/comment/89069544
accepted answer of: http://stackoverflow.com/q/51032453
has body: A common procedure is to use pandas which allows dtype soft conversion via pandas.DataFrame.infer_objects followed by pandas.DataFrame.values that returns a Numpy representation of the DataFrame. Optionally, you can specify the columns to use with usecols as suggested above. From the docs: usecols : list-like or callable, default None Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). How does that look like? df = pd.read_csv(infile, usecols = ['a', 'b']) # Read df_dtypes = df.infer_objects() # Soft conversion x = df.values # Numpy array print df.info() # Inspect -&gt; Object &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 3 entries, 0 to 2 Data columns (total 2 columns): a 3 non-null object b 3 non-null object dtypes: object(2) memory usage: 120.0+ bytes print df_types.info() # Inspect -&gt; dtype change &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 3 entries, 0 to 2 Data columns (total 2 columns): a 3 non-null int64 b 3 non-null int64 dtypes: int64(2) memory usage: 120.0 bytes print x # Inspect -&gt; numpy array [[7 3] [1 2] [5 1]]
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89073401
type: Answer
downvote count: 0

http://stackoverflow.com/q/51164281
has comment: http://stackoverflow.com/comment/89311883
score: 2
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: python
tagged with: pycharm
upvote count: 2
has answer: http://stackoverflow.com/a/51170007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89311867
has comment: http://stackoverflow.com/comment/89311925
has title: Installing Scikit-learn in pycharm on Mac
has body: I have been able to get all other packages working in my PyCharm environment, however when I try to download either sklearn or scikit-learn I get an error. The error starts like this: Collecting scikit-learn Using cached https://files.pythonhosted.org/packages/f5/2c/5edf2488897cad4fb8c4ace86369833552615bf264460ae4ef6e1f258982/scikit-learn-0.19.1.tar.gz Building wheels for collected packages: scikit-learn Running setup.py bdist_wheel for scikit-learn: started Running setup.py bdist_wheel for scikit-learn: finished with status 'error' Complete output from command "/Users/.../PycharmProjects/StartingProject/VE Test/bin/python" -u -c "import setuptools, tokenize;__file__='/private/var/folders/h0/0p8xxjc12kdgydxx7hpky_yc0000gn/T/pycharm-packaging/scikit-learn/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/h0/0p8xxjc12kdgydxx7hpky_yc0000gn/T/pip-wheel-wy8d4dqc --python-tag cp37: Partial import of sklearn during the build process. blas_opt_info: blas_mkl_info: customize UnixCCompiler libraries mkl_rt not found in ['/Users/.../PycharmProjects/StartingProject/VE Test/lib', '/usr/local/lib', '/usr/lib'] NOT AVAILABLE... I have tried to use my command line to install it as well but I am not finding success with that either. Any help would be appreciated. Thanks!
type: Question

http://stackoverflow.com/comment/89090380
comment on: http://stackoverflow.com/q/51045911
score: 0
has text: I just realized that can be reached by computers in the same network, but not from computers outside of the network
type: Comment
type: QuestionComment

graph-databases
tags question: http://stackoverflow.com/q/51026783
type: Tag
tag name: graph-databases

http://stackoverflow.com/comment/89021060
score: 1
has text: I am not 100% sure how it works, but it looks only `from_pyfile` method is working for the `instance_relative_config`. There is an example of accessing the config via `app.instance_path` at the bottom of http://flask.pocoo.org/docs/0.12/config/#config-dev-prod but this method looks a bit ad-hoc for me in terms of accessing a class.
type: QuestionComment
comment on: http://stackoverflow.com/q/51011855
type: Comment

matrix
tags question: http://stackoverflow.com/q/51085780
tags question: http://stackoverflow.com/q/51044417
tags question: http://stackoverflow.com/q/51030063
tags question: http://stackoverflow.com/q/51154435
tags question: http://stackoverflow.com/q/51087267
tag name: matrix
tags question: http://stackoverflow.com/q/51072549
tags question: http://stackoverflow.com/q/51146573
tags question: http://stackoverflow.com/q/51142844
tags question: http://stackoverflow.com/q/51049117
tags question: http://stackoverflow.com/q/51023118
tags question: http://stackoverflow.com/q/51077962
tags question: http://stackoverflow.com/q/51106981
tags question: http://stackoverflow.com/q/51018233
tags question: http://stackoverflow.com/q/51146949
tags question: http://stackoverflow.com/q/51103952
tags question: http://stackoverflow.com/q/51107567
tags question: http://stackoverflow.com/q/51161670
tags question: http://stackoverflow.com/q/51118926
tags question: http://stackoverflow.com/q/51016803
tags question: http://stackoverflow.com/q/51065823
tags question: http://stackoverflow.com/q/51066961
tags question: http://stackoverflow.com/q/51160354
type: Tag
tags question: http://stackoverflow.com/q/51040326
tags question: http://stackoverflow.com/q/51104939

http://stackoverflow.com/comment/89056595
has text: Does it make a difference if the missing values are blank as oppose to NaN - The missing values are blank in the dataframe
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51024585
type: Comment

http://stackoverflow.com/a/51040844
has body: To answer your both of your questions: First No, the code provided above shouldn't be circular, unless email.message contains references to the app module, assuming app is a valid module. Second Importing from email instead of email.message doesn't cause any errors because you are not importing the (seemingly) problematic EmailMessage class since it resides in email.message, not email. My theory is that it's caused by some import looping back to the app module located in the email.message module. Note: At the time of writing I was not aware that email or email.message were part of the standard (3.6.x) library, as I have never used anything related to those modules (and I don't use python 3.x&lt; very often) and thus I assumed this was caused by circular reference as the author suggested. As it turns out (and pointed out in the original post) this was caused by something else entirely.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51039756
answers question: http://stackoverflow.com/q/51039756

http://stackoverflow.com/a/51079771
answers question: http://stackoverflow.com/q/51064269
has comment: http://stackoverflow.com/comment/89148406
has comment: http://stackoverflow.com/comment/89150064
accepted answer of: http://stackoverflow.com/q/51064269
has comment: http://stackoverflow.com/comment/89149603
has comment: http://stackoverflow.com/comment/89150180
has body: Based on your data, I think this is what you ask for [Edit: see updated version below]: import pandas as pd from sklearn.linear_model import LinearRegression df = pd.DataFrame( {'Country:':['Brunei','Cambodia','Indonesia','Laos', 'Malaysia','Myanmar','Philippines','Singaore', 'Thailand','Vietnam'], '2000-2003': [0,0,14,1,6,0,25,8,26,8], '2004-2007': [0,3,15,6,21,0,37,11,44,36], '2008-2011': [0,5,31,9,75,0,58,27,96,61], '2012-2015': [5,11,129,35,238,3,99,65,170,96], '2016-2018': [6,22,136,17,211,10,66,89,119,88]}) # create a transposed version with country in header df_T = df.T df_T.columns = df_T.iloc[-1] df_T = df_T.drop("Country:") # create a new columns for target df["2019-2022"] = np.NaN # now fit a model per country and add the prediction for country in df_T: y = df_T[country].values X = np.arange(0,len(y)) m = LinearRegression() m.fit(X.reshape(-1, 1), y) df.loc[df["Country:"] == country, "2019-2022"] = m.predict(5)[0] This prints: Country: 2000-2003 2004-2007 2008-2011 2012-2015 2016-2018 2019-2022 Brunei 0 0 0 5 6 7.3 Cambodia 0 3 5 11 22 23.8 Indonesia 14 15 31 129 136 172.4 Laos 1 6 9 35 17 31.9 Malaysia 6 21 75 238 211 298.3 Myanmar 0 0 0 3 10 9.5 Philippines 25 37 58 99 66 100.2 Singaore 8 11 27 65 89 104.8 Thailand 26 44 96 170 119 184.6 Vietnam 8 36 61 96 88 123.8 Forget about my comment with shift(). I thought about it, but it makes not sense for this small amount of data, I think. But considering time series methods and treating each country's series as a time series may still be worth for you. Edit: Excuse me. The above code is unnessary complicated, but was just result of me going through it step by step. Of course it can simply be done row by row like tihs: import pandas as pd from sklearn.linear_model import LinearRegression df = pd.DataFrame( {'Country:':['Brunei','Cambodia','Indonesia','Laos', 'Malaysia','Myanmar','Philippines','Singaore', 'Thailand','Vietnam'], '2000-2003': [0,0,14,1,6,0,25,8,26,8], '2004-2007': [0,3,15,6,21,0,37,11,44,36], '2…
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/89283429
has text: https://github.com/SethMichaelLarson/virtualbox-python/issues/114 This seems to be a unsolved issue with threading and pyvbox.
score: 0
comment on: http://stackoverflow.com/q/51136288
type: Comment
type: QuestionComment

sql-authentication
tags question: http://stackoverflow.com/q/51066637
type: Tag
tag name: sql-authentication

http://stackoverflow.com/comment/89462979
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51087238
has text: I saw the question, smart that you've opened a new one for that. You probably need a FrontEnd developer to assist with this one, it's not really my expertise.
type: AnswerComment

http://stackoverflow.com/q/51092076
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Open new page in new tab in flask and pass parameters
has comment: http://stackoverflow.com/comment/89172715
has body: I want to open a new page in a new tab (Similar to window.open) using flask webApp and also pass parameters from the parent page to the child window and based on those parameters get data from database and show on the child window &lt;title&gt; Parent Page &lt;/title&gt; window.open('child.html') // pass parameters parameter1, parameter2 Flask Code: @app.route('/') def renderParentPage(): return render_template('parentPage.html') @app.route('/&lt;string:page_name&gt;/') def render_static(page_name): print('%s' % page_name) dataTosend = getBrandData("Parameters from parent page- parameter1, parameter2") return render_template('%s' % page_name, dataToSend=dataTosend)
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89172838
tagged with: http
type: Question
linked to: http://stackoverflow.com/q/19127434
score: 1
accepted answer: http://stackoverflow.com/a/51092533
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89172710
tagged with: javascript
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/51092533

http://stackoverflow.com/comment/89048300
score: 0
type: Comment
has text: The thing I fear with my approach is that because the handle remains open, nothing is flushed at a short iterval (because the file is not closed), and if that is the case for multiple files, all these buffers combined might take up quite some memory. Or is Python/the OS so smart that it will not let the buffer fill memory? (I added some data information in my OP.)
comment on: http://stackoverflow.com/a/51026511
type: AnswerComment

http://stackoverflow.com/a/51158653
has body: It's not clear what you want as your desired output. But you can find all svc_no covered by your criteria using a sequence of Boolean masks: df = pd.DataFrame({'svc_no': [11111, 22222, 11111], 'caller_id': [11111, 22222, 'n/a'], 'result': ['Not Match', 'Match', 'Not Match']}) counts = df['svc_no'].value_counts() grouper = df.groupby('svc_no')['caller_id'] cond1 = df['svc_no'].isin(counts[counts &gt; 1].index) cond2 = df['svc_no'].isin(df.loc[df['svc_no'] == df['caller_id'], 'svc_no']) cond3 = df['svc_no'].isin(df.loc[grouper.apply(lambda x: x.isin(['n/a', 'NULL'])), 'svc_no']) cond4 = df['svc_no'].isin(df.loc[df['result'] == 'Not Match', 'svc_no']) df.loc[cond1 &amp; cond2 &amp; cond3 &amp; cond4, 'remarks'] = 'Duplicate svc_no' print(df) caller_id result svc_no remarks 0 11111 Not Match 11111 Duplicate svc_no 1 22222 Match 22222 NaN 2 n/a Not Match 11111 Duplicate svc_no
has comment: http://stackoverflow.com/comment/89654876
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89654932
has comment: http://stackoverflow.com/comment/89653159
accepted answer of: http://stackoverflow.com/q/51157817
answers question: http://stackoverflow.com/q/51157817
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89301233
has comment: http://stackoverflow.com/comment/89301250
score: 1
has comment: http://stackoverflow.com/comment/89654919
has comment: http://stackoverflow.com/comment/89300716
has comment: http://stackoverflow.com/comment/89300779
downvote count: 0

http://stackoverflow.com/comment/89192309
score: 0
type: Comment
type: QuestionComment
has text: Which is where i want to save the file.
comment on: http://stackoverflow.com/q/51102237

http://stackoverflow.com/comment/89227328
comment on: http://stackoverflow.com/q/51118032
has text: @today you were right, learning rate was to high;)
type: Comment
type: QuestionComment
score: 0

deserialization
type: Tag
tags question: http://stackoverflow.com/q/51107600
tag name: deserialization
tags question: http://stackoverflow.com/q/51089252
tags question: http://stackoverflow.com/q/51054009

http://stackoverflow.com/q/51145801
has comment: http://stackoverflow.com/comment/94644943
favorite count: 0
score: 5
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51146337
has title: Importing JSON Object into Postgresql using Python
type: Question
has body: I'm trying to import JSON Data into the Postgresql using Python but, I'm getting "psycopg2.ProgrammingError: can't adapt type 'dict'" error when I put the "via" field with a JSONB data type in my created table in the Postgresql Database. Is there any way to fix my problem? Any help would do. sample.json [ { "url": "https://www.abcd.com/", "id": 123456789, "external_id": null, "via": { "channel": "email", "id": 4, "source": { "from": { "address": "abc@abc.com", "name": "abc def" }, "rel": null, "to": { "address": "def@def.com", "name": "def" } } } }, { "url": "http://wxyz.com/", "id": 987654321, "external_id": null, "via": { "channel": "email", "id": 4, "source": { "from": { "address": "xyz@xyz.com", "name": "uvw xyz" }, "rel": null, "to": { "address": "zxc@zxc.com", "name": "zxc" } } } } ] my_code.py import json import psycopg2 connection = psycopg2.connect("host=localhost dbname=sample user=gerald password=1234") cursor = connection.cursor() data = [] with open('sample.json') as f: for line in f: data.append(json.loads(line)) fields = [ 'url', #varchar 'id', #BigInt 'external_id', #BigInt Nullable 'via' #JSONB ] for item in data: my_data = [item[field] for field in fields] insert_query = "INSERT INTO crm VALUES (%s, %s, %s, %s)" cursor.execute(insert_query, tuple(my_data))
upvote count: 5
tagged with: http://stackoverflow.com/tag/json
tagged with: database
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51146337
tagged with: jsonb

http://stackoverflow.com/a/51178946
has body: It looks like the IMS JDBC driver should work with the Python JayDeBeApi. The code would look similar to the following: import jaydebeapi conn = jaydebeapi.connect('com.ibm.ims.jdbc.IMSDriver', ['jdbc:ims://&lt;host&gt;:&lt;port&gt;/&lt;psb_name&gt;', '&lt;user&gt;', '&lt;password&gt;'],'&lt;/to/path/imsudb.jar&gt;',) You will probably need an IMS System Programmer to set up the necessary backend address spaces along with the IMS catalog: IMS Connect (The IMS TCP/IP Gateway) IMS Open Database Manager IMS SCI/OM
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51137419
score: 2

http://stackoverflow.com/q/51078007
answer count: 2
has body: How come I am getting a shape ValueError for my neural network when what I am passing in is an array of shape (8,1) but the error I am getting is that the neural network is complaining about getting a (1,)? Neural Network: &gt;&gt;&gt; observation_dimension (8,) &gt;&gt;&gt; q_network = Sequential([ Dense(40, input_dim=observation_dimension, activation='relu'), Dense(40, activation='relu'), Dense(number_of_actions, activation='linear') ]) &gt;&gt;&gt; obs array([-0.00371828, 0.93953934, -0.37663383, -0.07161933, 0.00431531, 0.08531308, 0. , 0. ]) &gt;&gt;&gt; obs.shape (8,) Error: &gt;&gt;&gt; q_network.predict(obs) Traceback (most recent call last): ... ... ValueError: Error when checking input: expected dense_27_input to have shape (8,) but got array with shape (1,)
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/51079092
tagged with: keras
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51078727
has answer: http://stackoverflow.com/a/51078727
accepted answer: http://stackoverflow.com/a/51079092
upvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
score: 1
has title: Keras array shape error
type: Question

http://stackoverflow.com/q/51096373
linked to: http://stackoverflow.com/q/40686490
tagged with: scipy
type: Question
tagged with: numpy
score: -2
has title: Numpy fft not giving expected results
has comment: http://stackoverflow.com/comment/89213585
downvote count: 2
has comment: http://stackoverflow.com/comment/89181897
answer count: 1
has answer: http://stackoverflow.com/a/51105191
favorite count: 0
tagged with: fft
type: UnansweredQuestion
has body: I am trying to find the frequency spectrum in a current signal from a solenoid being driven by a 100Hz PWM driver. The signal is sampled at 19200 Hz. The following is a plot of the signal . The signal is a part of a longer time series data. 1024 data points are extracted form the 22 second point. Current Signal The following code is used for the analysis import numpy as np import matplotlib.pyplot as plt plt.figure(1) plt.plot(t,y) Fs=19200 # (Hz) sampling rate N=len(y) # length of signal time=N/Fs #total time of signal, 1/time is the fundamantal frequency freq=np.arange(N)/time # frequency vector for fft spectrum plot freq=freq[0:int(N/2)] # one sided frequecy Y=np.fft.fft(y)/N*2 # fft of signal Y=Y[0:int(N/2)] # one sided frequency plt.figure(2) plt.plot(freq,abs(Y)) # one sided frequency plot plt.xlabel("Hz") plt.ylabel("Units") plt.title("FFT spectrum") plt.grid() plt.show() One would expect a dominant 100 Hz component in the spectrum but the numpy fft results do not reflect that. Following is the numpy.fft frequency plot. FFT Spectrum Following is a plot form Matlab fft analysis for similar signal. As expected there is a dominant 100Hz component and it harmonics. Signal for Matlab fft analysis Matlab FFT spectrum
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/89198019

http://stackoverflow.com/a/51117710
upvote count: 3
answers question: http://stackoverflow.com/q/51117351
score: 3
has comment: http://stackoverflow.com/comment/99398245
downvote count: 0
type: Answer
has body: You can have a look in to this git hub page. https://github.com/experiencor/keras-yolo2

http://stackoverflow.com/comment/89242737
type: Comment
comment on: http://stackoverflow.com/a/51128938
score: 0
has text: @PM2Ring Don't ask me, ask OP. If that's an error, it's a business logic error, not a Python error.
type: AnswerComment

http://stackoverflow.com/a/51105673
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51103050
has body: To see the TMOS version, you would run tmsh show sys software. root@(ltm3)(cfg-sync Standalone)(Active)(/Common)(tmos)# show sys software -------------------------------------------------- Sys::Software Status Volume Product Version Build Active Status -------------------------------------------------- HD1.1 BIG-IP 13.1.0.5 0.0.5 yes complete HD1.2 BIG-IP 12.1.3.3 0.0.1 no complete HD1.3 none none none no complete

http://stackoverflow.com/q/51089814
has body: For the clustering algorithms in sklearn, is there a way to specify how many clusters you want the algorithm to find (instead of the algorithm finding its own number of clusters)? From my inputted data, I'm hoping for 2 clusters instead of the 3 it outputs for me. If it helps, I'm using the MeanShift algorithm (but my question applies to all of them). Also, most tutorials seem to use make_blobs, but I'm using pandas's read_csv to upload my data instead if that changes anything. This is the beginning part of my code: df = pd.read_csv(filename, header = 0) original_headers = list(df.columns.values) df = df._get_numeric_data() data = df.values ms = MeanShift() ms.fit(data) labels = ms.labels_ cluster_centers = ms.cluster_centers_ n_clusters_ = len(np.unique(labels)) print("Number of estimated clusters:", n_clusters_)
has answer: http://stackoverflow.com/a/51276842
tagged with: hierarchical-clustering
has comment: http://stackoverflow.com/comment/89178175
type: Question
has comment: http://stackoverflow.com/comment/89193058
answer count: 1
has comment: http://stackoverflow.com/comment/89197249
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89185129
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/89186268
has comment: http://stackoverflow.com/comment/89192436
tagged with: sklearn-pandas
has title: sklearn specifying number of clusters
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/q/51059678
score: -1
has body: I have data frame ["Trading_date","volume"]. how to create new data frame in which: aggregate multiple rows of the same trading date into one row and sum all the volumes.
accepted answer: http://stackoverflow.com/a/51059752
has comment: http://stackoverflow.com/comment/89109404
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89109360
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: how to aggregate multiple rows in pandas
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89109371
has answer: http://stackoverflow.com/a/51059752

http://stackoverflow.com/comment/89034491
comment on: http://stackoverflow.com/q/51020536
has text: What does the `pretrain_model` look like?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89038945
type: Comment
type: QuestionComment
has text: I want to find `fuz.token_set_ratio()` for each row of first dataframe with that of 2nd data frame if the `if ` condition is satisfied.Please help..i am new to python coding
comment on: http://stackoverflow.com/q/51012614
score: 0

http://stackoverflow.com/comment/89200393
comment on: http://stackoverflow.com/a/51106395
type: Comment
score: 1
type: AnswerComment
has text: This doesn't solve my particular problem: one of the modules is intended to be packaged for distribution via pip and so the end user cannot be required to edit the module once installed. Since the end user instantiates their own Base, I need to somehow pass it to the module. Even if I forced the user to use the module's Base, that would still prevent a second module from using the base. The goal is to modularize the app into useful components that have dedicated tables in a shared database.

amazon-web-services
tags question: http://stackoverflow.com/q/51047209
tags question: http://stackoverflow.com/q/51074502
tags question: http://stackoverflow.com/q/51101099
tags question: http://stackoverflow.com/q/51021038
tags question: http://stackoverflow.com/q/51028310
tags question: http://stackoverflow.com/q/51149832
tags question: http://stackoverflow.com/q/51133246
tags question: http://stackoverflow.com/q/51027796
tags question: http://stackoverflow.com/q/51162598
tags question: http://stackoverflow.com/q/51133277
tags question: http://stackoverflow.com/q/51120245
tags question: http://stackoverflow.com/q/51094961
tags question: http://stackoverflow.com/q/51022488
tags question: http://stackoverflow.com/q/51075892
tags question: http://stackoverflow.com/q/51060408
tags question: http://stackoverflow.com/q/51028785
type: Tag
tags question: http://stackoverflow.com/q/51105860
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/51158581
tags question: http://stackoverflow.com/q/51074403
tags question: http://stackoverflow.com/q/51136874
tags question: http://stackoverflow.com/q/51092035
tags question: http://stackoverflow.com/q/51108390
tags question: http://stackoverflow.com/q/51011448
tags question: http://stackoverflow.com/q/51104230
tags question: http://stackoverflow.com/q/51099089
tags question: http://stackoverflow.com/q/51087988
tags question: http://stackoverflow.com/q/51104357
tags question: http://stackoverflow.com/q/51105990
tags question: http://stackoverflow.com/q/51101224
tags question: http://stackoverflow.com/q/51101082
tags question: http://stackoverflow.com/q/51094284
tags question: http://stackoverflow.com/q/51018963
tags question: http://stackoverflow.com/q/51070229
tags question: http://stackoverflow.com/q/51064261

http://stackoverflow.com/a/51056151
score: 1
has comment: http://stackoverflow.com/comment/89110649
downvote count: 0
answers question: http://stackoverflow.com/q/51056081
type: Answer
has comment: http://stackoverflow.com/comment/89112703
has comment: http://stackoverflow.com/comment/89110705
upvote count: 1
has body: why not simple join all list and do check: if "0" not in a + b + c + d: print("you don't want this to be printing") and the solution more fast the set for mediun size lists, here some test for perfomance: In [1]: from random import randint ...: a = [str(randint(1, 1000)) for _ in range(500)] ...: b = [str(randint(1, 1000)) for _ in range(500)] ...: c = [str(randint(1, 1000)) for _ in range(500)] ...: d = [str(randint(1, 1000)) for _ in range(500)] ...: In [2]: %timeit "0" not in a + b + c + d 30.2 µs ± 265 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [3]: %timeit "0" not in set().union(a, b, c, d) 48.5 µs ± 219 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) but the solution using set saved memory, because a + b + c + d generate new big list.

http://stackoverflow.com/q/51110870
downvote count: 1
type: Question
type: AnsweredQuestion
has title: JSON do something if data exists and do something else if it doesn't
tagged with: http://stackoverflow.com/tag/json
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/51110897
answer count: 1
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/89209358
tagged with: python
has comment: http://stackoverflow.com/comment/89208781
has comment: http://stackoverflow.com/comment/89208900
has body: I have an API of JSON data that has ~600 entries that each contain changing data about an object. In some cases, there is a key data value and in others, there isn't. I want to check to see if that JSON data is present and store it and if it's not moved on to the next device. Trying to sort out entries that have specific data and those that don't: if data["entity"][n]["sensor_data"]["light_ intensity"] in data["entity"]: logger.debug("There is light_intensity data on this devcie") light_ intensity = data["entity"][n]["sensor_data"]["light_ intensity"] What is the best way to do this? Right now I'm getting a KeyError that 'light_ intensity' is not defined - If I manually look at the data and search for an entity that does have light_ intensity data and hardcode it like this. light_ intensity = data["entity"][222]["sensor_data"]["light_intesity"] logger.debug("Devcie 222 light_intesity: %s lums", light_intesity) Returns: Device 222 light_intensity: 88 lums This tells me that I can read data from entity's that do have the data buy get a KeyError from those that don't. I'm trying to create a search in a sense that allows me to find what devices have light readings percent and use that data and skip devices that are not currently sending that data.
accepted answer: http://stackoverflow.com/a/51110897

http://stackoverflow.com/q/51064346
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51065112
type: Question
has body: I have a set of objects and their positions over time. I would like to get the average distance between objects for each time point. An example dataframe is as follows: time = [0, 0, 0, 1, 1, 2, 2] x = [216, 218, 217, 280, 290, 130, 132] y = [13, 12, 12, 110, 109, 3, 56] car = [1, 2, 3, 1, 3, 4, 5] df = pd.DataFrame({'time': time, 'x': x, 'y': y, 'car': car}) df x y car time 0 216 13 1 0 218 12 2 0 217 12 3 1 280 110 1 1 290 109 3 2 130 3 4 2 132 56 5 The end result I would like to have is: df2 average distance between cars time 0 1.55 1 10.05 2 53.04 any idea on how to proceed? I've been trying apply the scipy.spatial.distance function to the dataframe, but I'm not sure how to apply it to df.groupby('time'), and then get the mean value of all those distances. Any help appreciated!
has title: How to apply euclidean distance function to a groupby object in pandas dataframe?
tagged with: dataframe
score: 4
tagged with: pandas
tagged with: euclidean-distance
possible better answer: http://stackoverflow.com/a/51065112
accepted answer: http://stackoverflow.com/a/51065497
favorite count: 0
has answer: http://stackoverflow.com/a/51066806
tagged with: python
has answer: http://stackoverflow.com/a/51065404
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/51065497

http://stackoverflow.com/q/51072977
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89136437
answer count: 1
has answer: http://stackoverflow.com/a/51073188
score: -1
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89136664
has comment: http://stackoverflow.com/comment/89135808
has comment: http://stackoverflow.com/comment/89136291
favorite count: 0
tagged with: python-3.x
has title: Get a percentage range of a list in python
accepted answer: http://stackoverflow.com/a/51073188
downvote count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89136646
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89161191
has comment: http://stackoverflow.com/comment/89135807
has body: I'm trying to find the data range of a given percentage in a list. I want my result to be the highest and lowest extremes of that range. This is the simplest workable solution I have so far. 'The string formatting is just for testing, when I implement this it will only return the desired values'. If you don't understand what I am trying to achieve then run my code and you should be able to understand what I am trying to accomplish. #Sample Data List data = [ 4.252, 5.878, 1.435, -0.112, 6.97, -1.812, 0.887, 1.724, -1.452, 5.193, -1.001, 11.085, 1.335, 11.763, -7.284, -1.733, 3.175, 3.077, 0.249, -2.095, -0.253, 11.095, 5.184, 1.45, -3.882, 8.251, -4.234, -0.096, 5.957, -4.473, -3.874, 3.246, -0.929, -1.707, 2.079, 0.647, -8.189, 2.074, 3.226, 0.123, -3.097, -5.706, 4.276, 7.377, -5.861, 0.357, 0.966, -0.63, 2.129, 1.514, 6.82, -1.854, 8.394, 5.141, -4.501, 1.307, -2.812, -0.348, 2.729, 2.232, 4.096, -2.257, -4.802, -1.116, 1.346, 4.733, -1.391, -2.986, 2.8, 4.949, -4.101, 2.727, -1.267, -15.034, 5.322, 7.011, 6.36, 0.16, 0.719, 4.302, 1.365, 3.098, -2.892, -4.589, -5.516, 2.182, -6.019, -6.75, 15.499, -4.58, 3.516, 1.18, 9.648, -1.21, -10.911, -0.583, -0.545, 3.286, 0.51, 9.578, -2.444, 2.771, -3.846, -3.819, 1.877, 1.392, -2.784, -5.907, 4.206, 1.42, -2.279, -0.358, -0.649, 2.052, 1.04, 1.764, -3.156, -2.685, 0.106, 3.569, 0.944, 3.797, -0.76, 4.89, -3.014, -2.118, -1.142, -1.578, -8.84, 3.034, -2.693, -2.989, -0.815, -2.504, 3.147, 1.596, -2.94, 0.906, -0.154, -3.765 ] #Input for percent range percent = 50 #Get half of percentage halfPercent = int(int((len(data) * float('.'+str(percent))/2))) #Build string for printing later and create a counter string = str(percent)+'% of data entries are beween values ' counter = 0 #Sort data and iterate up until it get to the counter gets to the halfPercent for item in sorted(data): if item &gt;= 0: counter += 1 if counter &gt;= halfPercent: string += str(item) counter = 0 break string += ' and ' #Sort data and iterate up until…

http://stackoverflow.com/comment/89170353
has text: Exactly, because numpy provides wheel files (precompiled packages) for python 3.6 which can be installed without having a compiler.
type: Comment
comment on: http://stackoverflow.com/a/51089259
score: 0
type: AnswerComment

http://stackoverflow.com/q/51017519
has comment: http://stackoverflow.com/comment/89033900
tagged with: matplotlib
score: 0
has comment: http://stackoverflow.com/comment/89138631
tagged with: matplotlib-basemap
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89090643
has title: Why doesn't my plot display the its coordinate points?
answer count: 0
type: UnansweredQuestion
has body: I am trying to use Matplotlib's Basemap class to display a bunch of US cities, their locations and dots that vary with the population size of the city. When I attempt to plot the information, neither the m.plot nor m.scatter work in displaying the points that I would like it to display. Here is the code import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import json import random #===========GETTING DATA FROM THE JSON FILE========# path = r"cities_data.json" json_file = open(path,"r", encoding="utf-8") #open file from path to read cities_info = json.load(json_file) #load the json file json_file.close() #close print(cities_info[1]["city"]) print(len(cities_info)) #take the city names out of every single dictionary in the json names = [] for x in range(len(cities_info)): temp = cities_info[x]["city"] names.append(temp) #take the latitudes lats = [] for x in range(len(cities_info)): temp = cities_info[x]["latitude"] lats.append(temp) #take the longitudes longs = [] for x in range(len(cities_info)): temp = cities_info[x]["longitude"] longs.append(temp) #get the population of each city pops = [] for x in range(len(cities_info)): temp = cities_info[x]["population"] pops.append(int(temp)) print(pops) #normalization of the data nPops = [(x - np.min(pops))/(np.max(pops) - np.min(pops)) for x in pops] #store a basemap object with the mercator projection m = Basemap(projection="mill",llcrnrlat=25,llcrnrlon=-130,urcrnrlat=50,urcrnrlon=-60) #draw the coast lines of the countries m.drawcoastlines() #color the continents red m.fillcontinents() #draw the countries m.drawcountries() #draw states m.drawstates() #==============FUNCTIONS===============# #create a function that randomly picks a color (as HEX decimal) def random_color(number_of_colors): color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(number_of_colors)] print(color) return color #plotting the position of NYC NYClat, NYClon = 40.7, -74.006…
type: Question

http://stackoverflow.com/a/51034830
has body: I followed the link from a question and eventually ended up at this answer : https://stackoverflow.com/a/10482477/5907969 The answer has a function to align the y-axes and I have modified the same to align x-axes as follows: def align_xaxis(ax1, v1, ax2, v2): """adjust ax2 xlimit so that v2 in ax2 is aligned to v1 in ax1""" x1, _ = ax1.transData.transform((v1, 0)) x2, _ = ax2.transData.transform((v2, 0)) inv = ax2.transData.inverted() dx, _ = inv.transform((0, 0)) - inv.transform((x1-x2, 0)) minx, maxx = ax2.get_xlim() ax2.set_xlim(minx+dx, maxx+dx) And then use it within the code as follows: import pandas as pd import matplotlib.pyplot as plt d = {'col1':['Test 1','Test 2','Test 3','Test 4'],'col 2' [1.4,-3,1.3,5],'Col3':[900,750,878,920]} df = pd.DataFrame(data=d) fig = plt.figure() # Create matplotlib figure ax = fig.add_subplot(111) # Create matplotlib axes ax2 = ax.twiny() # Create another axes that shares the same y-axis as ax. width = 0.4 df['col 2'].plot(kind='barh', color='darkblue', ax=ax, width=width, position=1,fontsize =4, figsize=(3.0, 5.0)) df['Col3'].plot(kind='barh', color='orange', ax=ax2, width=width, position=0, fontsize =4, figsize=(3.0, 5.0)) ax.set_yticklabels(df.col1) ax.set_xlabel('Positive and Neg',color='darkblue') ax2.set_xlabel('Positive Only',color='orange') align_xaxis(ax,0,ax2,0) ax.invert_yaxis() plt.show() This will give you what you're looking for
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51034573
answers question: http://stackoverflow.com/q/51034573
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/51090121
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89169199
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89168802
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51090554
tagged with: numpy
has comment: http://stackoverflow.com/comment/89168791
tagged with: arrays
has comment: http://stackoverflow.com/comment/89168969
has comment: http://stackoverflow.com/comment/89169325
score: 0
has body: Suppose I have this: import numpy as np x = np.zeros((10,16), dtype=np.int) x[6:8,3:11] = 1 x[4:6,5:7] = 1 x[2:4,4:8] = 1 x[4:6,9:11] = 1 x[7,2] = 1 x[6,11] = 1 x[8,3] = 1 print(x) Output: [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0] [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0] [0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0] [0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]] And I want to filter it so that elements in a 4 neighborhood (so, up, left, right, bottom) that have less than than 2 neighbors are removed. So, I'd end up with (last three positions set as one removed): [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0] [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0] [0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0] [0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]] I tried using scipy.ndimage.morphology.binary_closing, scipy.ndimage.morphology.binary_opening, scipy.ndimage.morphology.binary_dilation and scipy.ndimage.morphology.binary_erosion, but the result isn't what I need. I could make 2 for loops and iterate over each element of the array, checking for the neighbor elements, but I feel like there's a better way to do this. Am I mistaken? I'm more interested in this specific situation (4 neighborhood, keep 2 neighbors), but is it easy to generalize to another neighborhood or number of neighbors (assuming a binary array)?
answer count: 1
has title: Removing elements from a binary python array whose neighborhood are less than N

http://stackoverflow.com/q/51101998
tagged with: python
accepted answer: http://stackoverflow.com/a/51102126
has body: So I have a dictionary of DataFrames which I've split up at the moment into single DataFrames because I don't know how to work on it directly in the dictionary. They are results of test specimen which look like this for example T01 mm N Cycle a 1 1 b 2 1 c 3 2 d 4 2 e 5 3 ... ... ... Now I have made another DataFrame (tried it with a list aswell) looking like this: Cycles 1 3 5 ... My goal is to filter out every row where Cycle != Cycles So I get a list that looks like this: mm N Cycle a 1 1 b 2 1 e 5 3 f 6 3 ... ... ... I've created the DataFrames by this code: for k,v in data_dict.items(): globals()[k] = (v'mm','N', 'Unnamed: 3') globals()[k].columns = ['mm', 'N', 'Cycles'] Now I have 7 different DataFrames with different sizes ranging from (2570, 3) to (12402, 3). I've been looking around all the time but I can't seem to find a way that's working out. Maybe I shouldn't have used the globals()[k] call? I'm fairly new to python so I lack a lot of knowledge. Thank you in advance Edit: I've been trying it with bool operations like globals()[k].query("Cycle" != Cycles['Cycles']) or globals()[k][globals()[k].Cycle != Cycles['Cycles']] But that's not doing anything for me.
score: 1
upvote count: 1
type: AnsweredQuestion
tagged with: dataframe
type: Question
has title: Python - Filter DataFrame via column-comparison with another df/list
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51102219
downvote count: 0
has answer: http://stackoverflow.com/a/51102286
favorite count: 0
has answer: http://stackoverflow.com/a/51102126
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51102219

http://stackoverflow.com/comment/89351095
score: 0
type: Comment
has text: @MartijnPieters true, I've edited the post to say base85. Thank you for the comment.
type: AnswerComment
comment on: http://stackoverflow.com/a/51153555

http://stackoverflow.com/a/51035791
has comment: http://stackoverflow.com/comment/89063806
answers question: http://stackoverflow.com/q/51035731
has comment: http://stackoverflow.com/comment/89063586
accepted answer of: http://stackoverflow.com/q/51035731
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/89063558
downvote count: 0
has comment: http://stackoverflow.com/comment/89063787
has comment: http://stackoverflow.com/comment/89063484
has comment: http://stackoverflow.com/comment/89063742
has comment: http://stackoverflow.com/comment/89063466
has comment: http://stackoverflow.com/comment/89063695
has body: Use positional argument specifier in format: &gt;&gt;&gt; '{0} {0}, {1}!'.format('hello', 'world') 'hello hello, world!' &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/89063957
upvote count: 3
has comment: http://stackoverflow.com/comment/89063410
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89063862
has comment: http://stackoverflow.com/comment/89063925

http://stackoverflow.com/comment/89156850
has text: I know what you mean. I am calling connect and I want a way to check if I have called `connect`.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51083560
type: QuestionComment

http://stackoverflow.com/a/51090079
has comment: http://stackoverflow.com/comment/89169359
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89169078
has comment: http://stackoverflow.com/comment/89168734
has comment: http://stackoverflow.com/comment/89169010
type: Answer
accepted answer of: http://stackoverflow.com/q/51089741
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51089741
has comment: http://stackoverflow.com/comment/89168731
has body: I have modified your code to follow PEP8 a little better and corrected the game() method by removing the sleep() method and adding 2 more methods for controlling left and right movement. By making sure our Canvas is a class attribute and the character is a class attribute we can interact with them from any method within the class. I made everything into a class attribute that I thought should probably be one. Updated to include max left and max right. import tkinter as tk class Window(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.master.title('Dodger') self.master.geometry('600x800') self.master.config(bg='black') menu = tk.Menu(self.master) file = tk.Menu(menu) file.add_command(label='Exit', command=exit) file.add_command(label='Start', command=self.game) menu.add_cascade(label='File', menu=file) self.master.config(menu=menu) self.canvas = None self.character = None self.master.bind("&lt;Left&gt;", self.left_key) self.master.bind("&lt;Right&gt;", self.right_key) def game(self): self.canvas = tk.Canvas(self.master, width='600', height='800') self.canvas.pack() self.canvas.create_rectangle(0, 0, 600, 800, fill='black', outline='black') self.character = self.canvas.create_rectangle(270, 730, 330, 760, fill='blue', outline='red') def left_key(self, event): cords = self.canvas.coords(self.character) if cords[0] &lt;= 5: print("Max left") else: self.canvas.move(self.character, -5, 0) def right_key(self, event): cords = self.canvas.coords(self.character) if cords[2] &gt;= 595: print("Max Right") else: self.canvas.move(self.character, 5, 0) root = tk.Tk() app = Window(root).pack(fill="both", expand=1) root.mainloop()
has comment: http://stackoverflow.com/comment/89168753

http://stackoverflow.com/comment/89233170
type: AnswerComment
score: 0
has text: checking the same, will revert accordingly.
type: Comment
comment on: http://stackoverflow.com/a/51123449

http://stackoverflow.com/comment/89237957
has text: I'm confused on why the code you posted doesn't work out for you?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51126515

http://stackoverflow.com/a/51130680
has body: PyCharm 2.7 takes care of readability and general beauty of your code. Now it supports continuous checking of your code for PEP 8 compliance on the fly, as you type it in the editor. PyCharm highlights any coding style violations and gives you suggestions, which you can apply instantly with the well known PyCharm quick-fixes (PEP8 guidline is to be found here) Autoformat Code: To reformat code for the current file, follow these steps: In the editor of the currently opened file, press Ctrl+Shift+Alt+L . Note that if you select Code. Reformat Code from the main menu or press Ctrl+Alt+L , PyCharm will try to reformat the source code automatically without opening the Reformat File dialog.
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51130546
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51130546
downvote count: 0
has comment: http://stackoverflow.com/comment/89246825

http://stackoverflow.com/q/51136116
downvote count: 0
favorite count: 0
has title: Matplotlib contour plot using specific data points from a set
has body: I am very sorry for the cumbersome title, but I don't find a way to express it clearly. The task that I should accomplish here is, given three numpy arrays containing coordinate matrices (X, Y) and the evaluation of a real function in this grid (Z); to obtain contour plots of the data. However, some of the coordinates give place to unacceptable Z values, and shouldn't be considered in the plots. What I have done so far: cmap = plt.cm.get_cmap("winter") cmap.set_under("magenta") cmap.set_over("yellow") with PdfPages('myplot.pdf') as pdf: fig = plt.figure() CS = plt.contourf(X, Y, Z, cmap=cmap) cbar = plt.colorbar(CS) cbar.ax.set_ylabel('Z') plt.xlabel('X (\AA)') plt.ylabel('Y (\AA)') plt.tight_layout() pdf.savefig(fig) However, I don't find a proper way to restrict the values that should be taken into account in the plots (something like Zmin &lt; Z &lt; Zmax). I thought on the methods set_under and set_over of cmap, but it doesn't seem to be the way. Any suggestion abut this problem? Thank you very much in advance.
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/51136285
type: Question
type: AnsweredQuestion
tagged with: matplotlib
tagged with: numpy
tagged with: contour
accepted answer: http://stackoverflow.com/a/51136285
score: 2
answer count: 1

http://stackoverflow.com/comment/89118246
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51063969
has text: I have updated the model code. @Mitiku what would be an efficient way to add layers?

http://stackoverflow.com/q/51043573
has title: Logistic regression: ValueError: Unknown label type: 'continuous'
has comment: http://stackoverflow.com/comment/89159629
accepted answer: http://stackoverflow.com/a/51044140
favorite count: 0
has body: I want to use logistic regression to predict and plot a curve from an Excel dataset and get its slope coefficients. However, when I run the code (see below) the error " ValueError: Unknown label type: 'continuous'. " occurs. I read in similar questions that the y values should be 'int' type but I don't want to convert it because the y numbers are between 1.66 and 0.44... Is there a solution for this kind of cases or should I try another regression model? Thanks a lot in advance import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import PolynomialFeatures import seaborn as sns from sklearn.linear_model import LogisticRegression df = pd.read_excel('Fatigue2.xlsx',sheet_name='Sheet4') X = df'Strain1', 'Temperature1' y = df['Cycles1'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=101) #poly = PolynomialFeatures(degree=2) #X_ = poly.fit_transform(X_train) LR = LogisticRegression() LR.fit(X_train,y_train) g = sns.lmplot(x='Cycles1', y='Strain1', hue = 'Temperature1', data=df, fit_reg= False) g.set(xscale='log', yscale ='log') g.set_axis_labels("Cycles (log N)", "Strain") print ('Coefficients : ', LR.coef_, 'Intercept :', LR.intercept_) About the data, I have 97 values in total in an Excel sheet: Cycles1 Strain1 Temperature1 27631 1.66 650 ... ... 650 6496220 0.44 650
possible better answer: http://stackoverflow.com/a/53324115
score: 0
has answer: http://stackoverflow.com/a/53324115
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89081338
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89080314
has answer: http://stackoverflow.com/a/51044140
tagged with: logistic-regression
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89079019
has comment: http://stackoverflow.com/comment/89079911

http://stackoverflow.com/comment/89093920
comment on: http://stackoverflow.com/a/51050909
score: 0
type: AnswerComment
has text: above function can help you in fetching the param. exmaple: get_url_param('country');
type: Comment

http://stackoverflow.com/q/51089781
favorite count: 0
has comment: http://stackoverflow.com/comment/89168153
tagged with: python
has comment: http://stackoverflow.com/comment/89168026
score: 2
accepted answer: http://stackoverflow.com/a/55388412
type: AnsweredQuestion
tagged with: pose-estimation
downvote count: 0
has body: How can I take two images of an object from different angles and draw epipolar lines on one based on points from the other? For example, I would like to be able to select a point on the left picture using a mouse, mark the point with a circle, and then draw an epipolar line on the right image corresponding to the marked point. I have 2 XML files which contain a 3x3 camera matrix and a list of 3x4 projection matrices for each picture. The camera matrix is K. The projection matrix for the left picture is P_left. The projection matrix for the right picture is P_right. I have tried this approach: Choose a pixel coordinate (x,y) in the left image (via mouse click) Calculate a point p in the left image with K^-1 * (x,y,1) Calulate the pseudo inverse matrix P+ of P_left (using np.linalg.pinv) Calculate the epipole e' of the right image: P_right * (0,0,0,1) Calculate the skew symmetric matrix e'_skew of e' Calculate the Fundamental matrix F: e'_skew * P_right * P+ Calculate the epipolar line l' on the right image: F * p Calculate a point p' in the right image: P_right * P+ * p Transform p' and l back to pixel coordinates Draw a line using cv2.line through p' and l
tagged with: computer-vision
type: Question
has answer: http://stackoverflow.com/a/55388412
tagged with: opencv
has comment: http://stackoverflow.com/comment/89186668
upvote count: 2
has title: How to calculate an epipolar line with a stereo pair of images in Python OpenCV
tagged with: stereo-3d
answer count: 1

http://stackoverflow.com/comment/113641614
comment on: http://stackoverflow.com/a/51162198
type: Comment
score: 1
has text: For me MATLAB is too expensive and it gives me no features in addition to my open source tool collection I use. However good to know. Thanks.
type: AnswerComment

http://stackoverflow.com/comment/89239683
score: 0
type: Comment
type: QuestionComment
has text: I was using 2.12.4. I just updated to 2.19.1 and it worked. Thank you so much. So much time wasted...
comment on: http://stackoverflow.com/q/51127307

http://stackoverflow.com/q/51048678
type: Question
has title: AttributeError: 'xml.etree.ElementTree.Element' object has no attribute '_children'
has comment: http://stackoverflow.com/comment/89088435
tagged with: python-2.7
has body: I have the following code : def result_saml_decoded(result_saml): """Illustrate to result saml decoded value as response in a string. :param result_saml:results saml decoded :return:return principle_arn, resultsamldecoded, role_arns """ result_saml_decoded = base64.b64decode(result_saml) root = ET.fromstring(result_saml_decoded) principle_arns, role_arns = [], [] inner_saml_tag = [saml2 for saml2 in root._children if 'Assertion' in saml2.tag] attribute_saml_tag = [saml_tag for saml_tag in inner_saml_tag[0]._children if 'AttributeStatement' in saml_tag.tag] for inner_saml_tag in attribute_saml_tag[0]._children: if 'uri' in inner_saml_tag.get('NameFormat'): for saml_data in inner_saml_tag._children: parts = saml_data.text.split(',') principle_arns.append(parts[0]) role_arns.append(parts[1]) return principle_arns, role_arns which works in python 2.7 but fails in python 3.6 with : Traceback (most recent call last): File "/Users/kaulk/sandbox/oktapod1/oktapod/helpers.py", line 135, in assume_role principle_arns, role_arns = result_saml_decoded(resultsaml) File "/Users/kaulk/sandbox/oktapod1/oktapod/helpers.py", line 188, in result_saml_decoded inner_saml_tag = [saml2 for saml2 in root._children if 'Assertion' in saml2.tag] AttributeError: 'xml.etree.ElementTree.Element' object has no attribute '_children' what am I supposed to use for code that is supposed to be compatible with py27 and 36 ?
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89088550
has comment: http://stackoverflow.com/comment/89088607

http://stackoverflow.com/comment/89158674
type: QuestionComment
comment on: http://stackoverflow.com/q/51085128
score: 6
has text: What have you tried? I would start by creating a method which will return if a number is composite or not
type: Comment

http://stackoverflow.com/q/51047704
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/51047933
favorite count: 0
accepted answer: http://stackoverflow.com/a/51047824
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/51047762
has comment: http://stackoverflow.com/comment/89086623
has answer: http://stackoverflow.com/a/51047762
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51047824
has title: Combining two lists of different length to tuples at every nth element of the longer list
score: 1
has body: I want to combine two list to a list of tuples at every nth element of the longer list. Example: list1 = ['I', 'am'] list2 = ['1', '2', '3', '4', '5', '6'] to: list3 = [('I', 'am', '1', '2', '3'), ('I', 'am', '4', '5', '6')] Unfortunately I don't know a way to iterate through lists with a potentially pretty large amount of values in a way to achieve the result. Can anyone give me a hint on how to do this?
has comment: http://stackoverflow.com/comment/89086988
type: Question

http://stackoverflow.com/comment/89079668
type: AnswerComment
score: 0
has text: It is pretty good solution because of avoiding object deep copy and the only problem is pretty similar block of ``setattr`` lines.
type: Comment
comment on: http://stackoverflow.com/a/51044159

http://stackoverflow.com/comment/89968381
type: Comment
comment on: http://stackoverflow.com/a/51061890
has text: Hey, sorry actually...there was something wrong with that txt file. It worked just fine with the right file. Thanks anyways...
score: 0
type: AnswerComment

http://stackoverflow.com/a/68572278
answers question: http://stackoverflow.com/q/51077064
score: 2
has body: You can execute a Transact-SQL script that call for the execution of the dtsx package. This has an advantage over other answers, because you do not need to have acces to the DTExec (that requires access to the machine where the SSIS Service is running) and works for other programming languages (most if not all of them allow executing TSQL). The only requirements would be: Be able to connect to the SQL Server Database service within python (pyodbc or similar) Configure the Integration Services Catalog in the SQL Server Database service Microsoft quickstart: SSIS with TSQL Stored procedure documentation: catalog.create_execution Code example, extracted from the quickstart: Declare @execution_id bigint EXEC [SSISDB].[catalog].[create_execution] @package_name=N'Package.dtsx', @execution_id=@execution_id OUTPUT, @folder_name=N'Deployed Projects', @project_name=N'Integration Services Project1', @use32bitruntime=False, @reference_id=Null Select @execution_id DECLARE @var0 smallint = 1 EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id, @object_type=50, @parameter_name=N'LOGGING_LEVEL', @parameter_value=@var0 EXEC [SSISDB].[catalog].[start_execution] @execution_id GO
upvote count: 2
has comment: http://stackoverflow.com/comment/126199604
type: Answer
downvote count: 0

http://stackoverflow.com/a/51098379
has comment: http://stackoverflow.com/comment/89190539
answers question: http://stackoverflow.com/q/51097971
has body: If you check shapes of X, Y and Z in contour3d example, you shall find out that they are the same. So, in order to make your code working, you should extend your xx and yy to 2d arrays with np.meshgrid before creating a plot. xx, yy = np.meshgrid(xx, yy)
accepted answer of: http://stackoverflow.com/q/51097971
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51108465
has body: Build the list of arguments dynamically from the dictionary. cmd = ['foocommand'] for name, val in args.items(): if val: cmd += [name, val]
score: 4
answers question: http://stackoverflow.com/q/51108400
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/51075666
tagged with: keras-layer
answer count: 3
downvote count: 0
tagged with: neural-network
tagged with: keras
favorite count: 0
tagged with: python-3.x
has body: I have been trying to merge the following sequential models but haven't been able to. Could somebody please point out my mistake, thank you. The code compiles while using"merge" but give the following error "TypeError: 'module' object is not callable" However it doesn't even compile while using "Merge" I am using keras version 2.2.0 and python 3.6 from keras.layers import merge def linear_model_combined(optimizer='Adadelta'): modela = Sequential() modela.add(Flatten(input_shape=(100, 34))) modela.add(Dense(1024)) modela.add(Activation('relu')) modela.add(Dense(512)) modelb = Sequential() modelb.add(Flatten(input_shape=(100, 34))) modelb.add(Dense(1024)) modelb.add(Activation('relu')) modelb.add(Dense(512)) model_combined = Sequential() model_combined.add(Merge([modela, modelb], mode='concat')) model_combined.add(Activation('relu')) model_combined.add(Dense(256)) model_combined.add(Activation('relu')) model_combined.add(Dense(4)) model_combined.add(Activation('softmax')) model_combined.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model_combined
has answer: http://stackoverflow.com/a/51082386
tagged with: python
upvote count: 6
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51105318
has answer: http://stackoverflow.com/a/51105318
score: 6
type: Question
has title: How to implement Merge from Keras.layers
accepted answer: http://stackoverflow.com/a/51082386
has answer: http://stackoverflow.com/a/54104873

http://stackoverflow.com/a/51026024
answers question: http://stackoverflow.com/q/51025860
has comment: http://stackoverflow.com/comment/89045215
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: This is due to var2 being initialized only once whilst importing. The way around this would be to write a getter or and update function. A possible getter function would be: a.py var1 = 0 var2 = var1 + 1 def getVar2(): return var1 + 1 b.py: import a def update_var(): a.var1 = 10 print("Updated var1 is {}".format(a.var1)) print("var2 is {}".format(a.getVar2())) if __name__ == "__main__": update_var() A possible update function would be: a.py var1 = 0 var2 = var1 + 1 def updateVar2(): var2 = var1+1 b.py: import a def update_var(): a.var1 = 10 a.updateVar2() print("Updated var1 is {}".format(a.var1)) print("var2 is {}".format(a.var2())) if __name__ == "__main__": update_var()

http://stackoverflow.com/q/51080936
has comment: http://stackoverflow.com/comment/89152026
score: 0
tagged with: lxml
has comment: http://stackoverflow.com/comment/89152578
has comment: http://stackoverflow.com/comment/89159266
has comment: http://stackoverflow.com/comment/89158384
has comment: http://stackoverflow.com/comment/89158746
linked to: http://stackoverflow.com/q/10457564
answer count: 0
has comment: http://stackoverflow.com/comment/89154405
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89159631
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/89159868
has comment: http://stackoverflow.com/comment/89151092
has comment: http://stackoverflow.com/comment/89158340
has comment: http://stackoverflow.com/comment/89158795
has comment: http://stackoverflow.com/comment/89153268
tagged with: scrapy
has title: scrapy error: Error reading file '': failed to load external entity ""
type: Question
has comment: http://stackoverflow.com/comment/89160654
has body: I'm currently writing a scraper with scrapy. For some websites it works just fine, but for other i get the error Error reading file '': failed to load external entity "" Here is the code I wrote for my scraper, don't blame me but I'm still a beginner in python. import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor #from bs4 import BeautifulSoup import lxml from lxml.html.clean import Cleaner #from scrapy.exporters import XmlItemExporter import re cleaner = Cleaner() cleaner.javascript = True cleaner.style = True cleaner.remove_tags = ['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'figure', 'small', 'blockquote', 'sub', 'em', 'hr', '!--..--', 'span', 'aside', 'a', 'svg', 'ul', 'li', 'img', 'source', 'nav', 'article', 'section', 'label', 'br', 'noscript', 'body', 'time', 'b', 'i', 'sup', 'strong', 'div'] cleaner.kill_tags = ['header', 'footer'] class MySpider(CrawlSpider): name = 'eship5' allowed_domains = [ 'ineratec.de', ] start_urls = [ 'http://ineratec.de/', ] rules = [Rule(LinkExtractor(), callback='parse_item', follow=True)] # Follow any link scrapy finds (that is allowed). def parse_item(self, response): page = response.url.replace("/"," ").replace(":"," ") filename = '%s.txt' %page body = response.url clean_text = lxml.html.tostring(cleaner.clean_html(lxml.html.parse(body))) #clean_text = re.sub( '\s+', ' ', str(clean_text, "utf-8").replace('&lt;div&gt;', '').replace('&lt;/div&gt;', '')).strip() with open(filename, 'w') as f: f.write(clean_text) When I run the code with scrapy, the error occurs only on certain websites. Does it has anything to do with the ' ' and the " " ?? Thankful for any help. EDIT1: This is the whole error: 2018-06-28 14:01:18 [scrapy.core.scraper] ERROR: Spider error processing &lt;GET https://smight.com/en/&gt; (referer: https://smight.com/) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scrapy/utils/defer.py", l…

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/51061816
type: Tag

http://stackoverflow.com/a/51097345
has comment: http://stackoverflow.com/comment/89185529
has comment: http://stackoverflow.com/comment/89186535
has comment: http://stackoverflow.com/comment/89185535
has body: Ok, the logic is thus: hMin = 1, h=0 h += (IntBLM(startPos,endPos)-Int(startX,endX,npoints,I1,I2,sigma1,sigma2))**2 a. if h is greater than or equal to 1, the conditional never executes b. else if h is now between 0 and 1, the conditional executes hMin = h Now, h will never be less than hMin, since it always increases by a positive amount (a squared value). Thus the conditional never executes again, and I1min, I2min, sigma1min, sigma2min maintain their instantiated values
has comment: http://stackoverflow.com/comment/89184362
score: 0
has comment: http://stackoverflow.com/comment/89182707
answers question: http://stackoverflow.com/q/51096550
has comment: http://stackoverflow.com/comment/89186543
type: Answer
has comment: http://stackoverflow.com/comment/89185738

http://stackoverflow.com/comment/89268750
comment on: http://stackoverflow.com/a/51142038
score: 0
type: Comment
has text: Using "data = cursor.fetchone" and setting "data = data[0]" worked ! Alexa successfully spoke ONE results of the query. The data variable when set to equal cursor.catchall is not a singleton, so is there anyway to return ALL results of the query ? (since using "curser.fetchone" only returns one result)
type: AnswerComment

http://stackoverflow.com/a/51159191
answers question: http://stackoverflow.com/q/51158988
has comment: http://stackoverflow.com/comment/89304380
score: 0
has comment: http://stackoverflow.com/comment/89306356
has body: Do you have to use Putty? If not, see this answer - How do I get a Cron like scheduler in Python?. It uses a library called schedule. I'm using it myself to delete files from a directory every morning. basically you will `pip install schedule', and then run your script with something like: import schedule def job(): #Whatever the function does schedule.every().hour.do(job) while True: schedule.run_pending() time.sleep(1) Hope this helps.
has comment: http://stackoverflow.com/comment/89302770
type: Answer

http://stackoverflow.com/q/51026771
has title: pandas "case insensitive" in a string or "case ignore"
linked to: http://stackoverflow.com/q/6579876
has body: Here is the code that works for lowercase and returns only "apple": df2 = df1['company_name'].str.contains("apple", na=False) I need this to find "apple", "APPLE", "Apple", etc. Something like: df2 = df1['company_name'].str.contains.caseignore("apple", na=False) is there such a function anywhere?
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89046007
favorite count: 0
accepted answer: http://stackoverflow.com/a/51026904
tagged with: case-sensitive
possible better answer: http://stackoverflow.com/a/72840331
linked to: http://stackoverflow.com/q/319426
downvote count: 1
has answer: http://stackoverflow.com/a/72840331
type: AnsweredQuestion
tagged with: dataframe
score: 46
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51026904
upvote count: 47
has comment: http://stackoverflow.com/comment/89047186

http://stackoverflow.com/q/51161676
has title: Structuring main method
favorite count: 0
accepted answer: http://stackoverflow.com/a/51161725
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89308317
tagged with: python
has comment: http://stackoverflow.com/comment/89306935
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/89306763
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89310650
score: 1
has body: I have a python script that will do 3 things: check to see if a file exists in a directory copy specific files from one directory to another, and execute another python script. Right now if I run the script it runs through all 3 functions, regardless of if the file exists in the test directory. What I want it to do is check to see if the file exists. If it does, copy it, and once it's copied execute the other script. I am having trouble figuring out a simple way to link them all together. Here is my script: import os import os.path from os import path import shutil def check_file(): file_exists = False for deploy_file in os.listdir("C:\\test1\\test.txt"): if deploy_file.startswith("test"): file_exists = True else: exit(1) print file_exists def copy_file(): src = "C:\\test1\\" dst = "C:\\test2\\" files = [i for i in os.listdir(src) if i.startswith("test") and path.isfile(path.join(src, i))] print files for f in files: shutil.copy(path.join(src, f), dst) def run_script(): os.system("pathofscript") # for testing its just a script that prints "hello world" def main(): check_file() copy_file() run_script() main() So by running this as-is the output will be: True ['test.txt'] "hello world" How can I write my main() method to do what I am trying to do?
type: Question
has answer: http://stackoverflow.com/a/51161725
answer count: 1

http://stackoverflow.com/q/51058236
tagged with: pyqt4
score: 0
tagged with: pyqt
answer count: 1
has body: first of all, this is my code: class Fillscreen(QtGui.QWidget, Ui_View): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent,) self.setupUi(self) def full(self): self.showMaximized() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) monitors = selector.getMonitors() resolutions = selector.getResolution(monitors) for monitor in monitors: window = Fillscreen() window.move(monitor[0],monitor[1]) window.full() app.exec_() monitors looks like this: [(-1280, 0, 0, 1024), (0, 0, 1920, 1080), (1920, 0, 3840, 1080)] As is it only creates one window, which absolutely makes sense since im overwriting window on each loop. To solve this i could manually create a window1, window2 and window3 But how would i do this when i can't be sure of the Number of Monitors?
has answer: http://stackoverflow.com/a/51058538
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51058538
tagged with: python
type: AnsweredQuestion
type: Question
has title: Create Qt windows based on number of list items

http://stackoverflow.com/q/51070985
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59284768
downvote count: 0
has answer: http://stackoverflow.com/a/56670242
has comment: http://stackoverflow.com/comment/89131926
has body: import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') percent= 100*(len(df.loc[:,df.isnull().sum(axis=0)&gt;=1 ].index) / len(df.index)) print(round(percent,2)) input is https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0 and the output should be Ord_id 0.00 Prod_id 0.00 Ship_id 0.00 Cust_id 0.00 Sales 0.24 Discount 0.65 Order_Quantity 0.65 Profit 0.65 Shipping_Cost 0.65 Product_Base_Margin 1.30 dtype: float64
has answer: http://stackoverflow.com/a/62959032
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/73998460
has answer: http://stackoverflow.com/a/64329968
has answer: http://stackoverflow.com/a/51071181
linked to: http://stackoverflow.com/q/26266362
has title: Find out the percentage of missing values in each column in the given dataset
upvote count: 89
has answer: http://stackoverflow.com/a/65597293
has answer: http://stackoverflow.com/a/74521372
possible better answer: http://stackoverflow.com/a/51071085
has comment: http://stackoverflow.com/comment/89131842
has answer: http://stackoverflow.com/a/51071085
tagged with: pandas
has answer: http://stackoverflow.com/a/65645116
has answer: http://stackoverflow.com/a/51071037
accepted answer: http://stackoverflow.com/a/51071037
has answer: http://stackoverflow.com/a/67490432
has comment: http://stackoverflow.com/comment/89131848
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/62035697
has comment: http://stackoverflow.com/comment/89131834
score: 89
tagged with: python
has answer: http://stackoverflow.com/a/56870739
linked to: http://stackoverflow.com/q/33346591
answer count: 15
has answer: http://stackoverflow.com/a/69769621

http://stackoverflow.com/a/51092533
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: In order to pass parameters to the child page, you can format it as a GET request: window.open('/child?param1=value1&amp;param2=value2') And then use request.args to get parsed contents of query string: from flask import request @app.route(...) def login(): username = request.args.get('username') password = request.args.get('password') #Do something with parameters return render_template([...])
accepted answer of: http://stackoverflow.com/q/51092076
type: Answer
answers question: http://stackoverflow.com/q/51092076

http://stackoverflow.com/q/51154528
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89292053
downvote count: 0
tagged with: string
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89292360
has body: i have a pandas series like this: 0 $233.94 1 $214.14 2 $208.74 3 $232.14 4 $187.15 5 $262.73 6 $176.35 7 $266.33 8 $174.55 9 $221.34 10 $199.74 11 $228.54 12 $228.54 13 $196.15 14 $269.93 15 $257.33 16 $246.53 17 $226.74 i want to get rid of the dollar sign so i can convert the values to numeric. I made a function in order to do this: def strip_dollar(series): for number in dollar: if number[0] == '$': number[0].replace('$', ' ') return dollar This function is returning the original series untouched, nothing changes, and i don't know why. Any ideas about how to get this right? Thanks in advance
tagged with: python
accepted answer: http://stackoverflow.com/a/51154548
has title: Replacing the first string character in python 3
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51154875
has answer: http://stackoverflow.com/a/51154561
type: Question
has comment: http://stackoverflow.com/comment/89292094
possible better answer: http://stackoverflow.com/a/51154561
tagged with: replace
has answer: http://stackoverflow.com/a/51154548

http://stackoverflow.com/a/70918939
has body: Another option would be to have an opencv VideoWriter encoding H264 frames and sending to shmsink: h264_shmsink = cv2.VideoWriter("appsrc is-live=true ! queue ! videoconvert ! video/x-raw, format=BGRx ! nvvidconv ! " "nvv4l2h264enc insert-sps-pps=1 ! video/x-h264, stream-format=byte-stream ! h264parse ! shmsink socket-path=/tmp/my_h264_sock ", cv2.CAP_GSTREAMER, 0, float(fps), (int(width), int(height))) where width and height are the sizes of pushed frames, and then use shmsrc doing timestamp as source for test-launch RTSP server such as: ./test-launch "shmsrc socket-path=/tmp/my_h264_sock do-timestamp=1 ! video/x-h264, stream-format=byte-stream, width=640, height=480, framerate=30/1 ! h264parse ! video/x-h264, stream-format=byte-stream ! rtph264pay pt=96 name=pay0 " This may have some system overhead, but may work for low bitrate, or may require some optimization for higher bitrates.
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51058911

http://stackoverflow.com/q/51017384
has title: Why does this not create a file?
tagged with: python
has comment: http://stackoverflow.com/comment/89027515
accepted answer: http://stackoverflow.com/a/51017614
has comment: http://stackoverflow.com/comment/89027453
possible better answer: http://stackoverflow.com/a/51017467
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/51017467
answer count: 2
has comment: http://stackoverflow.com/comment/89027325
downvote count: 0
has comment: http://stackoverflow.com/comment/89027731
has body: I'm new to Python, Selenium, et cetera. I'm just wondering why in this context test.txt isn't created and written to when I run the script. import scrapy from selenium.webdriver import Firefox from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = Firefox(executable_path='C:\webdriver\geckodriver.exe') driver.get('https://www.indiegogo.com/explore/wellness?project_type=campaign&amp;project_timing=all&amp;tags=&amp;sort=trending') show_more = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//div[@class="text-center"]/a')) ) while True: try: show_more.click() except TimeoutException: break filename = 'test.txt' with open(filename, 'wb') as datafile: datafile.write('asdfsdf') print(driver.page_source) driver.close() The issue is that the break seemingly breaks out of the entire script instead of just the while loop. In other words, if I move with open above the while loop, it does create the file. Why is that the case?!
has comment: http://stackoverflow.com/comment/89027283
has comment: http://stackoverflow.com/comment/89027467
has comment: http://stackoverflow.com/comment/89027484
has answer: http://stackoverflow.com/a/51017614
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89027334
has comment: http://stackoverflow.com/comment/89027355
score: 1
has comment: http://stackoverflow.com/comment/89027431
has comment: http://stackoverflow.com/comment/89027493
has comment: http://stackoverflow.com/comment/89027253
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89027557
has comment: http://stackoverflow.com/comment/89027411

http://stackoverflow.com/a/51153885
answers question: http://stackoverflow.com/q/51153612
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51153612
has comment: http://stackoverflow.com/comment/89299284
type: Answer
has comment: http://stackoverflow.com/comment/89325860
has body: Instead of trying to work with the whole page and get the value from the html table data in the table, it would be much easier if you just called the API with the right parameters. The API is the following : https://www.eex.com/data//view/data/detail/ws-power-futures-austrian-v1/{year}/{month}.{day}.json Example : https://www.eex.com/data//view/data/detail/ws-power-futures-austrian-v1/2018/06.07.json It fetches a JSON, then you can manipulate the data inside it as you want, you can basically build your data frame with the appropriate values using pandas. Seems an easier solution than looking directly into the page and you won't have any problems with your values. Here are some links that may help you read a JSON : Parsing JSON : Parsing values from a JSON file? JSON to pandas DF : JSON to pandas DataFrame UPDATE : I wrote a chunk of code that should help you get the idea : from urllib.request import Request, urlopen import json request=Request('https://www.eex.com/data//view/data/detail/ws-power-futures-austrian-v1/2018/06.07.json') response = urlopen(request) data = response.read() d = json.loads(data) # this first obj corresponds to : P-Power-F-AT-Peak-Quarter first_obj = d["data"][0]["rows"] values = [] for row in first_obj: if('settlementPrice' in row["data"]): sp = row["data"]["settlementPrice"] values.append(sp) print(values) The JSON fetched looked like this : { "data": [ { "identifier": "P-Power-F-AT-Peak-Quarter", "rows": [ { "data" : {'param1': value, 'param2': value, ...}, "contractIdentifier": value, }, { "data" : {'param1': value, 'param2': value, ...}, "contractIdentifier": value, }, ... ] }, { "identifier": "P-Power-F-AT-Peak-Month", "rows": [ { "data" : {'param1': value, 'param2': value, ...}, "contractIdentifier": value, }, { "data" : {'param1': value, 'param2': value, ...}, "contractIdentifier": value, }, ... ] }, { "identifier": "P-Power-F-AT-Base-Year", "rows": [ { "data" : {'param1': value, 'param2': value, ...}, "contractIdentifier": value, }, …
upvote count: 2
has comment: http://stackoverflow.com/comment/89320980

http://stackoverflow.com/comment/89174745
type: QuestionComment
type: Comment
has text: Looks like this bug: https://bugs.python.org/issue25457
comment on: http://stackoverflow.com/q/51093268
score: 0

http://stackoverflow.com/q/51076116
tagged with: opencv
has comment: http://stackoverflow.com/comment/89170363
type: UnansweredQuestion
answer count: 0
has title: OpenCV(3.4.1) Error: Assertion failed (type == src2.type() && src1.cols == src2.cols && (type == 5 || type == 0)) in cv::batchDistance,
linked to: http://stackoverflow.com/q/39940766
type: Question
has body: What is this? Can anyone tell me? Please?? # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=False) # Match descriptors. matches = bf.match(des1,des2) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) # Draw first 10 matches. img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10],None, flags=2)
tagged with: python
tagged with: sift
score: 0
has comment: http://stackoverflow.com/comment/89142269
has comment: http://stackoverflow.com/comment/89141348
has comment: http://stackoverflow.com/comment/89142943

http://stackoverflow.com/q/51118801
has body: i am very new in python (and programming in general) and here is my issue. i would like to replace (or delete) a part of a string from a txt file which contains hundreds or thousands of lines. each line starts with the very same string which i want to delete. i have not found a method to delete it so i tried a replace it with empty string but for some reason it doesn't work. here is what i have written: file = "C:/Users/experimental/Desktop/testfile siera.txt" siera_log = open(file) text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |" for each_line in siera_log: new_line = each_line.replace("text_to_replace", " ") print(new_line) when i print it to check if it was done, i can see that the lines are as they were before. no change was made. can anyone help me to find out why?
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51118880
score: -1
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51118835
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89223615
has title: how to replace (or delete) a part of string from txt file in python

http://stackoverflow.com/a/51053248
has body: try this df = df.set_index('id') df =df.apply(lambda x: "(" + x['categories'] + ")" + x['products'],axis=1).to_frame('products') print df
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89097571
has comment: http://stackoverflow.com/comment/89097586
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51053185
answers question: http://stackoverflow.com/q/51053185
downvote count: 1
has comment: http://stackoverflow.com/comment/89097549
score: 0

http://stackoverflow.com/q/51111626
has title: Byte order for 4 channel Bitmap to feed into Tensorflow frozen model
tagged with: android
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/69602571
has body: I'm trying to get an Android Bitmap into the same format I fed into my Tensorflow model in python. Here's how it is done originally in the TensorFlowObjectDetectionAPIModel: bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); for (int i = 0; i &lt; intValues.length; ++i) { byteValues[i * 3 + 2] = (byte) (intValues[i] &amp; 0xFF); byteValues[i * 3 + 1] = (byte) ((intValues[i] &gt;&gt; 8) &amp; 0xFF); byteValues[i * 3] = (byte) ((intValues[i] &gt;&gt; 16) &amp; 0xFF); } There are a few issues with doing this for a 4 channel (RGBD) Bitmap. From what I understand, Bitmap.setPreMultiplied has to be set to false in order for the Bitmap to not treat the 4th channel as Alpha info, multiplying it to the other three channels. This is what I thought the solution would be intuitively (assuming Bitmap.setPreMultiplied(false): bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); //grabbing the 4 channels into 4 consecutive values of byteValues for (int i = 0; i &lt; intValues.length; ++i) { byteValues[i * 4 + 2] = (byte) (intValues[i] &amp; 0xFF); byteValues[i * 4 + 1] = (byte) ((intValues[i] &gt;&gt; 8) &amp; 0xFF); byteValues[i * 4] = (byte) ((intValues[i] &gt;&gt; 16) &amp; 0xFF); byteValues[i * 4 + 3] = (byte) ((intValues[i] &gt;&gt; 24) &amp; 0xFF); } However, loading the exact same RGB and Depth Image I use in python, I get different (bad) recognition results. But in order to create the tf.record file, I had to modify the way the image was saved, pulling from two files as shown here: image = cv2.imread(full_path)[:, :, ::-1] print(image.tostring()) background = cv2.imread(full_path.replace('JPEG', 'Depth').replace('R', 'D').replace('jpg', 'png'), 0) background = np.reshape(background, (480,320,1)) # Image and background are numpy arrays that has dimension of H x W x 3 and H x W x 1 # Concatenate them on depth channel to create an H x W x 4 input inputs_stacked = np.concatenate([image, bac…
tagged with: java
upvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89274426
type: Comment
has text: thanks for the response. My assumption is that writing to an excel workbook needs data in form of a tuple (though I could be wrong). I was just following along with the docs. I do plan on having the data get large and I realize it probably wouldn't be best to constantly be creating new tuples. I do not know how to do generators but it is on my bucket list of things to learn so no better time like the present I guess. I will start there. Thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/51144853
score: 0

testing
tags question: http://stackoverflow.com/q/51147008
tag name: testing
tags question: http://stackoverflow.com/q/51085101
tags question: http://stackoverflow.com/q/51085665
type: Tag
tags question: http://stackoverflow.com/q/51017249
tags question: http://stackoverflow.com/q/51144062
tags question: http://stackoverflow.com/q/51066880
tags question: http://stackoverflow.com/q/51166326

http://stackoverflow.com/q/51090876
type: Question
has comment: http://stackoverflow.com/comment/89170588
answer count: 3
possible better answer: http://stackoverflow.com/a/51091398
has answer: http://stackoverflow.com/a/51091398
accepted answer: http://stackoverflow.com/a/51091857
has comment: http://stackoverflow.com/comment/89170288
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51091130
tagged with: pandas
has comment: http://stackoverflow.com/comment/89170788
tagged with: python
has comment: http://stackoverflow.com/comment/89170442
has title: Plotting data with categorical x and y axes in python
upvote count: 3
tagged with: seaborn
has comment: http://stackoverflow.com/comment/89170433
has comment: http://stackoverflow.com/comment/89170247
has answer: http://stackoverflow.com/a/51091857
type: AnsweredQuestion
tagged with: matplotlib
downvote count: 3
has body: I have a list of case and control samples along with the information about what characteristics are present or absent in each of them. A dataframe including the information can be generated by Pandas: import pandas as pd df={'Patient':[True,True,False],'Control':[False,True,False]} # Presence/absence data for three genes for each sample df=pd.DataFrame(df) df=df.transpose() df.columns=['GeneA','GeneB','GeneC'] I need to visualize this data as a dotplot/scatterplot in the way that both of the x and y axis to be categorical and presence/absence to be coded by different shapes. Something like following: Patient| x x - Control| - x - __________________ GeneA GeneB GeneC I am new to Matplotlib/seaborn and I can plot simple line plots and scatter plots. But searching online I could not find any instructions or plot similar to what I need here.

http://stackoverflow.com/comment/89249808
has text: I am having problem when i want to open cellname.rpt as they could not find the directory. This is because directory test and library are in same level. However, from my script, the script thought that library is one level down after test. Error: workspace/test/../library/ce_clk.rpt. The actual location is workspace/library/ce_clk.rpt.
comment on: http://stackoverflow.com/a/51132060
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89054738
has text: You could compile each piece of the regex separately so they're more manageable, and then join them together as in this answer: https://stackoverflow.com/questions/22102814/pythonic-way-to-concatenate-regex-objects
score: 1
comment on: http://stackoverflow.com/q/51031139
type: QuestionComment
type: Comment

http://stackoverflow.com/a/56786144
has body: Ya their is a bug when you predict from model with keras. Keras will not be able to build graph due to some error. Try to predict images from model with the help of tensor flow. Just replace this line of code Keras code: features = model_places.predict( img ) tensorflow code: import tensorflow as tf graph = tf.get_default_graph() import this library in your code and replace. with graph.as_default(): features = model_places.predict( img ).tolist() If Problem still not solved : if still problem not solved than try to refresh the graph. As your code is fine, running with a clean environment should solve it. Clear keras cache at ~/.keras/ Run on a new environment, with the right packages (can be done easily with anaconda) Make sure you are on a fresh session, keras.backend.clear_session() should remove all existing tf graphs. Keras Code: keras.backend.clear_session() features = model_places.predict( img ) TensorFlow Code: import tensorflow as tf with tf.Session() as sess: tf.reset_default_graph()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51127344

http://stackoverflow.com/a/51158942
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/51158770
type: Answer
accepted answer of: http://stackoverflow.com/q/51158770
has body: str() returns '' every time. So fruit is always '' which doesn't satisfy any of the if statements. Also your if statements are off. You can just check if fruit is in favorite_fruits and then print: fruit = "mango" favorite_fruits = ["mango", "kiwi", "pineapple"] if fruit in favorite_fruits: print('You really like ' + fruit + '.') else: print('Your going to starve.') If you want user input then use input instead of hard coding fruit.

http://stackoverflow.com/comment/100243035
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56749404
score: 0
has text: what OS are you using?

tensorflow
tags question: http://stackoverflow.com/q/51119874
tags question: http://stackoverflow.com/q/51132991
tags question: http://stackoverflow.com/q/51155881
tags question: http://stackoverflow.com/q/51028324
tags question: http://stackoverflow.com/q/51055426
tags question: http://stackoverflow.com/q/51042721
tags question: http://stackoverflow.com/q/51146597
tags question: http://stackoverflow.com/q/51100054
tags question: http://stackoverflow.com/q/51049890
tags question: http://stackoverflow.com/q/51018233
tags question: http://stackoverflow.com/q/51107509
tags question: http://stackoverflow.com/q/51051176
tags question: http://stackoverflow.com/q/51115454
tags question: http://stackoverflow.com/q/51146217
tags question: http://stackoverflow.com/q/51019509
tags question: http://stackoverflow.com/q/51143639
tags question: http://stackoverflow.com/q/51108765
tags question: http://stackoverflow.com/q/51054482
tags question: http://stackoverflow.com/q/51061182
tags question: http://stackoverflow.com/q/51049566
tags question: http://stackoverflow.com/q/51088830
tags question: http://stackoverflow.com/q/51052420
tags question: http://stackoverflow.com/q/51064323
tags question: http://stackoverflow.com/q/51143210
tags question: http://stackoverflow.com/q/51046450
tags question: http://stackoverflow.com/q/51151941
tags question: http://stackoverflow.com/q/51062096
tags question: http://stackoverflow.com/q/51074006
tags question: http://stackoverflow.com/q/51144993
tags question: http://stackoverflow.com/q/51118032
tags question: http://stackoverflow.com/q/51016069
tags question: http://stackoverflow.com/q/51157904
tags question: http://stackoverflow.com/q/51144083
tags question: http://stackoverflow.com/q/51030924
tags question: http://stackoverflow.com/q/51131821
tags question: http://stackoverflow.com/q/51105062
tags question: http://stackoverflow.com/q/51087335
tags question: http://stackoverflow.com/q/51016504
tags question: http://stackoverflow.com/q/51071994
tags question: http://stackoverflow.com/q/51067176
tags question: http://stackoverflow.com/q/51045781
tags question: http://stackoverflow.com/q/51118926
tags question: http://stackoverflow.com/q/51047676
tags question: http://stackoverflow.com/q/51163871
tags question: http://stackoverflow.com/q/51148876
tags question: http://stackoverflow.com/q/51161990
tags question: http://stackoverflow.com/q/51160343
tags question: http://stackoverflow.com/q/51148385
tags question: http://stackoverflow.com/q/51146348
tags question: http://stackoverflow.com/q/51069945
tags question: http://stackoverflow.com/q/51076475
tags question: http://stackoverflow.com/q/51095124
tags question: http://stackoverflow.com/q/51016803
tags question: http://stackoverflow.com/q/51157813
tags question: http://stackoverflow.com/q/51063631
tags question: http://stackoverflow.com/q/51158399
tags question: http://stackoverflow.com/q/51114771
tags question: http://stackoverflow.com/q/51038373
tags question: http://stackoverflow.com/q/51140276
tags question: http://stackoverflow.com/q/51056479
tags question: http://stackoverflow.com/q/51081166
tags question: http://stackoverflow.com/q/51015897
tags question: http://stackoverflow.com/q/51110110
tags question: http://stackoverflow.com/q/51151969
tags question: http://stackoverflow.com/q/51161751
tags question: http://stackoverflow.com/q/51046867
tags question: http://stackoverflow.com/q/51023367
tags question: http://stackoverflow.com/q/51121885
tags question: http://stackoverflow.com/q/51017483
tags question: http://stackoverflow.com/q/51127344
tags question: http://stackoverflow.com/q/51108486
tags question: http://stackoverflow.com/q/51011920
tags question: http://stackoverflow.com/q/51031691
tags question: http://stackoverflow.com/q/51122171
tags question: http://stackoverflow.com/q/51153046
tags question: http://stackoverflow.com/q/51070935
tag name: tensorflow
tags question: http://stackoverflow.com/q/51091106
tags question: http://stackoverflow.com/q/51033775
tags question: http://stackoverflow.com/q/51100057

http://stackoverflow.com/comment/100279356
type: Comment
has text: just notice that for windows I didn't add the \filetypes folder in the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/56749404

http://stackoverflow.com/a/51109190
upvote count: 5
downvote count: 0
has body: As pointed out in Type Conversions, Python's dict objects become named lists in R. So, to access the equivalent of "dictionary keys" in R you would use names: ```{r} names(py$fruits) ``` ## [1] "melon" "apple" "banana" You may choose to convert the result back to a dict-like object using reticulate::dict(). The resulting object would then function as you want: ```{r} reticulate::dict( py$fruits ) ``` ## {'melon': 7, 'apple': 53, 'banana': None} ```{r} reticulate::dict( py$fruits )$keys() ``` ## ['melon', 'apple', 'banana']
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51108722
score: 5
type: Answer
answers question: http://stackoverflow.com/q/51108722

http://stackoverflow.com/comment/89303993
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51160152
has text: Matt ('s Mug), ok, go ahead and always run it under admin as I always do.
score: 0

http://stackoverflow.com/q/51158248
type: Question
tagged with: numpy
tagged with: avx
score: 0
linked to: http://stackoverflow.com/q/45770089
has comment: http://stackoverflow.com/comment/89327784
linked to: http://stackoverflow.com/q/8902971
has body: My project are heavily using logsumexp in the algorithm. Currently I'm using this library https://github.com/rmcgibbo/logsumexp , which is implemented in SSE instruction set. However, modern Intel CPU has much powerful AVX instruction sets. Hence, I would like to know if there's any faster logsumexp implementation by AVX or even CUDA for Python? Thank you.
tagged with: python
linked to: http://stackoverflow.com/q/48863719
has comment: http://stackoverflow.com/comment/89310346
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: Any LogSumExp for Python implemented by AVX?

http://stackoverflow.com/q/51091250
answer count: 2
has comment: http://stackoverflow.com/comment/89171321
downvote count: 0
possible better answer: http://stackoverflow.com/a/51092378
has title: Python, os.system and subprocess.call both don't work for variable string command
has answer: http://stackoverflow.com/a/51092378
tagged with: os.system
has answer: http://stackoverflow.com/a/51391450
favorite count: 0
has comment: http://stackoverflow.com/comment/89199418
has comment: http://stackoverflow.com/comment/89181187
upvote count: 2
accepted answer: http://stackoverflow.com/a/51391450
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89171128
tagged with: subprocess
type: Question
has body: I'm trying to issue a command to another application using python, but it seems to only acknowledge part of the command. Here are the lines of code in question: command = 'potreeconverter {} -q NICE -p {} –o {}\{}\{}\{}'.format(path,folder,pathup[0],cid,wpid,folder) print (command) os.system(command) I'm fairly new to Python so forgive me if that's a weird way to construct a string for a directory name containing many variables. However, the print function always returns the exact command that I intended, and it will run as intended if I simply copy and paste it into the command prompt manually. potreeconverter C:\Users\thomas\source\test.las -q NICE -p test –o C:\Users\thomas\source\55555\55555\test The command is accepted by the application, but it ignores the -o parameter, which specifies an output directory for the application. It does the same thing if I use subprocess.call. No other part of the command is ever ignored. I read that this issue can be solved by having python write the command to a batch file, and then sending the batch file through. I would really rather not do that because it would be pretty inefficient. Is there another way that anyone knows of to avoid this? Also, I'm unsure what this means but I thought it was odd and perhaps significant. When this problem occurs, and only when this problem occurs, the default output directory that the program chooses instead of the one I specified will use forward slashes instead of backslashes.

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51035619
tags question: http://stackoverflow.com/q/51105887
tag name: kivy-language
tags question: http://stackoverflow.com/q/51032986
tags question: http://stackoverflow.com/q/51039775
tags question: http://stackoverflow.com/q/51167248

http://stackoverflow.com/q/51144485
linked to: http://stackoverflow.com/q/3038459
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89275711
has comment: http://stackoverflow.com/comment/89275531
tagged with: pythonanywhere
upvote count: 0
tagged with: django-templates
tagged with: django-views
has body: Erorr I wanna know where django search for index.html Setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py def index(request): return render(request, 'index.html', {})
tagged with: django
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89275474
has title: TemplateDoesNotExist Error in Pythonanywhere
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/51145438
favorite count: 0
has comment: http://stackoverflow.com/comment/89275215
has answer: http://stackoverflow.com/a/67148921
has answer: http://stackoverflow.com/a/57688679

http://stackoverflow.com/comment/89256858
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51136248
type: Comment
has text: Can you please help me to understand how to add the extra columns(like in my case the key) to the result. Also in For loop range(0,2) what does this 2 mean, are they the number of keys?

http://stackoverflow.com/q/51089821
tagged with: python
has comment: http://stackoverflow.com/comment/119754144
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
has body: I'm trying to create a database using an example of an object from python, but I'm getting errors messages like: "AttributeError: 'Eu' object has no attribute 'translate'" I have no idea how to fix that sorry guys my english is not very good here's my code: import pymysql.cursors class Eu: def __init__(self, nome='mel', idade=22): self.nome = nome self.idade = idade eu = Eu() nome = eu.nome idade = eu.idade # connect do database conn = pymysql.connect(host='localhost', user='root', password='') # create a cursor and a database conn.cursor().execute('CREATE DATABASE banco73') conn.cursor().execute('USE banco73') # create tables conn.cursor().execute('CREATE TABLE tabela73 (eu BLOB)') # use tables conn.cursor().execute("""INSERT INTO tabela73 VALUES (?)""", (eu)) the entire console message: runfile('C:/Users/Usuario/.spyder-py3/temp.py', wdir='C:/Users/Usuario/.spyder-py3') Traceback (most recent call last): File "&lt;ipython-input-59-9994dddea11c&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Usuario/.spyder-py3/temp.py', wdir='C:/Users/Usuario/.spyder-py3') File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Usuario/.spyder-py3/temp.py", line 36, in &lt;module&gt; conn.cursor().execute("""INSERT INTO tabela73 VALUES (?)""", (eu)) File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 168, in execute query = self.mogrify(query, args) File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 147, in mogrify query = query % self._escape_args(args, conn) File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 133, in _escape_args return conn.escape(args) File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\connections.py", line 839, in esca…
accepted answer: http://stackoverflow.com/a/51090264
type: Question
tagged with: object
score: 3
possible better answer: http://stackoverflow.com/a/71804151
tagged with: mysql
tagged with: class
has answer: http://stackoverflow.com/a/51090264
has answer: http://stackoverflow.com/a/71804151
answer count: 2
has comment: http://stackoverflow.com/comment/89168584
downvote count: 0
favorite count: 0
has title: How can I save an python object on a MySQL database?

http://stackoverflow.com/q/51063282
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/74135929
tagged with: python
tagged with: statsmodels
tagged with: forecast
tagged with: facebook-prophet
upvote count: 1
has body: I'm new to learning python, and I'm creating a time series model which predicts total sales each month using the Prophet model. I am needing help getting the RMSE of my model! Thanks! from fbprophet import Prophet #Creating Dataframe# proph = train.groupby(['date_block_num'])[ 'item_cnt_day'].sum() proph.index=pd.date_range(start='2013-01-01', end='2015-10-01', freq='MS') proph = proph.to_frame().reset_index() proph.columns = ['ds', 'y'] proph.head() #Modelling# model=Prophet(yearly_seasonality=True) model.fit(proph) model.head() #Making future predictions future_data = model.make_future_dataframe(periods=1, freq='MS') forecast = model.predict(future_data) forecast'ds', 'yhat', 'yhat_lower', 'yhat_upper'.tail()
type: Question
tagged with: time-series
has answer: http://stackoverflow.com/a/52149785
has title: Calculating RMSE for Prophet Model in Python
answer count: 2
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51143537
score: 0
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
tagged with: pandas-datareader
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/50394873
has comment: http://stackoverflow.com/comment/89271677
has body: Here is my code. Please see the code and tell me what is not correct in this code and tell me the solution. import pandas_datareader.data as web import datetime start = datetime.datetime(2015, 1, 1) end = datetime.datetime(2018, 2, 8) df = web.DataReader('TSLA', 'google', start, end) print(df.head()) This is the exception: C:\Users\Sales\Desktop\Chart\venv\Scripts\python.exe C:/Users/Sales/Desktop/Chart/charts/chart1.py C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\google\daily.py:40: UnstableAPIWarning: The Google Finance API has not been stable since late 2017. Requests seem to fail at random. Failure is especially common when bulk downloading. warnings.warn(UNSTABLE_WARNING, UnstableAPIWarning) Traceback (most recent call last): File "C:/Users/Sales/Desktop/Chart/charts/chart1.py", line 8, in <module> df = web.DataReader('TSLA', 'google', start, end) File "C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\data.py", line 315, in DataReader session=session).read() File "C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\base.py", line 206, in read params=self._get_params(self.symbols)) File "C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\base.py", line 84, in _read_one_data out = self._read_url_as_StringIO(url, params=params) File "C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\base.py", line 95, in _read_url_as_StringIO response = self._get_response(url, params=params) File "C:\Users\Sales\Desktop\Chart\venv\lib\site-packages\pandas_datareader\base.py", line 155, in _get_response raise RemoteDataError(msg) pandas_datareader._utils.RemoteDataError: Unable to read URL: https://finance.google.com/finance/historical?q=TSLA&startdate=Jan+01%2C+2018&enddate=Feb+08%2C+2018&output=csv Response Text: b' Sorry... Google Sorry... We\'re sorry... ... but your computer or network may be sending automated queries. To protect our users, we can\'t process your request righ…
answer count: 0
downvote count: 1
type: Question
has title: I'm getting unstable API warning and also getting error 'pandas_datareader._utils.RemoteDataError: Unable to read URL:'
has comment: http://stackoverflow.com/comment/89271347
linked to: http://stackoverflow.com/q/50394873

http://stackoverflow.com/comment/123503755
type: Comment
comment on: http://stackoverflow.com/a/61480946
score: 1
has text: If anyone's interested, also @MartinCR, I came up with a metaclass approach which is inspired in part by this post. I've determined it to be very efficient, because it generates a `__post_init__` which only runs an initial time to set up properties so it plays well with dataclasses. You can find it in the [gist here](https://gist.github.com/rnag/d14b05680094b871935a9a30d43d5c0d).
type: AnswerComment

http://stackoverflow.com/a/53898818
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/110009577
answers question: http://stackoverflow.com/q/51124878
upvote count: 14
has comment: http://stackoverflow.com/comment/110006101
downvote count: 1
has body: ~~Unfortunately, Pycharm does not currently support Groovy/Jenkinsfile syntax highlighting.~~ Please see the other answers on this thread to check if groovy support is discovered or added for PyCharm. While this does not officially answer your question it does provide a workaround for those who are interested. Install IntelliJ IDEA, the community edition can be downloaded free from intelliJ Once installed, open File--&gt;Settings--&gt;Editor--&gt;File Types--&gt;Groovy and you can associate Jenkinsfile with the Groovy syntax by adding 'Jenkinsfile*' to the Groovy 'Registered patterns': A word to the wise: Don't open the Jenkinsfile directly in your Pycharm project with IDEA. It will start writing to the '.idea' folder and cause conflicts with the pyCharm IDE. I like to symlink/softlink my Jenkinsfile into a subdirectory of a folder called 'jenkinsfiles'. So if I have a project called ProjectA I symlink the Jenkins file to ..path../jenkinsfiles/ProjectA/Jenkinsfile. I then open ..path../jenkinsfiles/ in IDEA and can manage all the Jenkinsfiles for all my projects from there. lately I have been enjoying the free https://code.visualstudio.com/ which has a groovy plugin https://marketplace.visualstudio.com/items?itemName=marlon407.code-groovy.

srtm
tags question: http://stackoverflow.com/q/51076943
tag name: srtm
type: Tag

http://stackoverflow.com/comment/89181898
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51080159
has text: That would require a wrapper transaction on each connection, but that should be relatively easy once you have the single connection mechanism figured out.

http://stackoverflow.com/comment/89156077
type: QuestionComment
type: Comment
score: 0
has text: So you have two models? Can you share the models? Do they share al/most) fields?
comment on: http://stackoverflow.com/q/51083887

http://stackoverflow.com/q/51143201
tagged with: django
has title: Error while removing a div with a particular id using BeautifulSoup
has comment: http://stackoverflow.com/comment/89270851
type: Question
has comment: http://stackoverflow.com/comment/89283155
has comment: http://stackoverflow.com/comment/89270705
has comment: http://stackoverflow.com/comment/89270955
has comment: http://stackoverflow.com/comment/89270871
has comment: http://stackoverflow.com/comment/89272951
has body: I am trying to remove a div with a particular id using BeautifulSoup. Code snippet: from django import template from bs4 import BeautifulSoup register = template.Library() @register.filter(name='reset_html_styles') def reset_html_styles(value): # value = ' Some paragraph ' soup = BeautifulSoup(value, 'html5lib') soup.find('div', id='divRplyFwdMsg').decompose() return str(soup) which is giving me this error output: Error: 'NoneType' object has no attribute 'decompose' I faced no problem while removing divs using class names. I'm using python 3.6.5, django 2.0 and beautifulsoup4 4.6.0 version.
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89271088
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89279528
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89270897
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51088997
score: 2
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51089712
type: AnsweredQuestion
tagged with: global-variables
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51089091
downvote count: 0
possible better answer: http://stackoverflow.com/a/51089712
has body: So, what i'm trying to do is use the python interpreter as sort of a CLI for my server side python app. However, I'm getting a behavior i didn't expect in the loading of python modules. I have two python files and a cache file: Main.py Config.py Cache.json So what happens is that when Main is imported and ran, the main() function imports Configs and then calls a function to initialize Config. When initialized Config loads some global variables from Cache.json depending on the environment i'm running in. Here's a simplified example of the .py 's. #Main.py import Config def main(): """Initialize Python Application""" Config.init() if __name__ == "__main__": main() #Config.py import os import json Default_MSSQLPassword = "" Default_MSSQLUser = "" Default_OdbccDriver = "" MDGSQLP01 = "" def init(): """docstring""" with open("Cache.json", "r") as f: dtGlobalConstants = json.load(f) Default_MSSQLPassword = dtGlobalConstants["Default_MSSQLPassword"] Default_MSSQLUser = dtGlobalConstants["Default_MSSQLUser"] Default_OdbccDriver = dtGlobalConstants["Default_OdbccDriver"] MDGSQLP01 = dtGlobalConstants["MDGSQLP01"] Now theoretically if I call the below in the python interpreter: &gt;&gt;&gt;from Main import main &gt;&gt;&gt;main() Config should be imported by main(), persist, and I should be able to print the Cached value of Default_OdbccDriver that was loaded form Cache.json. But instead I get this: &gt;&gt;&gt;Config.Default_OdbccDriver &gt;&gt;&gt;'' So clearly Main is importing Config.py, because otherwise i'd get an error when calling property .Default_OdbccDriver . However, even though the value of Default_OdbccDriver is supposed to be "global" (according to python's odd definition of the word) it's value should be static and persist in the import cache. Anyone know what's going on or how to work around it? In the end, I want main() to initialize some values and expose some methods for working with my app, but this isn't a great start...
has title: Access global variables within python application from single import
has answer: http://stackoverflow.com/a/51089091
favorite count: 0

audacity
type: Tag
tags question: http://stackoverflow.com/q/51057369
tag name: audacity

http://stackoverflow.com/q/51132802
tagged with: lstm
type: Question
tagged with: keras
score: 0
has comment: http://stackoverflow.com/comment/89250404
tagged with: python
tagged with: quandl
has comment: http://stackoverflow.com/comment/89253720
answer count: 0
has title: LSTM neural network for multiple steps time series prediction
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89250264
tagged with: tensorflow
has body: I tried to develop a model that foresees two time-steps forward In this regard I modified a GitHub code for the single step forecast coding a data_load function that takes n steps backward in the X_train/test series and set it against a y_train/test 2-array. I set the neurons list to output in Dense a 2-vector object. And last I wrote a predict function and a plot function for the 2-step-forecast. I do not normalized features lables and forecasts I will do in the future. After a bit of hyperfine tuning it returns a good score for the mse and rmse: Train Score: 0.00000 MSE (0.00 RMSE) Test Score: 0.00153 MSE (0.04 RMSE) It can find quite well the trend, but it returns all forecasts with negative directions. Does anyone have a suggestion? import seaborn as sns import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt2 import pandas as pd from pandas import datetime import math, time import itertools from sklearn import preprocessing import datetime from sklearn.metrics import mean_squared_error from math import sqrt from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.recurrent import LSTM from keras.models import load_model import keras from numpy import newaxis pd.core.common.is_list_like = pd.api.types.is_list_like import pandas_datareader.data as web import h5py from keras import backend as K import quandl quandl.ApiConfig.api_key = 'myQuandlKey' seq_len = 2 shape = [seq_len, 9, 2] neurons = [256, 256, 64, 2] dropout = 0.2 decay = 0.5 epochs = 100 stock_name = 'AAPL' global_start_time = time.time() def get_stock_data(stock_name, normalize=True, ma=[]): """ Return a dataframe of that stock and normalize all the values. (Optional: create moving average) """ df = quandl.get_table('WIKI/PRICES', ticker = stock_name) df.drop(['ticker', 'open', 'high', 'low', 'close', 'ex-dividend', 'volume', 'split_ratio'], 1, inplace=True) df.set_index('date', inplace=True) # Renaming all the columns so…
has comment: http://stackoverflow.com/comment/89255388

comparison
tags question: http://stackoverflow.com/q/51088935
tag name: comparison
tags question: http://stackoverflow.com/q/51096552
tags question: http://stackoverflow.com/q/51031822
type: Tag
tags question: http://stackoverflow.com/q/51053402

http://stackoverflow.com/a/71238634
answers question: http://stackoverflow.com/q/51036394
upvote count: 2
has body: First of all on connection define charset, if it is not UTF-8, next, nvarchar and varchar. nvarchar stored utf-8, varchar not. In my case, (i have this and this on table) I connect: conn = pymssql.connect(host='xxx', user='xxx', password='xxx', database='xxx',charset='CP1250') cur = conn.cursor(as_dict=True) and in query must convert nvarchar to varchar: cur.execute( """SELECT convert(varchar, column) as column FROM table """)
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/89159229
type: Comment
score: 1
type: AnswerComment
has text: I actually figured out issue the tabula-py module was installed on python 3 while I was working with python 2.7 so once I changed the version on python the code ran, not with much success however.
comment on: http://stackoverflow.com/a/51069057

http://stackoverflow.com/q/51130535
accepted answer: http://stackoverflow.com/a/51316864
score: 1
tagged with: http-headers
has comment: http://stackoverflow.com/comment/89393769
type: Question
linked to: http://stackoverflow.com/q/45192108
answer count: 2
downvote count: 0
favorite count: 0
tagged with: azure-devops-rest-api
tagged with: token
has comment: http://stackoverflow.com/comment/89391629
tagged with: python
possible better answer: http://stackoverflow.com/a/51147627
has body: I am trying to use API of VSTS 5.0, but I get 203 when I try to use Token with python. headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'X-Requested-With':'XMLHttpRequest', 'Authorization': b'Basic '+ base64.b64encode(personal_access_token.encode('utf-8')), 'content-type': 'application/json',} def get_page_list(): url = 'https://{account}.visualstudio.com/DefaultCollection/_apis/projects' try: response = requests.get(url, headers=headers, verify = False) print (response.status_code) if response.status_code == 200: return response.json() except requests.ConnectionError as e: print('Error*****', e.args) if __name__ == '__main__': json = get_page_list() print(json) And this will return to this: 203 None I really can't understand what is going wrong.
has answer: http://stackoverflow.com/a/51147627
tagged with: azure-devops
has title: Using Token to get authorized for VSTS API, but status.code = 203
has answer: http://stackoverflow.com/a/51316864
upvote count: 1
has comment: http://stackoverflow.com/comment/89581495
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/100798371

http://stackoverflow.com/a/63073890
answers question: http://stackoverflow.com/q/51030131
score: 0
type: Answer
has body: From the Python LDAP documentation you can see that it requires a series of packages in order to get a proper installation (pre-build requisites). The commands you need to run, depends on the OS. Sadly, this is intended for Linux based OS's. I hope it helps! Cheers

http://stackoverflow.com/q/51017845
has comment: http://stackoverflow.com/comment/89062156
answer count: 0
score: 1
tagged with: duration
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89028253
tagged with: spyder
has body: I have a vehicle monitoring log file which consist of the following fields: Index, Timestamp(date time), lat, long, mode(denote as 0,2,4), vehicle model(denote as x,y and z) . The whole idea of the program is split into 2 part Is to capture the time when the mode field switch to each and every mode. By using the capture timing to calculate the total duration each vehicle stays in their mode. . 1,2016-05-02 09:14:32.242, lat, long, 2, x 2,2016-05-02 09:14:37.341, lat, long, 2, x 3,2016-05-02 09:14:39.142, lat, long, 2, x 4,2016-05-02 09:14:42.736, lat, long, 2, x 5,2016-05-02,09:14:48.212, lat, long, 0, x //Capturing this timing for X 6,2016-05-02,09:14:52.222, lat, long, 0, x 7,2016-05-02,09:14:56.335, lat, long, 2, x //Capturing this timing for X 8,2016-05-02,09:14:58.242, lat, long, 2, x 9,2016-05-02,09:15:01.742, lat, long, 2, y 10,2016-05-02,09:15:03.862, lat, long, 2, x 11,2016-05-02,09:15:13.277, lat, long, 2, y 12,2016-05-02,09:15:24.436, lat, long, 2, y 13,2016-05-02,09:15:32.211, lat, long, 0, y //capturing this timing for Y The end state of the program is to be able to calculate the total duration of each vehicle in each mode. Please advice on any methods to tackle such issue. Sorry if this is a duplicate question as i do not know what exact topic or heading such question belongs. . Im currently using Spyder IDE and need someone to point me a direction to research on! Thank you! P.S. As the data are confidential, these are just some test data without the actual lat long input import pandas as pd import numpy as np import csv from tkinter import * from tkinter import messagebox from tkinter import ttk from itertools import groupby import datetime def get_data(event): x = str1Var.get() y = str2Var.get() mydataset = pd.read_csv(x + '.txt') print (mydataset.shape) mydataset.sort_values([1,0]) print(mydataset) mydataset.to_csv(y +'.txt') As of now, I've only done reading file and sorting it with respect to the time. Still looking for logic and method to explore…
downvote count: 0
favorite count: 0
has title: Capturing changes in field in python
type: UnansweredQuestion
tagged with: python
tagged with: calculation

http://stackoverflow.com/comment/89115837
comment on: http://stackoverflow.com/a/51049753
type: AnswerComment
has text: So as I understand the `def h(g):` is currently performing ffill() on all columns other than the ones specified in `assign`, how can I exclude some columns from having anything done on them.
score: 0
type: Comment

http://stackoverflow.com/q/51022244
tagged with: alarms
favorite count: 0
has answer: http://stackoverflow.com/a/51029876
tagged with: notifications
tagged with: python
accepted answer: http://stackoverflow.com/a/51029876
downvote count: 1
type: AnsweredQuestion
has body: I am running an etcd cluster in my machine. I have added three members too. Is it possible to generate the an alarm/notification based on the condition that cluster is healthy/not-healthy and is it possible to read some email-ids from a YAML file and send a mail to these ids. I am able to do it in GO but not in Python. I just want directions to some websites or maybe some code from where I can infer and start. The curl request is: curl -L http://127.0.0.1:2379/health And the output is: {"health":"true"} However there is another way through command-line: ./etcdctl cluster-health And the output is: member 8e9e05c52164694d is healthy: got healthy result from http://localhost:2379 cluster is healthy I want the second result, parse it and then put my conditions like wait and retry.
score: -1
tagged with: etcd
has title: Generate alarms and notifications and send mail based on a condition in Python
type: Question
upvote count: 0
tagged with: yaml
answer count: 1

http://stackoverflow.com/comment/89160206
has text: using timeit I collected different results. I'm still trying to understand why. However, my real goal was to improve efficiency about one order of magnitude. Don't know if it is possible
type: AnswerComment
comment on: http://stackoverflow.com/a/51067167
score: 0
type: Comment

http://stackoverflow.com/comment/89044367
type: Comment
type: QuestionComment
has text: Do you want to just get the count of `base`, `standard`, and `premium` products in one query?
comment on: http://stackoverflow.com/q/51025577
score: 0

http://stackoverflow.com/q/51083843
linked to: http://stackoverflow.com/q/42266737
tagged with: grid-search
type: Question
tagged with: pipeline
score: 2
has comment: http://stackoverflow.com/comment/89166228
downvote count: 0
tagged with: scikit-learn
has title: Efficiently using the combination of sklearn's pipeline and gridSearchCV
has body: I've only been using sklearn for a short period of time and I'm currently trying to build a pipeline together with GridSearchCV. To my knowledge, the pipeline is particularly useful if you want to combine a known sequence of transformations together with a final estimator and keep the associated cross-validation consistent. However, I would like to additionally use the pipeline for arbitrarily combining a set of preprocessing steps with a set of estimators. Assume, for example, that I have one preprocessing object (e.g. StandardScaler()) and two estimator objects (e.g. Lasso() and PLSRegression()). To account for different possible combinations of these objects (here: StandardScaler() AND Lasso()) OR (StandardScaler() AND PLSRegression())), I construct the pipeline and associated GridSearchCV object as follows: # Instantiate the pipeline with a sequence of steps pipe = Pipeline(steps=[('preprocessor',None), ('estimator',None)]) # Construct the parameter grid accounting for different combinations # of preprocessing and estimation steps params = [{ 'estimator': [Lasso()], 'estimator__alpha': [0.5, 1], 'preprocessor': [StandardScaler()], 'preprocessor__with_mean': [True, False] }, { 'estimator': [PLSRegression()], 'estimator__n_components': [1, 2], 'preprocessor': [StandardScaler()], 'preprocessor__with_mean': [True, False] }] # Instantiate GridSearchCV object gs = GridSearchCV(estimator=pipe, param_grid=params) I found this solution in an earlier post "Parallel" pipeline to get best model using gridsearch. However, I find it somewhat cumbersome since either I have to define all feasible combinations of pipeline steps by hand or I have to write a hacky function that does that job for me. Especially, in a context with much more preprocessing steps and a larger variety of estimators this is not what I want to do. Is there a different, more simple, way to evaluate different combinations of preprocessors and estimators, preferably within the pipeline/GridSearchCV construct…
tagged with: python
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/comment/89230880
has text: Have a look [here](https://pypi.org/project/savReaderWriter/).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51122781

http://stackoverflow.com/comment/89063845
comment on: http://stackoverflow.com/a/51035688
type: AnswerComment
has text: @j.stalin - added solution with dictionary
type: Comment
score: 1

http://stackoverflow.com/a/53508590
answers question: http://stackoverflow.com/q/51032985
has body: I think the easier answer is to use the DataFrame.query function which allows you to query the multi-index by name as follows: import pandas as pd import numpy as np index = pd.MultiIndex.from_arrays([list("aaabbb"), list("abcabc")], names=['i0', 'i1']) df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6], 'y': [6, 5, 4, 3, 2, 1]}, index=index) df.query('i0 == "b" | i1 == "b"') returns: x y i0 i1 a b 2 5 b a 4 3 b 5 2 c 6 1
score: 10
downvote count: 0
upvote count: 10
type: Answer

http://stackoverflow.com/comment/89262535
comment on: http://stackoverflow.com/a/51119424
has text: @dearn44 Yes, we would lose many possible combinations. But it looks like we get lots of solutions if the set size is large enough because the number of partitions of 2n items is 2nCn, e.g. if 2n=8 we get 70 partitions (see https://oeis.org/A000984). So we should make the subgroups as large as is practical. The total number of solutions produced this way (in terms of the Solution count that my code prints) is the product of the numbers of solutions for each subgroup times `2**(m-1)` where m is the number of subgroups. And each solution gives multiple team options.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51121265
has comment: http://stackoverflow.com/comment/89227944
has comment: http://stackoverflow.com/comment/89228077
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/19602187
has comment: http://stackoverflow.com/comment/89228393
has title: Separate data points into clusters and taking the mean of each cluster
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51121619
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51121619
tagged with: scipy
has comment: http://stackoverflow.com/comment/89228416
type: Question
tagged with: numpy
has body: Suppose I have some data in a 2x4 Matrix (4 data points, 2 features) X = np.array([[4,3,5,6], = [x1 x2 x3 x4] [7,4,6,5]]) A "closest" 3x4 matrix which indicates the closest cluster k to each data point x. (3 clusters, 4 data points) C = [[1 0 1 0] [0 0 0 1] [0 1 0 0]] I would like to find an efficient way using numpy to compute the mean of the data points in each cluster. My idea was to construct a matrix that would look like: idea = [[x1 0 x3 0 ] [0 0 0 x4] [0 x2 0 0 ]] Summing its elements across the columns and then dividing by the respective elements in np.sum(c,axis=1), since the mean should only take into account the data points that belong to that cluster (i.e. not the zeros). The final expected output with this example should be a 3x2 matrix: output = [(x1+x3)/2 = [ [4.5 6.5] x4 [6 5 ] x2 ] [3 4 ]] I wasn't even able to construct a matrix that looks like my idea matrix. I don't know if this is the most efficient one can do to solve this problem I want to avoid using any for-loops.
tagged with: k-means
downvote count: 0
answer count: 1

sprite
tags question: http://stackoverflow.com/q/51012308
type: Tag
tags question: http://stackoverflow.com/q/51123027
tag name: sprite
tags question: http://stackoverflow.com/q/51111462

http://stackoverflow.com/comment/89231474
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51122977
has text: Thanks for the advice @Braca but I just felt I had enough information to answer (just exactly the way I did). Should you need for info, just ask :)

http://stackoverflow.com/q/51095631
has comment: http://stackoverflow.com/comment/89179167
has answer: http://stackoverflow.com/a/51274259
has body: I read on Internet and Stack Overflow different articles on Annual Return vs Annualised Return vs CAGR and I am a bit confused and I do not know if they are a different or same thing. Here what I need. Suppose I have a growth rate of 10% over 3 years. Starting with 100$ I have: Initial capital: 100$ Year 1: 110$ Year 2: 121$ Year 3: 133$ Now the Annual return here is 10% and Annual mean return should be 33/3=11%. Correct? Obviously, the Annual mean return does not give me a good measure of growth rate because does not take into account the compound interest. Am I correct? Suppose now I reverse my input date in the problem. I have the initial capital 100$ and final 133$ and I want to calculate the growth rate. The formula should be (Capital final/Capital initial)^(1/3)-1. (133/100)^(1/3)-1=(1,33)^(1/3)=0.098 that correspond more or less to 10%. Are my computation and reasoning correct so far? If so, what is the difference between Annual Return vs CAGR? It seems they are the same, correct? Suppose now my time frame goes from September 10 2008 to Ferbuary 10 2012, my time frame is 3 years and 132 days. According to this website (see video) https://www.investopedia.com/ask/answers/071014/what-formula-calculating-compound-annual-growth-rate-cagr-excel.asp the number of years here is (3 + K) where K is the number of days converted in years, in our example K=132/365=0.36 so the number of years N=3+0.36=3.36 and this is the value I should use in the formula. Am I correct? Now the last doubt is that the website to calculate K suggest to divide the number of days for 360 or 365 but should I consider in my calculation only the number of days the stock market is open (a number more or less equal to 272)? The last question about python is, suppose I have a panda data frame df, can someone put a snippet of code I can use to calculate the Annual Return and/or CAGR. The code should take into consideration that the time frame could have a number of days more than one year and not pe…
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51097035
has comment: http://stackoverflow.com/comment/89180348
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/64578896
upvote count: 2
downvote count: 2
has title: Annual Return vs Annualized Return vs CAGR
type: Question
linked to: http://stackoverflow.com/q/4436957

http://stackoverflow.com/q/51021497
downvote count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89035538
score: 1
linked to: http://stackoverflow.com/q/7409780
has answer: http://stackoverflow.com/a/51021667
has comment: http://stackoverflow.com/comment/89035686
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89035915
favorite count: 0
has title: select group based on same value in regular Expression
tagged with: python
tagged with: regex
has body: I have a following content ONE 1234234534564 123 34erewrwer323 123 123fsgrt43232 123 TWO 42433412133fr 234 fafafd3234132 342 THREE sfafdfe345233 3234 FOUR 324ereffdf343 4323 fvdafasf34nhj 4323 fsfnhjdgh342g 4323 Consider ONE,TWO,THREE and FOUR are separate group.In that I want match only ONE and FOUR, based on the condition of second value of each line in the every group must be same and it will match group that has more than one line in that..How can I do that in regular expression I have already tried following regex, but its not up to the mark \w+\n\w+\t(\d+)(\n\w+\t\1){2,}

http://stackoverflow.com/a/51031375
has body: Assuming that you're using Python 3, in which division always returns a float, the problem lies in find_d(). The expression (k*phi_n+1)/e converts arbitrary-precision integers to limited-precision floats, and this is where the inaccuracy comes in. If you want to test whether k*phi_n+1 is evenly divisible by e and return the quotient if so, you should instead write: if (k*phi_n+1) % e == 0: return (k*phi_n+1) // e # Note use of integer division or, slightly more efficiently with divmod(): d, rem = divmd(k*phi_n+1, e) if rem == 0: return d
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51030384
accepted answer of: http://stackoverflow.com/q/51030384
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51153543
possible better answer: http://stackoverflow.com/a/51154564
tagged with: azure-blob-storage
type: Question
upvote count: 2
tagged with: azure-iot-hub
answer count: 2
has title: Azure IoTHub DeviceMessage structure and route query
accepted answer: http://stackoverflow.com/a/51166552
has answer: http://stackoverflow.com/a/51154564
tagged with: azure
has comment: http://stackoverflow.com/comment/89303363
favorite count: 0
has answer: http://stackoverflow.com/a/51166552
has body: I used the python example from https://learn.microsoft.com/de-de/azure/iot-hub/quickstart-send-telemetry-python to send telemetry data to the IoTHub. Now I try to forward only the messages from the device "test-device" into a blob storage via a custom endpoint and a route. With the query string "true" all messages from all devices are pushed to the storage. However, I don't get the query to select only the messages from the deviceId "test-device". I search in the documentation but didn't find any helpful example... Can anyone help me with the query? At least it would be also helpful to sample incoming messages inside the IoTHub to get an idea of the structure of IotHub messages (like it is done in the StreamAnalytics "sample data").
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/comment/89374672
type: Comment
type: QuestionComment
has text: My initial would also be not all input ready, but since you say that's not the case... Sorry, no other guess atm, but a way around it perhaps. Does your server close the connection when done serving full response? If so, you could `recv` and concatenate until closed connection is detected (empty string returned). And continue with your script execution.
score: 0
comment on: http://stackoverflow.com/q/51049837

http://stackoverflow.com/comment/89206423
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51109420
has text: @Bharel: Sure, but that just makes it compiled Python bytecode embedded in an executable.

http://stackoverflow.com/q/51164584
answer count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/89312410
has comment: http://stackoverflow.com/comment/89312449
has answer: http://stackoverflow.com/a/51164654
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/51164644
has body: I have a file that looks like this - Col1 Col2 Key Value 101 a f1 abc 101 a f2 def 102 a f2 xyz 102 a f3 fgh 103 b f1 rst and I need output file that looks like: {"Col1":101, "Col2":"a", "kvpairs":{"f1":"abc","f2":"def"}} {"Col1":102, "Col2":"a", "kvpairs":{"f2":"xyz","f3":"fgh"}} {"Col1":103, "Col2":"b", "kvpairs":{"f1":"rst"}} I can loop through the file clubbing the key values pairs for the grouping fields Col1 and Col2 into a list and dropping it into a dict but was hoping there was a more pythonic way of doing it. There are questions answered using pandas aggregation but i can't find a neat (and efficient way) of building that nested map. Also, the source file is gonna be large, like 80m records crunching down to 8m in the resulting file. I can see those eyes lighting up :)
upvote count: 0
has answer: http://stackoverflow.com/a/51164659
favorite count: 0
tagged with: aggregate
type: Question
has comment: http://stackoverflow.com/comment/89312426
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89312740
has title: python aggregate list to dictionary
has comment: http://stackoverflow.com/comment/89312478
tagged with: list
has comment: http://stackoverflow.com/comment/89312672

http://stackoverflow.com/q/51073144
has title: os.openpty() Operation not permitted after os.seteuid() from root to a user
has comment: http://stackoverflow.com/comment/89139820
tagged with: pty
score: 0
has comment: http://stackoverflow.com/comment/89136174
answer count: 1
has body: If we seteuid(123) from root to user 123, it will fail. However to run os.openpty() directly as user 123, it will be successful. Any hints? Same in both python 2.7 or 3.6. On Redhat 7: &gt;&gt;&gt; os.openpty() (3, 4) &gt;&gt;&gt; os.seteuid(12345) &gt;&gt;&gt; os.openpty() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; PermissionError: [Errno 1] Operation not permitted
type: AnsweredQuestion
tagged with: linux
type: Question
has answer: http://stackoverflow.com/a/51073501
has comment: http://stackoverflow.com/comment/89136202
tagged with: python
has comment: http://stackoverflow.com/comment/89136359
accepted answer: http://stackoverflow.com/a/51073501

http://stackoverflow.com/comment/89165716
type: Comment
comment on: http://stackoverflow.com/q/51088335
type: QuestionComment
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.
score: 0

http://stackoverflow.com/q/51031822
has comment: http://stackoverflow.com/comment/89056079
upvote count: 1
type: Question
has title: Python: comparing two Counter objects with different keys
tagged with: comparison
accepted answer: http://stackoverflow.com/a/51031937
tagged with: python-2.7
has body: I have two strings that I want to word tokenize and then compare for differences s1 = 'one two shmoo' s2 = 'one one two' My first thought was to turn them both into collections.Counter objects, wrap them in pd.Series, and subtract the difference. import pandas as pd from collections import Counter def counter_series(s): return pd.Series(Counter(s.split(' '))) counter_series(s2) - counter_series(s1) But the output shows that this difference doesn't provide a count for words that aren't present in both strings: one 1.0 shmoo NaN two 0.0 dtype: float64 How can you include the missing counts? E.g. in the output above shmoo should also be 1. The solution doesn't have to use pandas.
tagged with: pandas
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89056826
tagged with: python
has comment: http://stackoverflow.com/comment/89056677
has answer: http://stackoverflow.com/a/51031937
type: AnsweredQuestion

http://stackoverflow.com/a/51123015
has comment: http://stackoverflow.com/comment/89231188
downvote count: 0
has comment: http://stackoverflow.com/comment/89250052
type: Answer
has comment: http://stackoverflow.com/comment/89233841
score: 1
has comment: http://stackoverflow.com/comment/89232050
has body: Telegram webhook only talks to https endpoints, so I suggest to check your server against https connections. Also, getWebhookInfo call returns a status object with the latest error infomation of your endpoint. Have a look of that error info and might find the exact problem.
has comment: http://stackoverflow.com/comment/89234964
has comment: http://stackoverflow.com/comment/89249565
upvote count: 1
has comment: http://stackoverflow.com/comment/89234946
answers question: http://stackoverflow.com/q/51108826

http://stackoverflow.com/q/51016696
tagged with: python
has title: When is best way to open a file to write to?
has comment: http://stackoverflow.com/comment/89025923
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51016739
tagged with: file
tagged with: file-writing
type: Question
has answer: http://stackoverflow.com/a/51016745
accepted answer: http://stackoverflow.com/a/51016745
has comment: http://stackoverflow.com/comment/89025976
has comment: http://stackoverflow.com/comment/89025967
score: 0
has body: Let's say I need to crunch some data and then write the results to some file. Would it be better to open the file first, then process the data, then write to the file? with open('file', 'w') as f: summary = process_data() f.write(summary) Or would it be better to open the file just before writing to it? summary = process_data() with open('file', 'w') as f: f.write(summary) My intuition tells me that if process_data() requires a lot of memory and if file is large, there may be some issues with the first approach. Edit: To clarify from some of the responses, what are the pros and cons of each approach?
answer count: 2
has answer: http://stackoverflow.com/a/51016739

http://stackoverflow.com/comment/89327774
score: 3
type: Comment
type: QuestionComment
has text: the solver is a tsp internally so you can't visit two time the same node. You must create a "duplicate" of the depot with a slack var (like in refuel) to empty/refill your vehicle.....
comment on: http://stackoverflow.com/q/51153760

http://stackoverflow.com/q/51072660
has comment: http://stackoverflow.com/comment/89137244
tagged with: background-task
has comment: http://stackoverflow.com/comment/89137299
has comment: http://stackoverflow.com/comment/89135676
tagged with: uwsgi
type: Question
has comment: http://stackoverflow.com/comment/89136384
has comment: http://stackoverflow.com/comment/89153642
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/89135384
has body: Edit for clarify my question: I want to attach a python service on uwsgi using this feature (I can't understand the examples) and I also want to be able to communicate results between them. Below I present some context and also present my first thought on the communication matter, expecting maybe some advice or another approach to take. I have an already developed python application that uses multiprocessing.Pool to run on demand tasks. The main reason for using the pool of workers is that I need to share several objects between them. On top of that, I want to have a flask application that triggers tasks from its endpoints. I've read several questions here on SO looking for possible drawbacks of using flask with python's multiprocessing module. I'm still a bit confused but this answer summarizes well both the downsides of starting a multiprocessing.Pool directly from flask and what my options are. This answer shows an uWSGI feature to manage daemon/services. I want to follow this approach so I can use my already developed python application as a service of the flask app. One of my main problems is that I look at the examples and do not know what I need to do next. In other words, how would I start the python app from there? Another problem is about the communication between the flask app and the daemon process/service. My first thought is to use flask-socketIO to communicate, but then, if my server stops I need to deal with the connection... Is this a good way to communicate between server and service? What are other possible solutions? Note: I'm well aware of Celery, and I pretend to use it in a near future. In fact, I have an already developed node.js app, on which users perform actions that should trigger specific tasks from the (also) already developed python application. The thing is, I need a production-ready version as soon as possible, and instead of modifying the python application, that uses multiprocessing, I thought it would be faster to create a simple …
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51090760
has comment: http://stackoverflow.com/comment/89138009
has comment: http://stackoverflow.com/comment/89153722
has comment: http://stackoverflow.com/comment/89137298
linked to: http://stackoverflow.com/q/50863360
has comment: http://stackoverflow.com/comment/89136721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89137265
upvote count: 1
tagged with: python
downvote count: 1
has title: Daemon background tasks on flask (uwsgi) application
linked to: http://stackoverflow.com/q/11256002
has comment: http://stackoverflow.com/comment/89137485
linked to: http://stackoverflow.com/q/50508310
has comment: http://stackoverflow.com/comment/89135718

http://stackoverflow.com/comment/89226437
comment on: http://stackoverflow.com/a/51120482
has text: Thanks for calling out my use of `round` - I didn’t even realise!
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/51296981
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51034526
answers question: http://stackoverflow.com/q/51034526
has body: I eventually found the answer to my question in the Django documentation. Turns out that the approach I detailed in my question was obsolete and wouldn't work in recent Django versions. The team that develops Django created a much more elegant and straightforward method: instead of overriding the renderer in your forms.py you have to use the Django templating language in your html file. It's described here. I will play around with it more (and update my answer if I find sth important to add) but as far as I understood it you have to: 1) specify the field by name when calling the form; 2) add the necessary tags manually; 3) use the radiobutton's tag attribute. Here's the code that works for me: {% extends 'base.html' %} {% block body %} Form test {% csrf_token %} Never Sometimes Often Always Question {% for radio in form.choice_field %} {{ radio.tag }} {% endfor %} Submit {{ text }} {% endblock %} It's rather obvious once you know it. Anyway, hope that helps someone!
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89059039
comment on: http://stackoverflow.com/q/51032915
type: QuestionComment
has text: Yes, that's good since it resolves the url now -> next challenge ;) You'll likely receive the 403 because you are missing a csrf token. You can either google for "how to include django csrf token in ajax request" or remove it via [csrf_exempt](https://docs.djangoproject.com/en/2.0/ref/csrf/#django.views.decorators.csrf.csrf_exempt) for this single request **Disclaimer: Removing csrf check is a serious security issue and should never be done in production and when data is altered at the target system.**
score: 0
type: Comment

http://stackoverflow.com/a/51424839
score: 0
has body: It looks like the element you're trying to capture is dynamically generated by JavaScript. request gets the content before this even happens. For situations like these there are 2 things you can do, Recommended way of doing it is to use something else, like selenium to get the page source. Check the network tab in browser's developer tools and see if the data file is getting downloaded, this is a hack-y kinda way and will not always work.
answers question: http://stackoverflow.com/q/51145100
type: Answer

http://stackoverflow.com/q/51153013
has comment: http://stackoverflow.com/comment/89289410
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89290755
has body: I am new the Django and I am unable to save the Registration form using the Class Based View. I have made the Abstract user in the Models as shown below. models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user non superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) user_type = models.CharField(max_length= 120, choices=u_type) # confirm = models.BooleanField(default=False) # confirmed_date = models.DateTimeField(default=False) USERNAME_FIELD = 'email' #username # USERNAME_FIELD and password are required by default REQUIRED_FIELDS = [] #['full_name'] #python manage.py createsuperuser objects = UserManager() def __str__(self): return self.email def get_full_name(self): if self.full_name: return self.full_name return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active I have used Form for creating the Registration form as shown below forms.py class RegistrationForm(forms.Form): password1 = forms.CharField(label='password') password2 = forms.CharField(label='Confirm Password') user_email = forms.CharField(label='Email') full_name = forms.CharField(label='Full Name') class Meta: model = User fields = ('full_name', 'email','user_type') def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('password does not match') return password2 def save(self, commit=True): user = super(RegistrationForm, self).save(com…
score: 0
has comment: http://stackoverflow.com/comment/89290177
has comment: http://stackoverflow.com/comment/89292768
tagged with: python
has comment: http://stackoverflow.com/comment/89290963
has comment: http://stackoverflow.com/comment/89289908
answer count: 0
has title: AttributeError , 'super' object has no attribute 'save', in class based view
type: UnansweredQuestion

http://stackoverflow.com/a/51066187
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89122668
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51065571
score: 1
has body: Given that XDFDF is a pandas.DataFrame, shouldn't the following work? XDFDFdrop = pd.DataFrame.duplicated(XDFDF,subset='LastSurveyMachineID') goodBucket = XDFDF.loc[~XDFDFdrop] #the ~ negates a boolean array badBucket = XDFDF.loc[XDFDFdrop] Edit: The updated error comes from you passing an entire row rather than an index to the function pandas.DataFrame.drop.
accepted answer of: http://stackoverflow.com/q/51065571
has comment: http://stackoverflow.com/comment/89126527

http://stackoverflow.com/a/51107802
downvote count: 0
answers question: http://stackoverflow.com/q/51107657
type: Answer
accepted answer of: http://stackoverflow.com/q/51107657
has comment: http://stackoverflow.com/comment/89670127
score: 1
upvote count: 1
has body: If you download the page html using some downloader (wget or curl) you will see that the elements are not in the page at all. The elements are being generated by javascript. For example (snippet from the source of the page): You have two options: Execute the javascript (with a browser and something like selenium to drive it) or parse it manually, by using beautiful soup to get the tag contents, then extracting the text inside document.write() and reparsing it with beautiful soup.
type: AcceptedAnswer

http://stackoverflow.com/q/51015103
has answer: http://stackoverflow.com/a/51015263
answer count: 2
accepted answer: http://stackoverflow.com/a/51015263
favorite count: 0
tagged with: python-3.x
has title: Python - Aren't packages relative to their current directory?
tagged with: python
possible better answer: http://stackoverflow.com/a/51015385
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51015385
downvote count: 0
has body: Okay, I've got a file structure like the following: main.py/ paquete/ __ init__.py test1.py This is what I've got in my main.py: from paquete import testFunc def main(): testFunc() if __name__ == '__main__': main() This is what I've got in my test1.py: def testFunc(): print("Hello from test1 function!") And this is what I've got in my __ init__.py: from test1 import testFunc But that doesn't work, it says that there's no module named test1. However, if I have something like: from paquete.test1 import testFunc It works perfect. But I don't get it, if __ init__.py it's in the same directory as test1, why do I need to prefix it with the name of the directory as if I was working from the root level of the project?
type: Question
upvote count: 2

http://stackoverflow.com/comment/89091563
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51050155
has text: Thank you, sorry to change the question a bit, but how would I separate this data? As you can see it is one big string. -- >: (1) cpd00015_c + (1) cpd00041_c + (1) cpd00095_c <=> (2) cpd00001_c + (1) cpd00009_c + (1) cpd00982_c + (1) cpd02333_c (3) cpd00004_c + (4) cpd00067_c + (1) cpd00075_c <= (1) cpd00001_c + (3) cpd00003_c + (1) cpd00985_c XXXXXXXXX

http://stackoverflow.com/comment/89167067
comment on: http://stackoverflow.com/q/51088946
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Pyinstaller and --onefile: How to include an image in the exe file](https://stackoverflow.com/questions/31836104/pyinstaller-and-onefile-how-to-include-an-image-in-the-exe-file)

http://stackoverflow.com/q/51071467
has body: X: a list of lists, where each list element corresponds to a label in Y Y: a binary list of labels (values are either 1 or 0) I want to extract the elements in X according to the value at the corresponding index in Y, as follows: good = values of X where the label/value in Y is 1 bad = values of X where the label/value in Y is 0 I am still fairly new to sub-setting in Python and not really sure of a good way to do this.
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51071597
has comment: http://stackoverflow.com/comment/89132740
possible better answer: http://stackoverflow.com/a/51071525
has answer: http://stackoverflow.com/a/51071527
has answer: http://stackoverflow.com/a/51071525
type: Question
has title: Separate a list based on values in a second list
score: 0
has answer: http://stackoverflow.com/a/51071549
has answer: http://stackoverflow.com/a/51071597

http://stackoverflow.com/comment/89178605
has text: @AkshayNevrekar - need columns names `year`, `month`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51095114

http://stackoverflow.com/q/51102539
score: 2
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/51134223
upvote count: 2
tagged with: python-unittest
type: Question
linked to: http://stackoverflow.com/q/19425736
has title: How to redirect Python's unittest modules error traceback to log file using logging module?
duplicate of: http://stackoverflow.com/q/19425736
has body: I have a python test script and I am trying to redirect its output(stdout and stderr) both to console and a log file.The script produces following output in console which is what I want. test_valid_timerange (testapp.TestApp) ... FAIL test_has_dashboard_description (testapp.TestApp) ... ok ====================================================================== FAIL: test_valid_timerange (testapp.TestApp) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/himanshu/git/content/test/testapp.py", line 135, in test_valid_timerange "%s: panel %s in dashboard %s does not use relative url" % (self.appname, dash.get("name"), panel.get("name"))) AssertionError: Kubernetes: panel Kubernetes - Kube-System in dashboard Pod and Container Running in Kube-System does not use relative url ---------------------------------------------------------------------- Ran 2 tests in 0.001s FAILED (failures=1) But in log file I am getting only this. 2018-06-29 18:29:56,289 [MainThread ] [INFO ] Starting Tests for manifestfile: /Users/himanshu/git/content/src/main/app-package/kubernetes/kops/kubernetes.manifest.json appfile: /Users/himanshu/git/content/src/main/app-package/kubernetes/kops/kubernetes.json 2018-06-29 18:29:56,341 [MainThread ] [INFO ] testing Kubernetes: test_valid_timerange 2018-06-29 18:29:56,341 [MainThread ] [INFO ] testing Kubernetes: test_has_dashboard_description 2018-06-29 18:29:56,342 [MainThread ] [DEBUG] Results - Total TestCases: 2 Total Failed: 1 I know one way of doing it is to explicitly get failures and errors from result object of test and printing them using a logger whose handler outputs only to file(This is because if I use my current logger it has both streamhandler and filehandler and it will print failure messages two times in console). This is my current code def get_logger(): log = logging.getLogger(__name__) if not log.handlers: log.setLevel(logging.DEBUG) logFormatter = logging.Formatter…
tagged with: python-2.7

http://stackoverflow.com/q/51134700
downvote count: 0
answer count: 1
has title: insert Python list of lists into PSQL database
favorite count: 0
has body: I have a Python list of lists and I would like to insert it into a PSQL database. lsls = [[int1, int2, int3],[int4, int5, int6]] I've tried the following command of the psycopg2 module, but it's not working: cur.executemany("""INSERT INTO example(col1, col2) VALUES (%s, %s)""", lsls) Integers in the first list should be added to col1 and integers in the second list to col2.
linked to: http://stackoverflow.com/q/18244565
tagged with: python
tagged with: psql
has answer: http://stackoverflow.com/a/51135056
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question

http://stackoverflow.com/comment/89101920
has text: you could plug that hole by **MyClass.inst = None** at class level and, assigning self to it that in \__init\__ and throwing an exception if it was already assigned.
comment on: http://stackoverflow.com/a/51041181
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90497577
type: Comment
score: 0
type: QuestionComment
has text: With the exact model number and product name it might be possible to search for more information regarding the format of your file.
comment on: http://stackoverflow.com/q/51039975

http://stackoverflow.com/a/51164051
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51161348
has body: There is a library called CVXOPT that has quadratic programming in it. def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): qp_G = .5 * (P + P.T) # make sure P is symmetric qp_a = -q if A is not None: qp_C = -numpy.vstack([A, G]).T qp_b = -numpy.hstack([b, h]) meq = A.shape[0] else: # no equality constraint qp_C = -G.T qp_b = -h meq = 0 return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0]
answers question: http://stackoverflow.com/q/51161348
downvote count: 1
has comment: http://stackoverflow.com/comment/131378490
upvote count: 5
score: 4

http://stackoverflow.com/q/51098714
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89190085
tagged with: python
has answer: http://stackoverflow.com/a/51098794
has body: Does Python have a builtin type for representing symbolic values, when strings cannot be used? A quick implementation of my own would look like class Symbol: def __init__(self, name): self.name = name def __repr__(self): return self.name Usecase Such symbols are useful when a value – say a keyword argument or a list entry – needs to be initialized to a value that indicates that it hasn't been explicitly set. If the values have constraints on allowed types, commonly None or some string would be used, but if any value is allowed, some other unique object is needed. My common method is to use an object() assigned to some private variable, but the symbol pattern is more convenient for debugging due to providing a meaningful printed representation. As an alternative, one could use e.g. a tuple ('default value',) and compare against it with the is operator, but this wouldn't work e.g. for dictionary keys. While the pattern is simple enough to copy/paste into each shell-script I am writing, a builtin solution with established behavior would be preferable. Non-builtins I know, that there are packages that provide a symbol type. An obvious one would be the symbol type of sympi, and there is https://pypi.org/project/SymbolType/. However, adding dependencies to avoid a 5-line pattern seems a heavy overkill, hence my question about a builtin type.
has comment: http://stackoverflow.com/comment/89198479
downvote count: 1
type: Question
has title: Non-string "Symbol" object in python?
answer count: 1
has comment: http://stackoverflow.com/comment/89198786
has comment: http://stackoverflow.com/comment/89185435
tagged with: symbols
score: 1

http://stackoverflow.com/a/51056194
upvote count: 14
downvote count: 1
type: Answer
has body: The abc system doesn't include a way to declare an abstract instance variable. The code that determines whether a class is concrete or abstract has to run before any instances exist; it can inspect a class for methods and properties easily enough, but it has no way to tell whether instances would have any particular instance attribute. The closest thing is probably a variable annotation: class Bird(metaclass=ABCMeta): feathers : str ... abc won't do anything with that annotation, but it at least expresses to readers and static type checkers that instances of Bird are supposed to have a feathers instance variable. (Whether static type checkers will understand that this instance variable is supposed to come from subclasses, I don't know.)
score: 13
answers question: http://stackoverflow.com/q/51055750

http://stackoverflow.com/comment/101260001
score: 1
comment on: http://stackoverflow.com/a/51416218
type: AnswerComment
has text: @tr0yspradling You can also create a global APP object and import it wherever you need to use it. Edited the answer to include this alternative.
type: Comment

http://stackoverflow.com/a/53850328
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51101252
upvote count: 3
has body: If your aim is to plot horizontal lines using the A and B columns as x-axis and C column as y-axis, you can directly use arrays of dataframe. Added 1 day to B column since the time changes very minimal to observe that in graph: df['B'] = df['B']+pd.Timedelta("1D") ax = plt.subplot() ax.hlines(df.C.values, df.A.values, df.B.values, lw=2) plt.show() Output Plot:
answers question: http://stackoverflow.com/q/51101252
type: Answer
downvote count: 0

http://stackoverflow.com/a/51124688
has body: Rather than manually starting threads, much better just use multiprocessing.pool. The multiprocessing part needs to be in a function that you call with map. Instead of map you can then use pool.imap. import multiprocessing import time def func(x): time.sleep(x) return x + 2 if __name__ == "__main__": p = multiprocessing.Pool() start = time.time() for x in p.imap(func, [1,5,3]): print("{} (Time elapsed: {}s)".format(x, int(time.time() - start))) Also check out: multiprocessing.Pool: What&#39;s the difference between map_async and imap? Also worth checking out is functools.partials which can be used to pass in multiple variables (in addition to the list). Another trick: sometimes you don’t l really need multiprocessing (as in multiple cores of your processor), but just multiple threads to concurrently query a database with many connections at the same time. In that case just do from multiprocessing.dummy import Pool and can avoid python from spawning a separate process (which makes you lose access to all the namespaces you don’t pass into the function), but keep all the benefits of a pool, just in a single cpu core. That’s all you need to know about python multi processing (using multiple cores) and multithreading (using just one process and keeping the global interpreter lock intact). Another little advice: always try to use map first without any pools. Then switch to pool.imap in the next step once you’re sure it all works.
has comment: http://stackoverflow.com/comment/89238852
has comment: http://stackoverflow.com/comment/89235518
score: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/89239461
has comment: http://stackoverflow.com/comment/89238033
upvote count: 4
has comment: http://stackoverflow.com/comment/89237566
has comment: http://stackoverflow.com/comment/89235708
has comment: http://stackoverflow.com/comment/89237528
has comment: http://stackoverflow.com/comment/89239439
has comment: http://stackoverflow.com/comment/89236818
has comment: http://stackoverflow.com/comment/89235735
has comment: http://stackoverflow.com/comment/89237398
answers question: http://stackoverflow.com/q/51123971
type: Answer

http://stackoverflow.com/q/51140416
score: 0
linked to: http://stackoverflow.com/q/4231243
has comment: http://stackoverflow.com/comment/89265339
answer count: 1
has answer: http://stackoverflow.com/a/51140654
tagged with: nfs
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51140654
tagged with: linux
type: Question
tagged with: inotifywait
has body: So I have this script running, using inotifywait. One server puts images into a NFS folder on the host server at /var/nfs/device_images. (chmod is 777 on working folders) The host server then moves it into a working directory of a python script. inotifywait -m /var/nfs/device_images -e create -e moved_to | while read path action file; do cp /var/nfs/drvie_images/$file /home/samuel/programname/images/$file; done It works, kinda. The file itself transfers, but it's corrupt. It seems inotifywait tries to send the photo before it's totally transferred? Anyone have a solution?
tagged with: python
has title: Inotify wait Copy Script Corrupting Images

http://stackoverflow.com/comment/89282748
score: 0
type: Comment
type: QuestionComment
has text: Yes I want N bars in one figure, but each bar consists of 2000 stacked bars
comment on: http://stackoverflow.com/q/51148539

interpreter
tags question: http://stackoverflow.com/q/51021971
tag name: interpreter
tags question: http://stackoverflow.com/q/51125676
tags question: http://stackoverflow.com/q/51055457
tags question: http://stackoverflow.com/q/51148730
tags question: http://stackoverflow.com/q/51116426
tags question: http://stackoverflow.com/q/51090219
type: Tag

http://stackoverflow.com/comment/89229727
has text: Please share the *too much time taking* code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51122073
score: 0

http://stackoverflow.com/q/51128855
tagged with: figure
downvote count: 5
possible better answer: http://stackoverflow.com/a/51128882
has comment: http://stackoverflow.com/comment/89242543
has body: I looked at a similar post but am still struggling with it. You don't have to write out the whole code if you don't want. But a syntactical guide would be helpful. Here is my lengthy manual approach: # Grid of MMR distributions by every 5 years mmr_1990 = mmr[mmr['Year']=='1990'] mmr_1995 = mmr[mmr['Year']=='1995'] mmr_2000 = mmr[mmr['Year']=='2000'] mmr_2005 = mmr[mmr['Year']=='2005'] mmr_2010 = mmr[mmr['Year']=='2010'] mmr_2015 = mmr[mmr['Year']=='2015'] year_list = [mmr_1990, mmr_1995, mmr_2000, mmr_2005, mmr_2010, mmr_2015] fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(2,3,1) ax2 = fig.add_subplot(2,3,2) ax3 = fig.add_subplot(2,3,3) ax4 = fig.add_subplot(2,3,4) ax5 = fig.add_subplot(2,3,5) ax6 = fig.add_subplot(2,3,6) #1990 ax1.hist(mmr_1990['MMR'], color='darkred', edgecolor='white') ax1.set_title('1990 MMR Distribution', fontweight='bold', loc='left') ax1.spines['left'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['bottom'].set_visible(False) ax1.tick_params(length=0) ax1.set_xlim(0,3000,500) #1995 ax2.hist(mmr_1995['MMR'], color='darkred', edgecolor='white') ax2.set_title('1995 MMR Distribution', fontweight='bold', loc='left') ax2.spines['left'].set_visible(False) ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['bottom'].set_visible(False) ax2.tick_params(length=0) ax2.set_xlim(0,3000,500) #2000 ax3.hist(mmr_2000['MMR'], color='darkred', edgecolor='white') ax3.set_title('2000 MMR Distribution', fontweight='bold', loc='left') ax3.spines['left'].set_visible(False) ax3.spines['top'].set_visible(False) ax3.spines['right'].set_visible(False) ax3.spines['bottom'].set_visible(False) ax3.tick_params(length=0) ax3.set_xlim(0,3000,500) #2005 ax4.hist(mmr_2005['MMR'], color='darkred', edgecolor='white') ax4.set_title('2005 MMR Distribution', fontweight='bold', loc='left') ax4.spines['left'].set_visible(False) ax4.spines['top'].set_visible(False) ax4.spines['right…
has comment: http://stackoverflow.com/comment/89242520
has answer: http://stackoverflow.com/a/51128923
answer count: 3
has title: Can someone help me rewrite this code (fig with multiple histograms) with a for loop or function?
upvote count: 0
score: -5
tagged with: histogram
favorite count: 0
has answer: http://stackoverflow.com/a/51128960
tagged with: python
accepted answer: http://stackoverflow.com/a/51128923
type: AnsweredQuestion
type: Question
tagged with: fig
has answer: http://stackoverflow.com/a/51128882

http://stackoverflow.com/comment/89047502
has text: @Umair bingo - that's at least the start of your problem. Your operating system should be setting this for you. Please check your system is setup correctly
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51026315

http://stackoverflow.com/comment/89164771
comment on: http://stackoverflow.com/a/51087590
type: Comment
score: 1
has text: @Spinor8, Woops, `enumerate` should work instead, have updated.
type: AnswerComment

http://stackoverflow.com/comment/89262553
type: AnswerComment
has text: This is what I want. But doing that runs me into the error that the shape of my wind_dir is different than the shape of u>0 and v>0, since not all of the entries in the array have u>0 and v>0. Does this make sense? shape mismatch: value array of shape (26406,) could not be broadcast to indexing result of shape (20049,)
type: Comment
comment on: http://stackoverflow.com/a/51139211
score: 0

http://stackoverflow.com/q/51071513
linked to: http://stackoverflow.com/q/1798796
has comment: http://stackoverflow.com/comment/89136871
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89132962
has comment: http://stackoverflow.com/comment/89136712
tagged with: python
linked to: http://stackoverflow.com/q/26773054
duplicate of: http://stackoverflow.com/q/1798796
answer count: 0
has title: Can't debug list index out of range error
linked to: http://stackoverflow.com/q/1207406
type: Question
duplicate of: http://stackoverflow.com/q/1207406
tagged with: runtime-error
score: 0
has body: for i in range (len(userCards)): print("i is "+str(userCards[i])) if userCards.count(userCards[i]) == 4: userMatches = userMatches + 1 userCards.remove(userCards[i]) I'm trying to remove duplicate cards from a list of numbers but I keep getting the list index out of range error

http://stackoverflow.com/q/51016397
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89028443
has answer: http://stackoverflow.com/a/51016507
has answer: http://stackoverflow.com/a/51016662
accepted answer: http://stackoverflow.com/a/51016662
has answer: http://stackoverflow.com/a/51016679
type: Question
has comment: http://stackoverflow.com/comment/89026030
has comment: http://stackoverflow.com/comment/89025487
downvote count: 2
tagged with: pep8
possible better answer: http://stackoverflow.com/a/51016507
has body: PEP 8 has conflicting code examples (in my opinion), and I'm curious what the convention is for positioning closing braces. Under the top of indentation they're on the same line as the parameters. Near the bottom it discusses positioning and instead says: The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list[...] or it may be lined up under the first character of the line that starts the multiline construct[...] which directly conflicts the code examples above. Where do you commonly position your closing braces for multi-line statements, and what do you think is best practice in terms of convention? Just for clarity, here are code examples which demonstrate the differences. foo = long_function_name( var_one, var_two, var_three, var_four) result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', )
favorite count: 0
has comment: http://stackoverflow.com/comment/89025462
tagged with: convention
has comment: http://stackoverflow.com/comment/89025438
tagged with: python
has answer: http://stackoverflow.com/a/79062951
has title: Closing braces with Python
score: 13
upvote count: 15

http://stackoverflow.com/q/51013512
downvote count: 0
has answer: http://stackoverflow.com/a/51013647
favorite count: 0
possible better answer: http://stackoverflow.com/a/64165842
has answer: http://stackoverflow.com/a/64165842
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51013647
upvote count: 3
tagged with: complex-numbers
type: Question
score: 3
tagged with: dataframe
has body: In python, I have a dataframe with 2 columns of real numbers. I want to make complex number and use those two columns as real and imaginary parts of my new set of data. I have tried complex(df['wspd'].astype(float),df['wdir'].astype(float)) but I still get this error: cannot convert the series to &lt;class 'float'&gt; How can I make it happen?
has title: How to make a dataframe containing complex numbers from dataframes with real numbers in python?
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/89115486
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51062412
has text: FYI: If you use a random-ish value to seed np.random this wouldn't happen. For example: with `from timeit import default_timer as tmr` and `np.random.seed(int(tmr()*100000) % 11)` you'll get (seemingly) random values based on the current time even if you seed the RNG before every call to `randint`.

http://stackoverflow.com/comment/89208232
comment on: http://stackoverflow.com/a/51081532
type: AnswerComment
score: 0
type: Comment
has text: Sir Thank you so much. How about if I want to edit something in my Contact list?

http://stackoverflow.com/comment/89300779
comment on: http://stackoverflow.com/a/51158653
type: Comment
has text: @RickyAguilar, OK, I've updated, not sure it's *exactly* what you want, but it produces your desired output.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89228293
type: Comment
comment on: http://stackoverflow.com/a/51121366
score: 1
has text: So I made a mistake somewhere getting data! Thank you, I'll upvote
type: AnswerComment

http://stackoverflow.com/comment/89521399
score: 0
type: AnswerComment
type: Comment
has text: Note that it's not a good idea to use a lot of string concatenation either. Use string formatting instead.
comment on: http://stackoverflow.com/a/51156780

http://stackoverflow.com/comment/89278715
score: 0
type: QuestionComment
type: Comment
has text: now Im a bit confused? are you trying to install gevent or tweepy? or are you trying to install tweepy but cant instlall it cause gevent is a requirement and you cant install it? it seems that you already have though. just upgrade the requests.
comment on: http://stackoverflow.com/q/51147178

http://stackoverflow.com/q/51149275
has comment: http://stackoverflow.com/comment/89282667
score: 0
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/51149615
has title: Changing and altering ranges of x and y axis in a line graph in MatplotLib
tagged with: pandas
tagged with: python
has body: I have created a line graph in Image 1 while I want to change my x-axis which is the 365 days of a year to 12 months but need to plot values of each date. I want to develop a graph like 2. My Dataframe looks like this Month Date max min 0 1.0 1900-01-01 15.6 -16.0 1 1.0 1900-01-02 13.9 -26.7 2 1.0 1900-01-03 13.3 -26.7 3 1.0 1900-01-04 10.6 -26.1 4 1.0 1900-01-05 12.8 -15.5
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51149345
type: Question
tagged with: charts
tagged with: linegraph
tagged with: matplotlib

http://stackoverflow.com/comment/89163617
comment on: http://stackoverflow.com/a/51084715
score: 1
has text: Wow, perfect answer. Thank you very much. Yes, I'm the kind of guy who prefers strict behavior regarding types, so I've just enabled this flag for our whole code base and now am working through the errors. ;)
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89103625
comment on: http://stackoverflow.com/a/51045526
type: AnswerComment
type: Comment
has text: The last part with the `d1,d2` assigning( was part of my wrong code)should change and should perform the comparison based on the previous code where it compares each new shp with the corresponding old. As it is now if i print hte results there is no comparison and listing of results based on the 'comparison code'.What is going on?
score: 0

http://stackoverflow.com/a/51025004
type: Answer
has body: Here are three possibilities: Use concat/groupby: First concatenate both DataFrames vertically. Then group by the index and select the first row in each group. Use combine_first: Make a new index which is the union of df1 and df2. Reindex df1 using the new index. Then use combine_first to fill in NaNs with values from df2. Use manual construction: We could use df2.index.difference(df1.index) to find exactly which rows need to be added to df1. So we could manually select those rows from df2 and concatenate them on to df1. For small DataFrames, using_concat is faster. For larger DataFrames, using_combine_first appears to be slightly faster than the other options: import numpy as np import pandas as pd import perfplot def make_dfs(N): df1 = pd.DataFrame(np.random.randint(10, size=(N,2))) df2 = pd.DataFrame(np.random.randint(10, size=(N,2)), index=range(N//2,N//2 + N)) return df1, df2 def using_concat(dfs): df1, df2 = dfs result = pd.concat([df1,df2], sort=False) n = result.index.nlevels return result.groupby(level=range(n)).first() def using_combine_first(dfs): df1, df2 = dfs index = df1.index.union(df2.index) result = df1.reindex(index) result = result.combine_first(df2) return result def using_manual_construction(dfs): df1, df2 = dfs index = df2.index.difference(df1.index) cols = df2.columns.difference(df1.columns) result = pd.concat([df1, df2.loc[index]], sort=False) result.loc[df2.index, cols] = df2 return result perfplot.show( setup=make_dfs, kernels=[using_concat, using_combine_first, using_manual_construction], n_range=[2**k for k in range(5,21)], logx=True, logy=True, xlabel='len(df)')
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51024619

http://stackoverflow.com/a/64907299
answers question: http://stackoverflow.com/q/51031519
type: Answer
has body: Cause : case sensitive change it from keras.layers import Merge to from keras.layers import merge
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/51140500
has comment: http://stackoverflow.com/comment/89265831
has comment: http://stackoverflow.com/comment/89265848
downvote count: 0
has body: https://docs.mongodb.com/manual/reference/program/mongo/#cmdoption-mongo-networkmessagecompressors reads: Messages are compressed when both parties enable network compression. Otherwise, messages between the parties are uncompressed. On the client side I read https://api.mongodb.com/python/current/changelog.html#changes-in-version-3-7-0: Support for wire protocol compression as it was not supported before v3.7. The block_compressor you see in the log is likely storage compression, not the wire compression. It is defined in storage options of mongodb config serverside and can't be changed from the client.
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51139748
score: 1
answers question: http://stackoverflow.com/q/51139748

http://stackoverflow.com/q/51030560
score: 0
has body: I have a work requirement where I needed to create a Kubernetes Pod(say child pod) from with in a pod(sat Master pod) in the same cluster. So far I was able to create a child pod from master pod. Problem, where I wanted help is the setup for gcloud and kubernetes. To make my pod create these child pods, I had to install these two &amp; configure them with same credentials as I have in my local system. Issues at hand (what is the best way/standard way)How to configure - gcloud &amp; kubernetes in this scenario? Is there any other way I dont have to install gcloud and kubernetes in the pod?
tagged with: gcloud
type: UnansweredQuestion
tagged with: kubernetes
tagged with: python
has comment: http://stackoverflow.com/comment/89105700
has title: How to configure a kubernetes pod, to create a pod from with a pod?
has comment: http://stackoverflow.com/comment/89410801
has comment: http://stackoverflow.com/comment/89055954
answer count: 0
type: Question

http://stackoverflow.com/q/51049173
linked to: http://stackoverflow.com/q/3501588
type: Question
has comment: http://stackoverflow.com/comment/89098750
accepted answer: http://stackoverflow.com/a/51090068
answer count: 1
has title: django, 'some_field' attribute has no file associated with it
score: 0
has body: views.py if request.is_ajax(): testpic = TestPic.objects.get(pk=1) form = TestPicForm(request.POST, request.FILES, instance=testpic) if form.is_valid(): form.save() forms.py class TestPicForm(forms.ModelForm): class Meta: from .models import TestPic model = TestPic fields = ('file', 'file_50',) def save(self): test_photo = super(TestPicForm, self).save() file = user_photo.file image = Image.open(file) rotated_image = image.rotate(90, expand=True) cropped_image = rotated_image.resize((300, 300), Image.ANTIALIAS) cropped_50_image = rotated_image.resize((50, 50), Image.ANTIALIAS) cropped_image.save(test_photo.file.path) file.seek(0) cropped_50_image.save(test_photo.file_50.path) return user_photo models.py class TestPic(models.Model): file = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d") file_50 = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d") This code is to upload a image file, to resize of it by two different size and to save it. Sadly, It works only when there is any file on field file_50. In other words, if there is file some_file_50.jpeg on file_50 field, image file uploading does works, but in django-admin, there cannot see any change of file name on file_50 field.(file name of file field is changed.) However content of some_file_50.jpeg is changed.(I can see these changes by click image file link on django-admin) Only name of file, some_file_50.jpeg is unchangeable. When file_50 field has no file on it, it throws the error: The 'file_50' attribute has no file associated with it. Question: How can I fix it? Thanks for reading. ADD Traceback: Internal Server Error: /accounts/crop/ Traceback (most recent call last): File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = …
has comment: http://stackoverflow.com/comment/89095639
has answer: http://stackoverflow.com/a/51090068
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51154241
score: 3
downvote count: 0
has body: There are pre-compiled binaries available on THIS page for Windows as MSI packages and ZIP files. You can find the one for the OS you are using. If you want to proceed with your current approach then can you can probably refer THIS LINK
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89351281
accepted answer of: http://stackoverflow.com/q/51154143
answers question: http://stackoverflow.com/q/51154143
type: Answer

printers
tag name: printers
type: Tag
tags question: http://stackoverflow.com/q/51122294

http://stackoverflow.com/comment/89372436
type: AnswerComment
has text: Hey Jay please see my update. I think we are close to the answer but not quite there yet.
type: Comment
comment on: http://stackoverflow.com/a/51182742
score: 0

http://stackoverflow.com/q/51147228
has comment: http://stackoverflow.com/comment/89316008
favorite count: 0
tagged with: python
score: 2
has body: What should I do, when I have e.g. this line: full_path = "https://www.google.cz/search?q=" + website_keywords # google link url Flake8 reports me, that characters in line are above 79 max. length. What should I do with comment then, when PEP 8 says that inline-comment should be on the same line with particular statement.
downvote count: 0
accepted answer: http://stackoverflow.com/a/51147258
has answer: http://stackoverflow.com/a/51147330
has comment: http://stackoverflow.com/comment/89278640
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51147258
tagged with: comments
upvote count: 2
has comment: http://stackoverflow.com/comment/89318275
answer count: 2
tagged with: flake8
possible better answer: http://stackoverflow.com/a/51147330
has title: More than 79 chars at line with comment

http://stackoverflow.com/comment/89189615
comment on: http://stackoverflow.com/a/51100358
score: 0
type: AnswerComment
type: Comment
has text: Use input `[-10, -20, -30]` instead, i.e. `new_map([-10, -20, -30], abs)`. Don't choose lists or unpacked elements arbitrarily, stick with one or the other.

timeline
tags question: http://stackoverflow.com/q/51101252
tag name: timeline
type: Tag

http://stackoverflow.com/comment/89050022
comment on: http://stackoverflow.com/q/51015891
score: 0
has text: @Amadan i'm try to change the value of "En: -2.942 " to 0 and then i run my python code and now the error is changing to -1.8038-1.8038. But when i separated this data into small part my code is working. Do i have a problem with the memory? I'm not sure the problem is json data
type: Comment
type: QuestionComment

h2o
tags question: http://stackoverflow.com/q/51100483
tag name: h2o
type: Tag

ssis
tags question: http://stackoverflow.com/q/51077064
tag name: ssis
tags question: http://stackoverflow.com/q/51160071
type: Tag

http://stackoverflow.com/a/51019678
score: 3
upvote count: 3
has body: The department field on your Employee model is a ForeignKey field, but in your AdForm you define it as CharField. You could fix the field definition in your form. Alternatively, you could also simply remove the explicit field definition. When using a model form, Django will select the correct field type for you. class AdForm(forms.ModelForm): class Meta: model = Employee fields = ('employee_name', 'surname', 'address', 'qualification', 'contact_num', 'department') This will render the department field as a &lt;select&gt; widget, allowing you to select from your (pre-existing) departments.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51019461
answers question: http://stackoverflow.com/q/51019461
type: Answer
has comment: http://stackoverflow.com/comment/89034865

http://stackoverflow.com/comment/89503556
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51262675
type: AnswerComment
has text: Note that the first step MAYBE optional. Try out all the other steps WITHOUT the downloading the latest version of PyCharm and if it works, well and good. If it doesn't then you may have to download the latest version in the link provided.

http://stackoverflow.com/q/51147519
has body: I have a df.apply which return a series with Key/Value like below (let's call it column A): Col. A 40237 1.871111 40239 1.280556 40240 1.784167 40241 0.049167 40243 0.011389 40244 0.660278 40245 1.512500 I would like to save these values into various columns using the value of a separate column (column B). Column B can contain 6 different distinct strings (4 in the example). Col. B 40237 Open 40239 Open 40240 In Progress 40241 Closed 40243 Waiting 40244 In Progress 40245 Waiting I want to save my column A values into one of 4 columns based on value of column B. End result is: Col. A Col. B Open Time In Progress Time Closed Time Waiting Time 40237 1.871111 Open 1.871111 np.nan np.nan np.nan 40239 1.280556 Open 1.280556 np.nan np.nan np.nan 40240 1.784167 In Progress np.nan 1.784167 np.nan np.nan 40241 0.049167 Closed np.nan np.nan 0.049167 np.nan 40243 0.011389 Waiting np.nan np.nan np.nan 0.011389 40244 0.660278 In Progress np.nan 0.660278 np.nan np.nan 40245 1.512500 Waiting np.nan np.nan np.nan 1.512500 Now my best efforts to get this to work was: for key in output.index: df.loc[key,(df['Col. B'] + " Time")] = output.loc[key] However my error is ValueError: cannot index with vector containing NA / NaN values. I'm not sure why exactly, though my columns in general do have plenty of nan's.
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51147564
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89279141
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51147564
has comment: http://stackoverflow.com/comment/89279170
has title: Pandas - Store output conditionally
tagged with: pandas

http://stackoverflow.com/q/51100501
has title: How to continue looping after a module defined exception in Python?
has comment: http://stackoverflow.com/comment/89191124
has comment: http://stackoverflow.com/comment/89192388
type: Question
has comment: http://stackoverflow.com/comment/89192002
has comment: http://stackoverflow.com/comment/89192246
has answer: http://stackoverflow.com/a/51101542
has comment: http://stackoverflow.com/comment/89190005
linked to: http://stackoverflow.com/q/15600707
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/51101542
favorite count: 0
tagged with: python-3.x
has body: I loop though a list of currencies in order to download price series from an API and it happens that some of them are not supported so that it raises a module defined exception class : ExchangeError: This currency pair is not supported. When it occurs I would like to continue the loop to the next currency but for some reason I'm unable to handle the module exception. Here is an example that works fine with a built-in exception : f = [1,2,3,4,'A',5] def foo(nb): return nb /2 for i in f : try: print(foo(i)) except TypeError : continue As expected it returns : 0.5 1 1.5 2 2.5 But as soon as it is a module (or user defined) exception it throws an error saying the exception is not defined : @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def apiFetchOHLC(obj, currency, timeframe, option): ohlcv = obj().fetch_ohlcv(currency, timeframe, since = option) return ohlc for c in currencies_list : ... try : # Download data ohlc = apiFetchOHLC(obj, c, tf, maxCandlesLimit) # except : # works fine except ExchangeError : # doesn't work print("Oops! That was no valid currency. Continue...") continue This is the error I get when I run the loop : except ExchangeError: NameError: name 'ExchangeError' is not defined To make it works I need to remove the exception type ExchangeError but to me it is not a workaround because it will continue the loop whatever the exception is, and sometimes I need to retry the download. How can I achieve this with try and except or with the retrying package ? (link)
has comment: http://stackoverflow.com/comment/89192138
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51102697
score: 1
accepted answer: http://stackoverflow.com/a/51102697

http://stackoverflow.com/a/51135320
downvote count: 0
score: 1
has body: I believe need resample with mean: df = df.resample('15Min').mean() Alternative solution with Grouper: df = df.groupby(pd.Grouper(freq='15Min')).mean() print (df) variable_1 (Settlement_Date,) 2018-06-30 20:30:00 4.166667 2018-06-30 20:45:00 4.466667 2018-06-30 21:00:00 2.600000
upvote count: 1
answers question: http://stackoverflow.com/q/51135289
type: Answer

pyinstaller
tags question: http://stackoverflow.com/q/51069952
tags question: http://stackoverflow.com/q/51012750
tags question: http://stackoverflow.com/q/51024190
tags question: http://stackoverflow.com/q/51137192
type: Tag
tags question: http://stackoverflow.com/q/51060894
tags question: http://stackoverflow.com/q/51150492
tag name: pyinstaller
tags question: http://stackoverflow.com/q/51124464
tags question: http://stackoverflow.com/q/51133340
tags question: http://stackoverflow.com/q/51093366
tags question: http://stackoverflow.com/q/51132467
tags question: http://stackoverflow.com/q/51134270
tags question: http://stackoverflow.com/q/51129948
tags question: http://stackoverflow.com/q/51069774
tags question: http://stackoverflow.com/q/51017068
tags question: http://stackoverflow.com/q/51155045
tags question: http://stackoverflow.com/q/51155505
tags question: http://stackoverflow.com/q/51108155

http://stackoverflow.com/q/51106747
has body: I'm trying to write a program that will allow me to solve a system of equations using numpy, however, I want the solution to be non-trivial (not all zeros). Obviously the program is just going to set everything to 0, and boom, problem solved. I attempted to use a while loop (like below), but quickly found out it's going to continue to spit 0 back at me. I don't care if I end up using numpy, I'm open to other solutions if it's more elegant. I actually haven't solved this particular set by hand, maybe the trivial solution is the only solution. If so, the principle still applies. Numpy seems to always spit 0 back. Any help would be appreciated! Thanks. x1 = .5 x2 = .3 x3 = .2 x4 = .05 a = np.array([[x1,x2],[x3,x4]]) b = np.array([0,0]) ans = np.linalg.solve(a,b) while ans[0] == 0 and ans[1] == 0: print ("got here") ans = np.linalg.solve(a,b) print(ans)
has comment: http://stackoverflow.com/comment/89200631
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1835246
score: 1
upvote count: 1
has title: Getting the non-trivial solution to a set of linear equations
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89200568
has answer: http://stackoverflow.com/a/51106799
answer count: 2
has answer: http://stackoverflow.com/a/51106849
downvote count: 0

http://stackoverflow.com/q/51107398
answer count: 1
has body: I want to get data(user) from dropdown by using Ajax success function. I want when clicking 'add member',it will show username under the button,and also the username will stay when refreshing the page. {% block script %} var url = $( '#selection-button' ).attr( 'action' ); $("#selection-button").on('click', function(e) { e.preventDefault(); var value =$('#member_list').val(); $.ajax({ type:'POST', url: '{% url 'project:project_add_member' project_id=project_id %}', data: { user_id:value }, success:function (result) { $("#res").append(value); }, error:function (result) { alert('error'); console.info(data); } }); }); {% endblock %}
has title: how to use Ajax success function store data in database?Django
tagged with: ajax
tagged with: python
type: UnansweredQuestion
tagged with: django
type: Question
score: 0
has answer: http://stackoverflow.com/a/51109031

http://stackoverflow.com/a/73187732
downvote count: 1
has body: def shampoo_instructions(num_cycles): if num_cycles &lt; 1: print ('Too few') elif num_cycles &gt; 4: print ('Too many') else: n = 0 while n != num_cycles: n = n + 1 print ( n ,':Lather and rinse.') print ('Done.') this is working code. the other answers provide an infinite loop with the use of &lt; or &lt;= operator in the while statement.
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51116712
has comment: http://stackoverflow.com/comment/129295318
score: -1

http://stackoverflow.com/comment/89119560
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51064760
has text: @ pckofwolfs I have edited my comment. This, would create a numpy array with 100 elements, each of length 30, which is pretty much the same as python list, but implemented in a more compact way: https://stackoverflow.com/questions/993984/why-numpy-instead-of-python-lists
type: AnswerComment

http://stackoverflow.com/a/56266602
score: 0
has comment: http://stackoverflow.com/comment/99153752
type: Answer
answers question: http://stackoverflow.com/q/51126115
has comment: http://stackoverflow.com/comment/99174794
has body: I know two ways: for x in [1.23456, None]: print( '1: {}'.format(x is not None and '{:0.4f}'.format(x) or 'None') ) print( '2: {:{x_fmt}}'.format(x, x_fmt=x is not None and '0.4f' or '') ) Out: 1: 1.2346 2: 1.2346 1: None 2: None

http://stackoverflow.com/comment/89133833
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51067181
has text: If `Component { }` is unnecessary, what should I use instead in the `MyDelegate.qml`? I have to surround the `id:...` and `text:...` with something.

http://stackoverflow.com/comment/89290654
type: Comment
type: QuestionComment
has text: Sounds similar to [PY-28339](https://youtrack.jetbrains.com/issue/PY-28339) ticket in PyCharms' bug tracker. Please feel free to vote/comment there.
score: 1
comment on: http://stackoverflow.com/q/51034459

http://stackoverflow.com/a/51137599
type: Answer
has body: In other words, you want to skip outputting a blank line if the next line is find me. Since you already have all the lines in readcontent, you can simply peek ahead with the next index: with open("input.txt", "r") as infile: readcontent = infile.readlines() with open("output.txt", "w") as out_file: for index, line in enumerate(readcontent): if not line.strip() and readcontent[index + 1].strip() == 'find me': continue if line.strip() == 'find me': out_file.write('Added New line\n') out_file.write(line)
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51137309
accepted answer of: http://stackoverflow.com/q/51137309
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51048792
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51049393
has title: stdout/stderr - ValueError: too many values to unpack (expected 2)
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51049393
tagged with: python
has comment: http://stackoverflow.com/comment/89088885
type: AnsweredQuestion
has body: I have a script that was working fine in python 2.7 but now in 3.6 it's failing. Particularly I am having issues at this point The function below is being called by the following line of code: exec_command(ssh, 'systemctl status myservice', timeout=60) Which then executes the function. ssh in this case is an ssh connection using paramiko. def exec_command(ssh, cmd, timeout, want_exitcode=False): # one channel per command stdout, stderr = ssh.exec_command(cmd) # get the shared channel for stdout/stderr channel = stdout.channel # indicate that we're not going to write to that channel anymore channel.shutdown_write() # read stdout/stderr in order to prevent read block hangs stdout_chunks = [] stdout_chunks.append(stdout.channel.recv(len(stdout.channel.in_buffer))) When running I get the following error: File "path\myscript.py", line 54, in exec_command ValueError: too many values to unpack (expected 2) [13340] Failed to execute script myscript Line 54 is stdout, stderr = ssh.exec_command(cmd)
type: Question

http://stackoverflow.com/comment/89199302
has text: @Nils There, I fixed it. Column titles don't necessarily match up with the columns but close enough.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51105917

http://stackoverflow.com/q/51046942
tagged with: python
has comment: http://stackoverflow.com/comment/89085024
has comment: http://stackoverflow.com/comment/89372930
type: Question
type: AnsweredQuestion
has title: Implementing luigi dynamic graph configuration
has answer: http://stackoverflow.com/a/53125632
score: 12
has comment: http://stackoverflow.com/comment/89371017
linked to: http://stackoverflow.com/q/42563175
has comment: http://stackoverflow.com/comment/89369649
upvote count: 12
tagged with: luigi
accepted answer: http://stackoverflow.com/a/53125632
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89372508
favorite count: 0
linked to: http://stackoverflow.com/q/49987595
tagged with: python-3.x
has body: I am new to luigi, came across it while designing a pipeline for our ML efforts. Though it wasn't fitted to my particular use case it had so many extra features I decided to make it fit. Basically what I was looking for was a way to be able to persist a custom built pipeline and thus have its results repeatable and easier to deploy, after reading most of the online tutorials I tried to implement my serialization using the existing luigi.cfg configuration and command line mechanisms and it might have sufficed for the tasks' parameters but it provided no way of serializing the DAG connectivity of my pipeline, so I decided to have a WrapperTask which received a json config file that would then create all the task instances and connect all the input output channels of the luigi tasks (do all the plumbing). I hereby enclose a small test program for your scrutiny: import random import luigi import time import os class TaskNode(luigi.Task): i = luigi.IntParameter() # node ID def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.required = [] def set_required(self, required=None): self.required = required # set the dependencies return self def requires(self): return self.required def output(self): return luigi.LocalTarget('{0}{1}.txt'.format(self.__class__.__name__, self.i)) def run(self): with self.output().open('w') as outfile: outfile.write('inside {0}{1}\n'.format(self.__class__.__name__, self.i)) self.process() def process(self): raise NotImplementedError(self.__class__.__name__ + " must implement this method") class FastNode(TaskNode): def process(self): time.sleep(1) class SlowNode(TaskNode): def process(self): time.sleep(2) # This WrapperTask builds all the nodes class All(luigi.WrapperTask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) num_nodes = 513 classes = TaskNode.__subclasses__() self.nodes = [] for i in reversed(range(num_nodes)): cls = random.choice(classes) dependencies = random.sample(self.nodes, (num_nodes…
tagged with: data-pipeline

http://stackoverflow.com/comment/89132190
has text: @bobrobbob that is a good idea. Unfortunately I am not very experienced with referrers - how would I find out what to enter before making the url request?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51069581

http://stackoverflow.com/a/51136806
has comment: http://stackoverflow.com/comment/138737635
has body: EDIT: For last pandas version use concat: df = pd.DataFrame(np.arange(1, 9).reshape(2, -1), columns=list('ABCD')) print (df) A B C D 0 1 2 3 4 1 5 6 7 8 df1 = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns) df = pd.concat([df1, df], ignore_index=True) print (df) A B C D 0 NaN NaN NaN NaN 1 1.0 2.0 3.0 4.0 2 5.0 6.0 7.0 8.0 Old pandas versions: Use append of DataFrame with one empty row: df1 = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns) df = df1.append(df, ignore_index=True) print (df) A B C D E 0 NaN NaN NaN NaN NaN 1 1.0 2.0 3.0 4.0 5.0 2 4.0 5.0 6.0 7.0 8.0
type: Answer
has comment: http://stackoverflow.com/comment/89257949
upvote count: 14
has comment: http://stackoverflow.com/comment/89257997
has comment: http://stackoverflow.com/comment/89257910
score: 14
has comment: http://stackoverflow.com/comment/138729799
answers question: http://stackoverflow.com/q/51136283
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51136283

http://stackoverflow.com/a/51109868
score: 1
accepted answer of: http://stackoverflow.com/q/51109792
has body: searching a regex with a bytes input works, but of course your variable name is treated literally. You have to inject your variable, for instance by using format on the string, then encode to bytes (bytes object doesn't have format so encode it afterwards (you cannot use b prefix here): pattern = re.compile(r'(\.\W+)?([^.]?{}[^.]*?\.)'.format(UserSpecifiedPattern).encode(), re.DOTALL | re.IGNORECASE | re.MULTILINE ) notes: it works for this particular pattern which doesn't make use of {} to repeat expressions. If you have to use that, double the braces: ex: {{1,5}} depending on the pattern you're passing, you may need to use re.escape on it if you want regex to see it literally (it doesn't matter much with words)
answers question: http://stackoverflow.com/q/51109792
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89110925
has text: shouldn't @sum be \sum in LaTeX? (inside the formula tags the text is LaTeX code not doxygen comment).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51060126

http://stackoverflow.com/a/53573939
score: 3
upvote count: 3
has body: Not sure if you are still struggling with this. In my case, I am using CentOS 7, and this Error is because my system did not install ffmpeg. If you want to test ffmpeg is installed or not, try this in console: $ ffmpeg Just follow this instruction and problem should be fixed.
answers question: http://stackoverflow.com/q/51134945
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89196655
has text: At least make it a ``set`` instead of ``list`` to retain the O(1) test.
type: AnswerComment
comment on: http://stackoverflow.com/a/51104752
type: Comment
score: 1

google-cloud-platform
tags question: http://stackoverflow.com/q/51038887
tags question: http://stackoverflow.com/q/51094303
tags question: http://stackoverflow.com/q/51120038
tags question: http://stackoverflow.com/q/51084056
tags question: http://stackoverflow.com/q/51076475
tags question: http://stackoverflow.com/q/51154921
tags question: http://stackoverflow.com/q/51143556
tags question: http://stackoverflow.com/q/51030233
tags question: http://stackoverflow.com/q/51078146
type: Tag
tags question: http://stackoverflow.com/q/51083239
tags question: http://stackoverflow.com/q/51101912
tags question: http://stackoverflow.com/q/51015928
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/51160954
tags question: http://stackoverflow.com/q/51131849
tags question: http://stackoverflow.com/q/51059993
tags question: http://stackoverflow.com/q/51148293
tags question: http://stackoverflow.com/q/51137714
tags question: http://stackoverflow.com/q/51157514
tags question: http://stackoverflow.com/q/51136741
tags question: http://stackoverflow.com/q/51062928
tags question: http://stackoverflow.com/q/51111611

http://stackoverflow.com/comment/89251411
score: 0
type: Comment
has text: thanks A lot, Robbie, Wanted to ask, what if I had 3 Variables to be plotted (A, B, C). How would we adjust the width?
type: AnswerComment
comment on: http://stackoverflow.com/a/51131836

http://stackoverflow.com/comment/89206135
has text: @MikeyMike Updated my answer and added a create table part so I could actually create and see the data myself. Works fine for me.
comment on: http://stackoverflow.com/a/51093339
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51124676
has title: Pandas: selecting values of array with [columnname][rownumber] just works for multiindex
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51125065
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
upvote count: 3
has body: I try to analyze data with the help of pivot tables using Pandas. For multiindex everything works fine. I have this pivot table: &gt;&gt;&gt;print(pivtab) count win pp ps 8000 8200 4 2 8100 8200 2 1 8300 3 1 Now I can select for example the value in the 2nd row in the column "count" with &gt;&gt;&gt;print(pivtab["count"][1]) 2 The unexpected behaviour comes when using just a single index pivot table. The pivot table looks like this: count win pp 8000 4 2 8100 5 2 Now when I try to use the same way with print(pivtab["count"][1]) I get an KeyError: 1. It seems as if Python now doesn't accept the row number but the row name (=index). With &gt;&gt;&gt;print(pivtab["count“][8100]) 5 everything works fine. The complete code looks like this: import pandas as pd columns = ["count","game_Id","season","win","pp","ps"] matrix = pd.DataFrame(columns=columns) # Create a test matrix for i in range(1,10): win = 0 if int(i/2) == i/2: win = 1 pprim = 8000 if i &gt; 4: pprim = 8100 psub = 8200 if i &gt; 6: psub = 8300 new_row = pd.DataFrame(1, i, 11, win, pprim, psub, columns=columns) matrix = matrix.append(new_row,ignore_index=True) print(matrix) pivtab = pd.pivot_table(matrix, index=["pp","ps"], values=["count","win"], aggfunc="sum") print("\n", pivtab) print(pivtab["count"][1]) To be completely confused I tried another test matrix... and here everything works fine! import pandas as pd matrix = pd.DataFrame({"A":["hey","hey","boo","boo"], "B":[1,2,3,2], "valueA":[123,441,190,123], "valueB":[5,5,6,6]}) piv_matrix = pd.pivot_table(matrix, index=["A"], values=["valueA","valueB"], aggfunc="sum") print(piv_matrix) print("\nValue:", piv_matrix["valueA"][1]) Result: valueA valueB A boo 313 12 hey 564 10 Value: 564 I would be happy if you could explain to me the reason for this unexpected (at least for me) behaviour. Thanks!
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/51125065
score: 3
tagged with: multi-index

http://stackoverflow.com/q/51028456
score: 3
tagged with: image-processing
has answer: http://stackoverflow.com/a/51068555
has comment: http://stackoverflow.com/comment/89062945
has body: Using OpenCV in python, I am trying to stitch multiple images that are out of order. I have a functioning stitch method that stitches two images, given which one is on the left and right. def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False): """ This function performs image stitching with help of other member functions of Stitcher class. Args: images (list) : List of two images ordered left to right ratio (float) : Ratio for Lowe's Test reprojThresh (float) : reprojThresh parameter for RANSAC for homography computation showMatches (bool) : Flag for marking showing matches on input images """ (imageL, imageR) = images #Find key points and features for input images (kpsR, featuresR) = self.find_kp_features(imageR) (kpsL, featuresL) = self.find_kp_features(imageL) # Match features between two input images M = self.matchKeypoints(kpsR, kpsL, featuresR, featuresL, ratio, reprojThresh) if M is None: return None (matches, H, status) = M #Perform perspective correction on second image (imageR) result = cv2.warpPerspective(imageR, H, (imageR.shape[1] + imageL.shape[1], imageR.shape[0])) #Insert Left image (imageL) in result to obtai stitched image result[0:imageL.shape[0], 0:imageL.shape[1]] = imageL if showMatches: vis = self.drawMatches(imageR, imageL, kpsR, kpsL, matches, status) return (result, vis) return result source: https://github.com/TejasBob/Panorama/blob/master/image-stitching-report.pdf I have read through the following paper, but I am still confused on an approach to stitching multiple images together that are in a random order. I have considered using a bundle adjustment algorithm, but am unaware of a possible implementation for this. My question is what would be the best way to stitch together multiple images that are out of order? Some suitable material or pseudo code of what I can do will also be helpful.
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89087998
tagged with: image-stitching
has comment: http://stackoverflow.com/comment/89338515
accepted answer: http://stackoverflow.com/a/51068555
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: computer-vision
type: Question
tagged with: opencv
has title: How to stitch multiple images that are in a random order using OpenCV in python?

http://stackoverflow.com/comment/89256581
has text: There's a typo in @ekhumoro 's comment. To find out the file from which 'dash' was imported, do `import dash ; print(dash.__file__)` (without quotes).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51132948
score: 1

http://stackoverflow.com/comment/89131687
type: QuestionComment
type: Comment
has text: Have you tried using `pip`?
score: 0
comment on: http://stackoverflow.com/q/51070965

http://stackoverflow.com/comment/89061718
score: 0
comment on: http://stackoverflow.com/q/51034737
type: Comment
type: QuestionComment
has text: For the second part https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe

http://stackoverflow.com/q/51069903
favorite count: 0
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51070527
has body: My dataframe looks like this: Date AAPL NFLX INTC AAPL_Ret NFLX_Ret INTC_Ret 0 2008-01-31 27.834286 3.764286 25.350000 1 2008-02-29 27.847143 3.724286 24.670000 -0.07 0.25 -0.05 2 2008-03-31 25.721428 3.515714 22.670000 0.15 0.10 0.06 3 2008-04-30 25.377142 3.554286 22.879999 etc 4 2008-05-31 24.464285 3.328571 22.260000 I want to calculate quantiles for the stock returns going across the rows in my df. So for example, the quantiles (let's say we use 3 groups) would rank the first row of returns as AAPL and INTC in quantile 3, and NFLX in quantile 1 (since it's the highest return). The expected output would be (below, scroll to right): Date AAPL NFLX INTC AAPL_Ret NFLX_Ret INTC_Ret AAPL_Ret Q NFLX_Ret Q INTC Ret Q 0 2008-01-31 27.834286 3.764286 25.350000 1 2008-02-29 27.847143 3.724286 24.670000 -0.07 0.25 -0.05 3 1 3 2 2008-03-31 25.721428 3.515714 22.670000 0.15 0.10 0.06 1 2 2 3 2008-04-30 25.377142 3.554286 22.879999 etc 4 2008-05-31 24.464285 3.328571 22.260000 What I've tried: I originally wanted to use pd.qcut with something like axis=1 in the formula but the method doesn't take an argument like that. So I thought I could do something like a for loop (since I will eventually expand the file to many stocks) for col in df.columns: if '_Ret' in col: df[col+'_Rank'] = df.apply(pd.qcut(df[col], 5, labels=np.arange(5, 0, -1), axis=1) But I'm stuck here. Would greatly appreciate your help, am a python beginner. Thanks!
has title: Ranking across rows
type: Question
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51070527
score: 1

http://stackoverflow.com/q/51044904
type: Question
has body: I want to catch outliers in the 16 x 224 array by using the Elliptic Envelope from sklearn. The problem is that when I predict the array, it gives me different dimension: ell = EllipticEnvelope() ell.fit(c) b = ell.predict(c) C is 16 x 224 as I said before, and the "b" is size 16 x 1.
has title: Elliptic Envelope outlier detection
downvote count: 4
tagged with: deep-learning
answer count: 1
accepted answer: http://stackoverflow.com/a/51052846
tagged with: scikit-learn
favorite count: 0
score: -3
tagged with: python
type: AnsweredQuestion
tagged with: outliers
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/51052846

http://stackoverflow.com/comment/89150942
has text: Are numbers integer? What is range of n?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51080191
type: Comment

http://stackoverflow.com/q/51033026
favorite count: 0
has comment: http://stackoverflow.com/comment/89058948
has body: I've encountered this strange problem with opening/closing files in python. I am trying to do the same thing in python that i was doing successfully in matlab, and i am getting a problem communicating with some software through text files. I've come up with a strange workaround to solve the problem, but i dont understand why it works. I have software that communicates with a some lab equipment. To communicate with this software, i write a file ('wavefile.txt') to a specific folder, containing parameters to send to the device. I then write another file named 'request.txt' containing the location of this first file ('wavefile.txt') which contains the parameters to send to the device. The software is constantly checking this folder to find the file named 'request.txt' and once it finds it, it will read the parameters in the file which is specified by the text in 'request.txt' and then delete 'request.txt'. The software/equipment developer instructs to give a 50 ms second delay before closing the 'request.txt' file. original matlab code that works: home = cd; cd \\CREOL-FAST-01\data fileID = fopen('request.txt', 'wt'); proj = 'C:\\dazzler\\data\\wavefile.txt'; fprintf(fileID, proj); pause(0.05); fclose('all'); cd(home); original python code that does not work: home = os.getcwd() os.chdir(r'\\CREOL-FAST-01\data') with open('request.txt', 'w') as file: proj = r'C:\dazzler\data\wavefile.txt' file.write(proj) time.sleep(0.05) os.chdir(home) Every time the device program reads the 'request.txt' when its working with matlab, it deletes it immediately after matlab closes it. When i run that code with python it works SOMETIMES, maybe 1 in every 5 tries will be successful and the parameters are sent. The 'request.txt' file is always deleted with the python code above,but the parameters i've input are clearly not sent to my lab device. My guess is that when i write the file in python, the device program is able to read it before python writes the text to it, so its just opening t…
tagged with: python
has comment: http://stackoverflow.com/comment/89059132
linked to: http://stackoverflow.com/q/7127075
has title: python write file vs matlab write file, read by another software
tagged with: matlab
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/51033305
upvote count: 1
has answer: http://stackoverflow.com/a/51033305
has answer: http://stackoverflow.com/a/51033159
downvote count: 1
has comment: http://stackoverflow.com/comment/89058611
type: Question
has answer: http://stackoverflow.com/a/51050663
has comment: http://stackoverflow.com/comment/89136663
answer count: 3
accepted answer: http://stackoverflow.com/a/51033159

http://stackoverflow.com/comment/89049752
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51028364
has text: Could you post a portion of your dataframe so that we can provide a comparable use case example?
type: Comment

http://stackoverflow.com/comment/89199068
score: 0
type: Comment
type: QuestionComment
has text: Apparently `tcp_connect` is `None`. Have you done any debugging?
comment on: http://stackoverflow.com/q/51105996

http://stackoverflow.com/q/51018421
has body: I'm trying to automate a data refresh in Power BI, based on specific parameters. In order I've adjusted the Power BI refresher script (https://github.com/dubravcik/pbixrefresher-python), based on PyWinAuto. To adjust the parameters, I have to open and use a dropdown menu in the ribbon of Power BI and I suspect that when opening the dropdown menu, the focus is still on the main screen of PowerBI, so I cannot manipulate inside the dropdown menu. How could I identify and focus on the dropdown menu with PyWinAuto? (See also https://i.sstatic.net/jk6kS.png) # Focus on the Power BI window app = Application(backend = 'uia').connect(path = PBIDesktop.exe) win = app.window(title_re = '.*Power BI Desktop') win.wait("enabled", timeout = 300) win.set_focus() win.wait("enabled", timeout = 300) # Open the dropdown menu with Alt+H, then Q win.type_keys('%HQ') # Next part doesn't work, I suspect because of no focus on the dropdown menu win.type_keys('{DOWN}{DOWN}{ENTER}')
tagged with: powerbi
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89034049
tagged with: pywinauto
favorite count: 0
tagged with: focus
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/60666603
tagged with: powerbi-desktop
upvote count: 1
answer count: 1
has title: Pywinauto focus on new dropdown
type: UnansweredQuestion

http://stackoverflow.com/comment/89058980
has text: @ronnLee Nothing except `flask`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51015205
score: 0

http://stackoverflow.com/comment/89070816
has text: What exactly do you mean by "next stage"?
score: 0
comment on: http://stackoverflow.com/q/51033792
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89261092
type: Comment
score: 1
has text: You don't need the `if` keyword after the `and` keyword. The `and` is correct. You are selecting all files in the directory that are not older than a month AND they contain either 'summary' or 'summaries'
type: QuestionComment
comment on: http://stackoverflow.com/q/51138484

http://stackoverflow.com/a/51073909
upvote count: 1
answers question: http://stackoverflow.com/q/51065918
score: 1
has comment: http://stackoverflow.com/comment/89139565
accepted answer of: http://stackoverflow.com/q/51065918
has comment: http://stackoverflow.com/comment/89145585
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89141664
downvote count: 0
has body: While btilly's answer is absolutely correct, it is a bit more than what's needed for this problem, at least in python. Using the itertools library and the eval() function, you can get by with a much shorter and simpler approach. Do note that eval() and exec() are considered insecure, since they will execute anything passed, however as a script for personal use it should be fine. Any malicious code would probably trip an exception casting the inputs to ints anyways. from itertools import permutations coeffs = list(map(int, input("Coefficents, separated by spaces:\n").split())) target = int(input("Target value:\n")) operators = ["({}+{})","({}-{})","({}*{})","({}/{})","({}**{})","({}**(1.0/{}))"] def make_expr(expr, coeffs, target): if not coeffs: try: return eval(expr), expr except OverflowError: return None except ArithmeticError: return None solutions = [make_expr(op.format(expr, coeffs[0]), coeffs[1:], target) for op in operators] solutions += [make_expr(op.format(coeffs[0], expr), coeffs[1:], target) for op in operators] solutions = [x for x in solutions if x is not None] val, expr = min(solutions, key=lambda x: abs(x[0]-target)) return val, expr def find_best(coeffs, target): assert(len(coeffs) &gt; 1) solutions = [make_expr(perm[0], perm[1:], target) for perm in permutations(coeffs)] solutions = [x for x in solutions if x is not None] val, expr = min(solutions, key=lambda x: abs(x[0]-target)) return "Closest value: {0}\nExpression: {1}".format(val, expr) print(find_best(coeffs, target)) To support more operators, just insert them into the list, with {}'s where the arguments go, and surrounded by paretheses. I've added support for extra operators, however since I do not shortcut the iteration when it finds a perfect solution, it can take a very long time for 3+ operators.
has comment: http://stackoverflow.com/comment/89167572
has comment: http://stackoverflow.com/comment/89168035
type: Answer

http://stackoverflow.com/comment/89286756
comment on: http://stackoverflow.com/q/51151328
type: Comment
type: QuestionComment
score: 3
has text: If it takes too long too load, buy a new computer. If it just takes too long to plot simply downsample your signal.

http://stackoverflow.com/comment/89235568
score: 0
type: AnswerComment
type: Comment
has text: Your solution does not check whether the source string contains any other char than a-e. If it does, the check should fail.
comment on: http://stackoverflow.com/a/51124947

http://stackoverflow.com/comment/89194183
comment on: http://stackoverflow.com/a/51103197
has text: I used `df.set_index(['week'], inplace=True)` to get rid of the index column, I removed this string and everything started work perfectly. Thank you)
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89181464
has text: @Abhishek, Thanks so much, Perfectly bringing the data as desired, can't expect better than this ... You are the Best.... Let me now try to import this json to mongoDB, I hope it works !!
type: Comment
comment on: http://stackoverflow.com/q/51095528
score: 0
type: QuestionComment

http://stackoverflow.com/q/51018477
has title: Can't parse certain information applying conditional statement
has comment: http://stackoverflow.com/comment/89030654
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51019070
has comment: http://stackoverflow.com/comment/89030468
tagged with: selenium-webdriver
score: 2
upvote count: 2
tagged with: selenium
tagged with: web-scraping
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51019070
type: Question
has body: I've written a script in python in combination with selenium to parse the emails of some companies out of a webpage. The problem is that the emails are either within span[data-mail] or span[data-mail-e-contact-mail]. If I try the two conditions seperately, I can get all the emails. However, when I try to wrap them within try:except:else block, they no longer work. Where am I going wrong? website link This is the script: from selenium import webdriver from bs4 import BeautifulSoup url = "replace with the link above" driver = webdriver.Chrome() driver.get(url) soup = BeautifulSoup(driver.page_source,'html.parser') for links in soup.select("article.vcard"): try: #the following works when tried individually email = links.select_one(".hit-footer-wrapper span[data-mail]").get("data-mail") except: #the following works as well when tried individually email = links.select_one(".hit-footer-wrapper span[data-mail-e-contact-mail]").get("data-mail-e-contact-mail") else: email = "" print(email) driver.quit() When I execute the above script, It prints nothing. They both work, if printed individually, though.
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51112813
favorite count: 0
has comment: http://stackoverflow.com/comment/89212507
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89212728
score: 1
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy
type: Question
has body: If I run my query in python, it returns a syntax error. However, if I run this with navicat, it work's fine. Why doesn't it run in python? sql_query INSERT INTO solarsystem ( solarsystemName, solarsystemPositionX, solarsystemPositionY, solarsystemSectorId, solarsystemAngle ) VALUES ('Lima [698/562]',698,562,13,171); SELECT LAST_INSERT_ID(); error 1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()' [EDIT] create.py [...] args = (solarsytem['solarsystemName'], solarsytem['x_pos'], solarsytem['y_pos'], solarsytem['sector_id'], solarsytem['angle']) with self.engine.begin() as connection: result_proxy = connection.execute(sql_query, args).first() [...] UPDATE If I try the INSERT as single query this works. However, SELECT LAST_INSERT_ID(); didn't work. It returns: TypeError: not all arguments converted during string formatting
has comment: http://stackoverflow.com/comment/89212874
has answer: http://stackoverflow.com/a/51113377
downvote count: 0
tagged with: navicat
has title: syntax error at 'SELECT LAST_INSERT_ID()'
tagged with: python-2.7
answer count: 1

random
tags question: http://stackoverflow.com/q/51031432
tags question: http://stackoverflow.com/q/51112867
tags question: http://stackoverflow.com/q/51072541
tags question: http://stackoverflow.com/q/51013319
tags question: http://stackoverflow.com/q/51046266
tags question: http://stackoverflow.com/q/51125006
tags question: http://stackoverflow.com/q/51011601
tags question: http://stackoverflow.com/q/51029890
tags question: http://stackoverflow.com/q/51156652
tags question: http://stackoverflow.com/q/51071212
tags question: http://stackoverflow.com/q/51054497
tag name: random
tags question: http://stackoverflow.com/q/51088335
tags question: http://stackoverflow.com/q/51120502
type: Tag
tags question: http://stackoverflow.com/q/51049603

http://stackoverflow.com/a/51161549
score: 7
has comment: http://stackoverflow.com/comment/89323843
has comment: http://stackoverflow.com/comment/117057396
has comment: http://stackoverflow.com/comment/89323893
has body: The first point is that you need to create a ScalarMappable for your colorbar. You need to define the colormap, which in your case is 'viridis' and specify the maximum and minimum of the values you want for the colorbar. Then because it uses numeric time values you want to reformat those. import matplotlib.pyplot as plt import pandas as pd # Define your mappable for colorbar creation sm = plt.cm.ScalarMappable(cmap='viridis', norm=plt.Normalize(vmin=df.index.min().value, vmax=df.index.max().value)) sm._A = [] df.plot(legend=False, colormap='viridis', figsize=(12,7)); cbar = plt.colorbar(sm); # Change the numeric ticks into ones that match the x-axis cbar.ax.set_yticklabels(pd.to_datetime(cbar.get_ticks()).strftime(date_format='%b %Y'))
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51160705
has comment: http://stackoverflow.com/comment/89341954
answers question: http://stackoverflow.com/q/51160705

http://stackoverflow.com/q/51025418
tagged with: matplotlib
has body: I have a png image as follows: I wrote the following script to read into matplotlib. import numpy as np, matplotlib.pyplot as plt from PIL import Image fi = "map.png" data = np.array(Image.open(fi)) print data.shape plt.imshow(data) plt.show() But the image looks different. How to make it look similiar to the first one? I mean, the colors.
has answer: http://stackoverflow.com/a/51025924
tagged with: image
type: Question
answer count: 2
has title: Strange image produced by matplotlib
downvote count: 0
has answer: http://stackoverflow.com/a/51025576
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51025576
score: 1
possible better answer: http://stackoverflow.com/a/51025924

http://stackoverflow.com/q/51073113
accepted answer: http://stackoverflow.com/a/51091326
downvote count: 1
type: Question
tagged with: mousewheel
tagged with: ttk
has title: Need to install a mousewheel in a ttk notebook with a scrollbar
score: -1
tagged with: scrollbar
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89136211
has answer: http://stackoverflow.com/a/51091326
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has body: I need the mousewheel to function on all tabs. Right now it only works on the friday tab. The controller for the mouse wheel is around line 18. I've got two possible approaches for controlling the mouse wheel, one of which is commented out.The second works if I replace "bind_all" with "bind" but then only the areas that are not covered by widgets are scrollable via the mouse wheel. Anyhow, the fact that the mouse wheel works on the last tab tells me it is possible for the mouse wheel to work on all the tabs, I just can't figure it out. Edit: I prematurely posted a solution for this problem. I had to take that back as I found the areas of the canvas covered by widgets could not scrolled with the mouse wheel. When the whole canvas is covered, the mouse wheel was useless. from tkinter import * from tkinter import ttk out_root = Tk() out_root.title("KLUSTERBOX - Output") # list the names of the tabs tab = ["saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"] C = ["C0","C1","C2","C3","C4","C5","C6"] # create a notebook tabControl = ttk.Notebook(out_root) # Create Tab Control tabControl.pack() for i in range(7): # loop to fill notebook pages. tabs = Frame(tabControl) # put frame in notebook tabs.pack() tabControl.add(tabs, text="{}".format(tab[i])) # Add the tab C[i] = Canvas(tabs) # put canvas inside notebook frame S = Scrollbar(tabs, command=C[i].yview) # define and bind the scrollbar with the canvas C[i].config(yscrollcommand=S.set, scrollregion=(0, 0, 10000, 10000)) # bind the canvas with the scrollbar # Enable mousewheel option 1 C[i].bind_all('&lt;MouseWheel&gt;', lambda event: C[i].yview_scroll(int(-1 * (event.delta / 120)), "units")) # Enable mousewheel option 2 # if i==0: C[0].bind_all('&lt;MouseWheel&gt;', lambda event: C[0].yview_scroll(int(-1 * (event.delta / 120)), "units")) # if i==1: C[1].bind_all('&lt;MouseWheel&gt;', lambda event: C[1].yview_scroll(int(-1 * (event.delta / 120)), "units")) # if i==2: C[2].bind_all('&lt;MouseWheel&g…

http://stackoverflow.com/q/51085199
has comment: http://stackoverflow.com/comment/89166414
answer count: 0
type: Question
tagged with: python-itertools
has body: Hi I'm totally out of ideas. I have the following list of substrings. I need to build permutations of these substrings that create strings that match specific criteria. Each substring can be used any number of times (i.e. with replacement) and the order of the substrings is irrelevant. items = ["q", "q.", "qg", "q.g.", "q.g", "qgr", "q.g.r", "q.g.r.", "qghr", "q.g.h.r", "q.g.h.r.", "q.g.r.h", "q.g.r.h.", "qakky", "qakky.", "qak", "qak.", "qkgr", "q.k.g.r", "q.k.g.r.", "qkghr", "q.k.gh.r", "q.k.gh.r.", "qr", "q.r.", "q.r", "gokoaheo", "gokoaheo.", "goko", "goko.", "g", "g.", "r", "r.", "rhk.", "k.", "k", "rhk", "gho", "ghr", "gr", "kgr", ".", ".", "goh", "goho", "gho.", "goho.", "rohok", "rohok.", "roh", "roh.", "kat.", "q", "q.", "qgr", "qghr"] Each resultant permutation must be as follows: Start with a 'q' Cannot end with a '.' Must not have any of the following substrings: '..', 'ee', 'oo', 'll', 'gg', 'aa' Must have no more than 2 'q's 'r's and 'g's ; No more than 4 'h's, 'o's ; no more than 5 'k's or '.'s Cannot have more than 13 characters or less than 9. Hence I wrote the following function to sift each permutation: def badseq(item): patt=re.compile('\.$|^[^q]') lets = ['q','g','r','h','o','k','.','..','gg','oo','ll','aa','ee'] nums = [2,2,2,4,4,5,0,0,0,0,0,0] if len(item) &gt; 13 or len(item) &lt; 9: return True for i in range(len(lets)): l=lets[i] n=nums[i] if item.count(l) &gt; n : return True elif re.search(patt, item): return True return False Is there a better way to do this than calculate so many permutations and then filter them out one by one? completelist=[] for repetitions in range(8): perms=["".join(x) for x in itertools.permutations(items, repetitions) if not badseq("".join(x))] completelist.extend(perms) completelist=[x for x in set(completelist)] The problem is that because I don't mind how many repetitions there are and the substrings are all of different lengths, I don't know how many repetitions to use in the itertools argument. I have gone w…
has title: Filtering itertools permutations by the length of the resulting permutation python
has comment: http://stackoverflow.com/comment/89166308
score: 0
has comment: http://stackoverflow.com/comment/89158880
tagged with: processing-efficiency
has comment: http://stackoverflow.com/comment/89169349
tagged with: permutation
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51061907
has body: I have several txt files that are formatted in this way label1: value1 label2: string1 date: 2018-06-26 label3: value2 label4: string I would like to read those files and create a database where I have headers and then values/strings which then I write to file. any help? regards
has comment: http://stackoverflow.com/comment/89113506
tagged with: pandas
has answer: http://stackoverflow.com/a/51062646
linked to: http://stackoverflow.com/q/38366494
favorite count: 0
has comment: http://stackoverflow.com/comment/89113971
linked to: http://stackoverflow.com/q/10373247
linked to: http://stackoverflow.com/q/8331469
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51062641
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89113768
has comment: http://stackoverflow.com/comment/89114511
tagged with: file
type: Question
answer count: 2
downvote count: 0
tagged with: database
accepted answer: http://stackoverflow.com/a/51062646
has title: read file with pandas and create header
possible better answer: http://stackoverflow.com/a/51062641

http://stackoverflow.com/comment/89135826
score: 0
type: Comment
has text: Appreacite it alot @JayHello! Really helped me and you made a solution for it! Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/51072933

matplotlib-basemap
tags question: http://stackoverflow.com/q/51110638
tags question: http://stackoverflow.com/q/51089866
tag name: matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/51017519
tags question: http://stackoverflow.com/q/51032225
tags question: http://stackoverflow.com/q/51048648

bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/51035303
tag name: bayesian-networks

http://stackoverflow.com/q/51111868
answer count: 1
tagged with: ssh
has body: I need to execute multiple shell commands in a ssh session using the subprocess module. I am able to execute one command at a time with: subprocess.Popen(["ssh", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", "%s" % &lt;HOST&gt;, &lt;command&gt;]) But is there a way to execute multiple shell commands with subprocess in a ssh session? If possible, I don't want to use packages. Thank you very much!
favorite count: 0
tagged with: python-3.x
upvote count: 5
has title: Multiple commands with ssh using Python subprocess
tagged with: python
linked to: http://stackoverflow.com/q/19354870
type: AnsweredQuestion
tagged with: subprocess
downvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51111906
score: 5
has comment: http://stackoverflow.com/comment/89210826
has answer: http://stackoverflow.com/a/51111906
has comment: http://stackoverflow.com/comment/89210864

http://stackoverflow.com/comment/91250464
has text: The pull request was merged at Aug 2. You can now try installing directly from https://github.com/Sterncat/opticspy
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51125701

http://stackoverflow.com/q/51052422
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/89117494
score: 0
has body: I want to extract the text from HTML page with has node, but within this node, there is no standard format of nodes. I am able to extract the complete text within , however my output is not the same as it shows on the HTML page. For example, below is the HTML is want to extract- This is first Paragraph This is second Paragraph This is third paragraph &nbsp 3rd para continue This is what i have in my code. xxx = response.xpath("//article/div | //article/ul | //article/ol | //article/p") content = "" for eachLine in warningLetterlines: tmp = eachLine.xpath('.//text()').extract() content += "".join( i.replace(u'\xa0', u'') for i in tmp ) + "\n" This code outputs as - This is first paragraph This is second paragraphThis is third paragraph3rd para continue However, what i want is - This is first paragraph This is second paragraph This is third paragraph 3rd para continue I have tried to add some custom logic to join the list with either "\n" or "" based on the inner node, but as i mention my HTML page is not in a common format so my code is breaking whenever it sees something new. I also thought of getting a list of node name and join it based on the name of the node ( like add "\n" for / and "" for / etc), but the length of these 2 list are not same. Following are some of the pages i am trying to scrap - (Notice that all 3 has a different html layout with-in node. https://www.fda.gov/ICECI/EnforcementActions/WarningLetters/2017/ucm572086.htm https://www.fda.gov/ICECI/EnforcementActions/WarningLetters/2016/ucm503559.htm https://www.fda.gov/ICECI/EnforcementActions/WarningLetters/2013/ucm376390.htm I want to scrap these pages in the exact same text format how it is displaying on the page. I found a online html to text converter which gives me my desired output but i am not sure how to implement this by my own. Any approach / help please ? I am really stuck to this problem. This is the online converter if you want to look at- https://templates.mailchimp.com/resources/html-…
has comment: http://stackoverflow.com/comment/89098255
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/89096575
has title: Generic approach to extract text from any HTML format using scrapy xpath
tagged with: xpath
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: web-scraping

http://stackoverflow.com/comment/89363014
has text: In addition, the JVM will apply a Just-In-Time compilation of 'hot' methods (run often) to machine-specific (optimized) assembly on the fly at runtime.
comment on: http://stackoverflow.com/a/51141750
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89243164
score: 0
has text: @trust512 it might be a time consuming or worthless, but most of my work I did in MT5. It is not at all possible for me to shift to new platform and start it from ground zero. Kindly, let me know how I can make the above integration possible, please.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51061059

http://stackoverflow.com/a/51089842
has comment: http://stackoverflow.com/comment/89168152
answers question: http://stackoverflow.com/q/51089798
has body: Your function can take arbitrarly long to return. In particular, you will get into an infinite loop if no item is None. Instead, recover all indices which are None and use random.choices to randomly return k of them. import random def get_random_addr(input_arr, k=1, target=None): return random.choices([i for i, v in enumerate(input_arr) if v is target], k=k) Usage l = [0, None, 2, 3, None, None] for i in get_random_addr(l, k=2): l[i] = i print(l) # [0, None, 2, 3, 4, 5]
has comment: http://stackoverflow.com/comment/89167968
has comment: http://stackoverflow.com/comment/89168380
has comment: http://stackoverflow.com/comment/89168348
score: 0
has comment: http://stackoverflow.com/comment/89167974
has comment: http://stackoverflow.com/comment/89168221
has comment: http://stackoverflow.com/comment/89168048
has comment: http://stackoverflow.com/comment/89168321
type: Answer
has comment: http://stackoverflow.com/comment/89167985
has comment: http://stackoverflow.com/comment/89168532
has comment: http://stackoverflow.com/comment/89168207

heap-memory
tag name: heap-memory
tags question: http://stackoverflow.com/q/51028426
type: Tag

http://stackoverflow.com/q/51056437
upvote count: 1
has title: kfold cross validation wont terminate, stuck at cross_val_score
tagged with: tensorflow
type: Question
type: AnsweredQuestion
tagged with: cross-validation
linked to: http://stackoverflow.com/q/50993867
has answer: http://stackoverflow.com/a/51058744
accepted answer: http://stackoverflow.com/a/51058744
has body: I am trying to run kfold cross validation. but for some reason, it gets stuck here, it wont terminate from here accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1) i cant understand whats the problem. and how do i fix it. import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:,1:] # Splitting the dataset into the Training set and Test set 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, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) import keras from keras.models import Sequential #Required to initialize the ANN from keras.layers import Dense #Build layers of ANN from keras.layers import Dropout # Evaluating the ANN import keras from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from keras.models import Sequential #Required to initialize the ANN from keras.layers import Dense #Build layers of ANN def build_classifier(): # Builds the architecture, or the classifier classifier = Sequential() classifier.add(Dense(activation = 'relu', input_dim = 11, units = 6, kernel_initializer = 'uniform'))# add layers classifier.add(Dense(activation = 'relu', units = 6, kernel_initializer = 'uniform'))# add layers classifier.add(Dense(activation = 'sigmoid', units = 1, kernel_initializer = 'uni…
has comment: http://stackoverflow.com/comment/89106361
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89104307
tagged with: scikit-learn
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/89103939
tagged with: python
score: 1

http://stackoverflow.com/q/51159184
tagged with: node.js
has answer: http://stackoverflow.com/a/51159301
tagged with: django
has comment: http://stackoverflow.com/comment/89665049
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51353887
linked to: http://stackoverflow.com/q/55568872
upvote count: 5
has comment: http://stackoverflow.com/comment/89301749
has title: Do Django templates get cached in browser?
has body: Let's say we have a request made in Django which renders my_template.html and the context of {foo: bar} return render(request, "my_template.html", {foo: bar}) Now based on the user activity foo and bar change. Let's say if a user has made his first request. Django will return the template and the corresponding {foo: bar} based on user activity. Let's say if the user had made a second request with a different activity. Will Django send my_template.html from the server to the browser or will only the changed context be sent to the browser? Does the template get cached in the browser? Case 1: If the template gets cached in a browser if a code with some changes is deployed does it reflect in the client's browser? Does this work in the way where the md5 hash of both the templates is compared if they are not in sync then the template is downloaded from Django server? Case2 If the template is rendered every time for every request then does that mean the bandwidth usage is not optimistic? I read that in a node and angular the javascript bundles is cached in clients browser and only data(context {foo: bar}) calls are made to a server so the bandwidth usage is better and loading is faster is this true.
type: Question
answer count: 3
score: 5
accepted answer: http://stackoverflow.com/a/51159301
possible better answer: http://stackoverflow.com/a/51308776
has comment: http://stackoverflow.com/comment/89456433
downvote count: 0
has answer: http://stackoverflow.com/a/51308776
favorite count: 0
tagged with: angular
has comment: http://stackoverflow.com/comment/89496786
tagged with: python

http://stackoverflow.com/comment/89291475
comment on: http://stackoverflow.com/q/51154031
has text: Indeed basic but I couldn't figure it out from the Pandas documentation. I just want to automatically check every single records from row a for a certain value. I can't find the answer in "Select rows from a DataFrame based on values in a column in pandas".
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89096584
comment on: http://stackoverflow.com/q/51052740
type: QuestionComment
type: Comment
has text: use >= 95 istead of <= 5?
score: 1

http://stackoverflow.com/comment/89133018
type: Comment
type: QuestionComment
has text: conn.commit is at the end of the code
score: 0
comment on: http://stackoverflow.com/q/51070954

http://stackoverflow.com/comment/89207997
has text: @mypetlion my bad. meant to say pandas
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51110378

http://stackoverflow.com/comment/89295984
type: QuestionComment
comment on: http://stackoverflow.com/q/51154825
score: 0
has text: I suspect is is a Conda issue. Conda: 4.4.11, Python 3.6.2 :: Anaconda custom (64-bit), gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609, read_eagle has no version numbers I am aware of.
type: Comment

http://stackoverflow.com/a/51106578
type: Answer
downvote count: 0
has body: You can use enumerate and itertools.chain within a dictionary comprehension. set ensures mappings are unique. Data from @Abhishek. from itertools import chain res = {v: k for k, v in enumerate(set(chain.from_iterable(df['ingredients'])))} print(res) {'aap': 15, 'app': 3, 'bootstrapping': 1, ... 'ponda': 0, 'secure': 17, 'upi': 5}
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51106292

http://stackoverflow.com/comment/89193714
type: QuestionComment
comment on: http://stackoverflow.com/q/51103050
has text: Possible duplicate of [What are the potential results for platform.system()](https://stackoverflow.com/questions/31107019/what-are-the-potential-results-for-platform-system)
score: 0
type: Comment

http://stackoverflow.com/comment/108382353
has text: This is actually not directly answering the question but instead circumventing it by a `virtualenv` approach.
type: Comment
comment on: http://stackoverflow.com/a/60189988
type: AnswerComment
score: 0

http://stackoverflow.com/q/51079753
has answer: http://stackoverflow.com/a/51079907
has body: list_of_elements = [1255, 1256, 1257, 1258, 1259] print(components[1255],components[1256],components[1257],components[1258],components[1259]) Output of the print is: [481, 498, 5142, 5157] [481, 497, 5192, 5199] [481, 498, 5219, 5238] [481, 484, 5239, 5242] [481, 487, 5269, 5271)] What I want to do is to take the smallest number of the first index(0), the biggest of the second, smallest of the third and biggest of the fourth so i'll end up with in this case: [481,498,5142,5271] So, again, basically I'll be given a list of elements (in this case it's list_of_elements, might have 0 values up to unknown), then I have to input the elements of that list as keys in a dictionary components and do the steps explained above.
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/51080919
score: 2
type: AnsweredQuestion
tagged with: list
downvote count: 0
has title: Calculating minimum or maximum by index in list of lists
type: Question
accepted answer: http://stackoverflow.com/a/51079907
has answer: http://stackoverflow.com/a/51080919
upvote count: 2
answer count: 2

http://stackoverflow.com/q/51160830
type: AnsweredQuestion
has body: I have two custom-written C routines that I would like to use as a part of a large Python application. I would prefer not to rewrite the C code in pure Python (or Cython, etc.), especially to maintain speed. What is the cleanest, easiest way that I can use my C code from my Python code? Or, what is the cleanest, easiest way for me to wrap my C code for use in my Python source? I know "cleanest" and "easiest" will attract opinions, but I really just need some good options for using custom pre-written code, versus many of the other answers/tutorials which describe how to use full-on C libraries as CPython extensions. EDIT: Cython and ctypes have both been suggested. Which is a better choice in my case? Each of the two routines I mentioned originally are very computationally intensive. They are used for image calculations and reconstructions, so my plan is to build a Python application around their use (with other functionality in mind that I already have in Python) with the C code run as needed for processing.
tagged with: http://stackoverflow.com/tag/c
possible better answer: http://stackoverflow.com/a/51161001
type: Question
score: 0
answer count: 2
tagged with: python-3.5
has title: Calling custom C subroutines in a Python application
has answer: http://stackoverflow.com/a/51161001
tagged with: python
tagged with: python-c-api
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89305387
has answer: http://stackoverflow.com/a/51160991
accepted answer: http://stackoverflow.com/a/51160991

css-selectors
tags question: http://stackoverflow.com/q/51052735
tags question: http://stackoverflow.com/q/51164890
tags question: http://stackoverflow.com/q/51144220
tags question: http://stackoverflow.com/q/51160246
tags question: http://stackoverflow.com/q/51149507
tags question: http://stackoverflow.com/q/51035611
tags question: http://stackoverflow.com/q/51159965
tag name: css-selectors
type: Tag
tags question: http://stackoverflow.com/q/51076418

http://stackoverflow.com/a/51019207
downvote count: 0
has body: There are hopeful google search results for this problem found by 'jupyter notebook rest api', e.g. https://blog.ouseful.info/2017/09/06/building-a-json-api-using-jupyer-notebooks-in-under-5-minutes/ Have you tried using kernelgateway?
answers question: http://stackoverflow.com/q/51018536
score: 4
has comment: http://stackoverflow.com/comment/89036614
type: Answer
has comment: http://stackoverflow.com/comment/89031665
upvote count: 4

http://stackoverflow.com/comment/89125472
comment on: http://stackoverflow.com/q/51067664
type: Comment
type: QuestionComment
has text: `myfiles = [item for item in myfiles if item[-6:] == '2m.csv']` is what you need.
score: 0

http://stackoverflow.com/comment/89065433
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51036588
has text: error " dispatch() got an unexpected keyword argument 'string' "
type: Comment

http://stackoverflow.com/a/51037070
upvote count: 1
score: 1
downvote count: 0
has body: I had an an similar error some years ago on a Windowsmachine. I think the Problem is that you path contains an special character (&amp;)... Just change the name of the folder or escape it with backspace
answers question: http://stackoverflow.com/q/51037001
type: Answer

http://stackoverflow.com/a/51163553
accepted answer of: http://stackoverflow.com/q/51163528
answers question: http://stackoverflow.com/q/51163528
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The constructor method (like other Python magic methods) is called __init__ (two underscores on each side).

http://stackoverflow.com/comment/89123927
has text: Check whether `len(driver.find_elements_by_name('phone'))` returns `1` or more. If more- try different locator
score: 0
comment on: http://stackoverflow.com/q/51066880
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51102220
tagged with: pytorch
has answer: http://stackoverflow.com/a/52836866
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89351994
has comment: http://stackoverflow.com/comment/89426751
has body: I'm implementing DDPG and got stuck training my two nets. All in all I've got 4 nets called: actor, actor_target, critic and critic_target. I'm training the actor and critic in the training loop and do soft updates for the other two nets with: def update_weights(self, source, tau): for target, source in zip(self.parameters(), source.parameters()): target.data.copy_(tau * source.data + (1 - tau) * target.data) My training loop looks like: tensor_next_states = torch.tensor(next_states).view(-1, 1) prediction_target = self.actor_target(tensor_next_states).data.numpy() target_critic_output = self.critic_target( construct_tensor(next_states, prediction_target)) y = torch.tensor(rewards).view(-1,1) + \ self.gamma * target_critic_output output_critic = self.critic( torch.tensor(construct_tensor(states, actions), dtype=torch.float)) # compute loss and update critic self.critic.zero_grad() loss_critic = self.criterion_critic(y, output_critic) loss_critic.backward() self.critic_optim.step() # compute loss and update actor tensor_states = torch.tensor(states).view(-1, 1) ouput_actor = self.actor(tensor_states).data.numpy() self.actor.zero_grad() loss_actor = (-1.) * \ self.critic(construct_tensor(states, ouput_actor)).mean() loss_actor.backward() self.actor_optim.step() # update target self.actor_target.update_weights(self.actor, self.tau) self.critic_target.update_weights(self.critic, self.tau) using SGD as optimizer and self.criterion_critic = F.mse_loss. construct_tensor(a,b) constructs a tensor like [a[0], b[0], a[1], b[1], ...]. I've noticed, that the RMSE on the test set before and after training is the same. So I debugged a lot and noticed in update_weights that the weights of the trained net and the target net are the same - so I concluded, that the training does not have any affect on the weights of the trained net. I already checked that the computed losses are not zero but still a float, checked replacing the zero_grad() calls and moving the computed losses to self,…
upvote count: 4
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/89370752
answer count: 1
favorite count: 0
tagged with: reinforcement-learning
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89252484
tagged with: python
has title: Net does not change weights during training, pytorch
has comment: http://stackoverflow.com/comment/89400208
score: 3

http://stackoverflow.com/a/51094069
downvote count: 0
type: Answer
upvote count: 2
has body: You can strip an extension using basename &lt;file&gt; &lt;extension&gt;. There are a variety of ways you could arrange to do that. Using a loop in bash For example, loop through the results from find and then zip the file: for f in $(find . -name '*.py') do zip "$(basename "$f" .py).zip" "$f" done Using a subshell in find Unfortunately we can't use $(...) in find ... -exec directly. However we can always invoke a shell and do it there: find . -name '*.py' -exec sh -c 'zip "$(basename "$0" .py)".zip "$0"' '{}' \;
score: 2
answers question: http://stackoverflow.com/q/51093899

lxml
tags question: http://stackoverflow.com/q/51042841
tags question: http://stackoverflow.com/q/51108651
tags question: http://stackoverflow.com/q/51158136
type: Tag
tags question: http://stackoverflow.com/q/51034706
tags question: http://stackoverflow.com/q/51051610
tags question: http://stackoverflow.com/q/51094378
tags question: http://stackoverflow.com/q/51052345
tags question: http://stackoverflow.com/q/51013526
tags question: http://stackoverflow.com/q/51080936
tags question: http://stackoverflow.com/q/51118394
tag name: lxml

http://stackoverflow.com/a/51073489
has comment: http://stackoverflow.com/comment/89167231
type: Answer
answers question: http://stackoverflow.com/q/51030872
has comment: http://stackoverflow.com/comment/89175689
score: 1
upvote count: 1
has body: From what I can tell, the difficulty is that you are trying to make an indicator column from an array of arrays. I collapsed your indicator array to "indicator": np.array([ "A", "B", "C", "AA", "ABC", ]) ... and the thing ran. More, I can't find any example where the vocabulary array is anything but a flat array of strings.
downvote count: 0
has comment: http://stackoverflow.com/comment/89167283
has comment: http://stackoverflow.com/comment/89175679

jenkins
tags question: http://stackoverflow.com/q/51124878
tag name: jenkins
tags question: http://stackoverflow.com/q/51149409
tags question: http://stackoverflow.com/q/51143881
tags question: http://stackoverflow.com/q/51101594
type: Tag

http://stackoverflow.com/q/51135148
answer count: 2
accepted answer: http://stackoverflow.com/a/51135462
has answer: http://stackoverflow.com/a/79044432
tagged with: discord
favorite count: 0
has answer: http://stackoverflow.com/a/51135462
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I'd like to use my bot not as a daemon that runs forever, but as a kind of "shell script". So it should automatically quit after it has done its work. My approach so far in Python 3.5 / Python 3.6: import discord TOKEN = '&lt;redacted&gt;' client = discord.Client() @client.event async def on_ready(): for member in client.get_all_members(): print(member.display_name) # please, please quit now! client.run(TOKEN) What I want here is, that the script should just quit after printing all the members' display_names, so I can further process them elsewhere. At the moment it DOES print the desired information, but continues to run forever.
has title: Make bot automatically quit after it has done its work
type: Question
tagged with: discord.py
possible better answer: http://stackoverflow.com/a/79044432
upvote count: 2

http://stackoverflow.com/a/51147830
has body: Input: A B C 0 1\n2\n3 2\n5 A Code: import pandas as pd cols = df.columns.tolist() # create list in each cell by detecting '\n' for col in cols: df[col] = df[col].apply(lambda x: str(x).split("\n")) # empty dataframe to store result dfs = pd.DataFrame() # loop over rows to construct small dataframes # and then accumulate each to the resulting dataframe for ind, row in df.iterrows(): a_vals = row['A'] b_vals = row['B'] + ["n/a"] * (len(a_vals) - len(row['B'])) c_vals = row['C'] + [row['C'][0]] * (len(a_vals) - len(row['C'])) temp = pd.DataFrame({'A': a_vals, 'B': b_vals, 'C': c_vals}) dfs = pd.concat([dfs, temp], axis=0, ignore_index=True) Output: A B C 0 1 2 A 1 2 5 A 2 3 n/a A
has comment: http://stackoverflow.com/comment/89285180
has comment: http://stackoverflow.com/comment/89281054
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89280120
answers question: http://stackoverflow.com/q/51146214
downvote count: 0
score: 1

http://stackoverflow.com/a/51043021
has body: I am not sure if this is the correct approach..but if it helps. import re from dateutil.parser import parse s = '2018-06-18 15:03:55 Etc/GMT' print( parse(re.sub("(?&lt;=:\d{2}\s).*\/", r"", s)) ) Output: 2018-06-18 15:03:55+00:00 I am using regex to remove Etc/ from the src datetime Using dateutil to convert to datetime object.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51042795
downvote count: 0
has comment: http://stackoverflow.com/comment/89077053
type: Answer

http://stackoverflow.com/comment/89124655
comment on: http://stackoverflow.com/a/51067184
has text: No, I am trying to assign the value of one of three date columns to a new, fourth date column based on the categorical value in a string column.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51120831
has body: I want to do foreground segmentation using opencv. I have written code that has trackbars so that I can find optimal parameters for the segmentation. When the code is executed it works, the images are shown with contours marked and etc. But when I try to move bars on the track bar. I'm getting the following error. OpenCV(3.4.1) Error: Assertion failed (size.width&gt;0 &amp;&amp; size.height&gt;0) in imshow, file /feedstock_root/build_artefacts/opencv_1523502125490/work/opencv-3.4.1/modules/highgui/src/window.cpp, line 356 Traceback (most recent call last): File "forgroundsegmentation.py", line 17, in foreground_segment cv2.imshow('brightness preprocess', tmp) This is my code. import cv2 import numpy as np winName = "ForeGround Segment" def foreground_segment(src, a=None,b=None, useEqualize=1, blurSize=21, th1=None, brightness=None): winName = "ForeGround Segment" tmp = brightness if (blurSize &gt;= 3): blurSize += (1 - blurSize % 2) tmp = cv2.GaussianBlur(tmp, (blurSize, blurSize), 0) if (useEqualize): tmp = cv2.equalizeHist(tmp) cv2.imshow('brightness preprocess', tmp) #cv2.imwrite('../BrightnessPreprocess.png', tmp) ret, tmp = cv2.threshold(tmp, th1, 255, cv2.THRESH_BINARY_INV) cv2.imshow(winName, tmp) im2, contours, hierarchy = cv2.findContours(tmp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) dst = src #print(contours) maxDim = 0 largest = -1 for i in range(len(contours)): cv2.drawContours(dst, contours, largest, (0, 0, 255), 1) dim = len(contours[i]) if (dim &gt; maxDim): maxDim = dim largest = i img_mask = np.zeros(src.shape, np.uint8) if (largest &gt;= 0): theImg = contours[largest] cv2.polylines(dst, theImg, True, (0, 255,0), 2) cv2.drawContours(img_mask, contours, largest, 255, -1) cv2.imshow("Result Mask", img_mask) cv2.imshow("Result Contour", dst) #cv2.imwrite("../img_mask.png", img_mask) #cv2.imwrite("../result.png", dst) if __name__ == '__main__': src = cv2.imread('frontal.png') print(src.shape) src = cv2.resize(src, (int(src.shape[0]/3), int(src.shape[…
has title: OpenCV trackbar assertion failed error
accepted answer: http://stackoverflow.com/a/51121252
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89227813
tagged with: opencv
type: AnsweredQuestion
score: 1
type: Question
tagged with: trackbar
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51121252
favorite count: 0

http://stackoverflow.com/comment/89224137
has text: @Vishal If the dtypes of `df1` and `df2` are different. Otherwise I think this is pretty solid. If this is going into production code, make sure you write a few test cases for it.
type: Comment
comment on: http://stackoverflow.com/a/51119107
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89292391
score: 0
type: QuestionComment
type: Comment
has text: `return (Y//r)%self.n` -- no, that's not the way you do it. Instead of integer division you must perform division in the ring of integers mod n, also more commonly known as a [*modular inverse*](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse).
comment on: http://stackoverflow.com/q/51151220

http://stackoverflow.com/comment/89247263
type: Comment
comment on: http://stackoverflow.com/a/51131244
type: AnswerComment
score: 0
has text: @MarkSetchell no but you're right I should remove some of the old records which aren't used anymore. I'll edit

http://stackoverflow.com/comment/109006502
has text: Same here. Just resubmitting my C++ solution w/o any changes produced different runtime results: from 4ms (99.89%) to 16ms (54.73%). They probably should prepare test data more carefully to avoid such fast run times and hence such wide scatter.
score: 1
comment on: http://stackoverflow.com/a/54522588
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51144354
tagged with: optimization
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51144397
has answer: http://stackoverflow.com/a/51144397
tagged with: websocket
tagged with: python
tagged with: dictionary
has body: The best way I can think to explain my question is with the following example. Note that "a conditional returning True" is actually a response from an asynchronous websocket. Say, as a while True loop is running, there is a variable x assigned to a list of 15 dicts, each dict having 5 key/value pairs, with each pair having been chosen randomly from a dict y of 26 key/value pairs, where each key is a letter of the alphabet. It is known that none of the values of the dicts in x sum to > 50. Say some some conditional in the while True loop turns true, and the value for key a in y is now 30. Besides brute forcing, is there any faster way to check if the values of any dict in x now sum to > 50, accounting for the change to a? Note: I am looking for a solution that applies to all keys in y, not just a.
has title: Fastest way to run an algorithm on several arguments, having run it in the past, after a change to one variable
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51144538
type: Question
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/51144538

http://stackoverflow.com/q/51116200
type: Question
has title: How to stop the mainWindow while opened a new Window and get my Value
has comment: http://stackoverflow.com/comment/89229790
tagged with: window
has comment: http://stackoverflow.com/comment/89219551
score: 0
has comment: http://stackoverflow.com/comment/89222702
tagged with: multi-window
tagged with: python
has body: My problem is that i have an Main-Class with an button-click function, where if i click the button, the EntryBox will be opened and in the button-click function i want to create the folder too, but i dont know how to "stop" the mainWindow while the EntryBox-Window is open to get the value(Folder name). @BryanOakley Minimal, Complete, and Verifiable example: That's my msBox.py import tkinter as tk FolderName = "" class EntryBox: def __init__(self, Text): self.root = tk.Tk() self.textBox = tk.Entry(self.root) self.EBOKAY = tk.Button(self.root, text="Okay") self.EBOKAY.bind("&lt;Button-1&gt;", self.EBOKAY_click) self.EBLabel = tk.Label(self.root, text=Text) self.EBLabel.pack() self.textBox.pack() self.EBOKAY.pack() self.root.mainloop() def EBOKAY_click(self, event): global FolderName FolderName = self.textBox.get() self.root.destroy() Here is my next file gui.py: import tkinter as tk import os import msBox # variables path = "/" class GUI: def __init__(self, master): self.button1 = tk.Button(master, text="Set") self.button1.bind('&lt;Button-1&gt;', self.button1_click) self.button1.pack() def button1_click(self, event): test = msBox.EntryBox("New folder name:") # Here is need a wait-Statement or anything else os.mkdir(path + msBox.FolderName) Here is my main.py: import tkinter as tk import gui def main(): root = tk.Tk() design = gui.GUI(root) root.mainloop() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/89238937
tagged with: tkinter
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51087391
answer count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89176154
has answer: http://stackoverflow.com/a/51088129
has comment: http://stackoverflow.com/comment/89163267
has body: I have a code which was working great on python 2.7 but then I migrated to python 3.5 and it's not working anymore, I'm getting an error. Here is the code: def gen_cert(keyname, certname, password, username): cmd = [ 'openssl', 'pkcs12', '-name', username, '-inkey', tempdirname + keyname, '-in', tempdirname + certname, '-export', '-out', dirname + username + '.p12', '-password', 'pass:' + password ] s = subprocess.Popen(cmd, shell=False) out, err = s.communicate('\n'.encode()) The error is - Can't convert 'User' object to str implicitly The error is coming due to this dirname + username + '.p12' Here are the local variables: | Variable | Value | ______________________________ | certname |'w0ui8t9mkg.pem' | | keyname |'7g89utc1it.pem' | | password |'bo02qm99ui' | | username |&lt;User: abcuser&gt;| Here is the function which is calling the above function: def generate_user_certificate(self, request, queryset): check_folders(request) UsersList = [] for qs in queryset: username = qs.username keyname = random_name('.pem') certname = random_name('.pem') password = random_name('') gen_cert(keyname, certname, password, username) UsersList.append(username) # Displaying success message for certificate generation allusers = ', '.join(UsersList) messages.success( request, "Certificates for users: " + allusers + " generated successfully.") Also I'm getting an error in allusers = ', '.join(UsersList) which says sequence item 0: expected str instance, User found How to resolve it? I'm using django 2.0
tagged with: typeerror
has answer: http://stackoverflow.com/a/51094120
has comment: http://stackoverflow.com/comment/89164083
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51088295
favorite count: 0
linked to: http://stackoverflow.com/q/16699362
tagged with: python-3.x
type: Question
upvote count: 2
tagged with: python
has title: TypeError - Can't convert 'User' object to str implicitly
has comment: http://stackoverflow.com/comment/89165265
accepted answer: http://stackoverflow.com/a/51094120
has comment: http://stackoverflow.com/comment/89163294
has comment: http://stackoverflow.com/comment/89283428
has comment: http://stackoverflow.com/comment/89204210
possible better answer: http://stackoverflow.com/a/51087761
has answer: http://stackoverflow.com/a/51087761
has comment: http://stackoverflow.com/comment/89163293

http://stackoverflow.com/a/51020255
has comment: http://stackoverflow.com/comment/89037390
has comment: http://stackoverflow.com/comment/89037239
has comment: http://stackoverflow.com/comment/89035615
type: AcceptedAnswer
downvote count: 0
has body: Yes you can use if instead of elif in this case, since they are mutually exclusive. Either the event is this or that, but elif is probably used to avoid checking both if conditions every time. In C++ you could use switch, but as far as I know there is no switch in python. Mode seems to change from rectangle shape to circle shape in your selection. You may use m to change from one mode to the other one.
answers question: http://stackoverflow.com/q/51020105
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89033400
accepted answer of: http://stackoverflow.com/q/51020105
has comment: http://stackoverflow.com/comment/89037711
has comment: http://stackoverflow.com/comment/89036651
score: 1
has comment: http://stackoverflow.com/comment/89037024

http://stackoverflow.com/q/51147178
has comment: http://stackoverflow.com/comment/89278567
has answer: http://stackoverflow.com/a/51147329
tagged with: gevent
downvote count: 1
has comment: http://stackoverflow.com/comment/89278523
type: Question
has comment: http://stackoverflow.com/comment/89278520
has comment: http://stackoverflow.com/comment/89278370
score: -1
has body: I am trying to install gevent with pip but failed to install it. Requirement already satisfied: gevent in c:\program files (x86)\python36-32\lib\site-packages (1.3.4) Requirement already satisfied: cffi&gt;=1.11.5; sys_platform == "win32" and platform_python_implementation == "CPython" in c:\program files (x86)\python36-32\lib\site-packages (from gevent) (1.11.5) Requirement already satisfied: greenlet&gt;=0.4.13; platform_python_implementation == "CPython" in c:\program files (x86)\python36-32\lib\site-packages (from gevent) (0.4.13) Requirement already satisfied: pycparser in c:\program files (x86)\python36-32\lib\site-packages (from cffi&gt;=1.11.5; sys_platform == "win32" and platform_python_implementation == "CPython"-&gt;gevent) (2.18) tweepy 3.6.0 has requirement requests&gt;=2.11.1, but you'll have requests 2.10.0 which is incompatible. Please help me out with this error.
has comment: http://stackoverflow.com/comment/89278715
has comment: http://stackoverflow.com/comment/89278633
has comment: http://stackoverflow.com/comment/89278618
answer count: 2
has answer: http://stackoverflow.com/a/51147471
upvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python-wheel
has title: unable to install specific libraries in Python
tagged with: pip
tagged with: python

http://stackoverflow.com/comment/89138473
type: AnswerComment
type: Comment
has text: it also modifies the calling convention and "C" doesn't have a calling convention for the parameter std::vector<>&. You couldn't expose the same function to a C compiler.
comment on: http://stackoverflow.com/a/51071298
score: 1

http://stackoverflow.com/comment/89237064
type: Comment
type: QuestionComment
has text: I noticed after performing adaptive threshold. See the answer below if it helps.
score: 0
comment on: http://stackoverflow.com/q/51124738

http://stackoverflow.com/a/51161260
type: Answer
has comment: http://stackoverflow.com/comment/89307226
has comment: http://stackoverflow.com/comment/89306945
has comment: http://stackoverflow.com/comment/89307314
has comment: http://stackoverflow.com/comment/89307716
upvote count: 3
has comment: http://stackoverflow.com/comment/89306875
has comment: http://stackoverflow.com/comment/89307663
score: 3
has comment: http://stackoverflow.com/comment/89308186
has comment: http://stackoverflow.com/comment/89307045
has comment: http://stackoverflow.com/comment/89305993
has comment: http://stackoverflow.com/comment/89306013
accepted answer of: http://stackoverflow.com/q/51161137
has comment: http://stackoverflow.com/comment/89306892
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51161137
has comment: http://stackoverflow.com/comment/89306700
has comment: http://stackoverflow.com/comment/89306823
has comment: http://stackoverflow.com/comment/89307335
has body: You can write a commands.check to use Server.get_member to try to find the member in the given server. Something like class NonMember(commands.CommandError): def __init__(self, server_id, *args, **kwargs): self.server_id = server_id super().__init__(*args, **kwargs) @bot.event async def on_command_error(error, ctx): if isinstance(error, NonMember): await bot.send_message(ctx.message.channel, "{} Not an member. ".format(error.user.mention)) def is_member_of(server_id): def predicate(ctx): server = bot.get_server(server_id) if not server: raise commands.CommandError("Cannot poll members of server with id {}".format(server_id)) if bool(server.get_member(ctx.message.author.id)): return True else: raise NonMember(server_id) return commands.check(predicate) @bot.command(pass_context=True) @is_member_of("1234") async def ping(ctx): msg = "Pong {0.author.mention}".format(ctx.message) await bot.say(msg)

http://stackoverflow.com/a/51038752
has body: You can use csv.reader and a dictionary comprehension to construct a mapping between flower name and price: from io import StringIO import csv mystr = StringIO("""petunia,5.95 alyssum,3.95 begonia,5.95 sunflower,5.95 coelius,4.95""") # replace mystr with open(csv_pricefile) with mystr as fin: reader = csv.reader(fin) flower_prices = {name: float(price) for name, price in reader} print(flower_prices) {'alyssum': 3.95, 'begonia': 5.95, 'coelius': 4.95, 'petunia': 5.95, 'sunflower': 5.95} Then extract the price of a specific flower via the dictionary, e.g. for petunia use flower_prices['petunia'].
has comment: http://stackoverflow.com/comment/89088108
answers question: http://stackoverflow.com/q/51038626
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89087714
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89087746
has comment: http://stackoverflow.com/comment/89088170

http://stackoverflow.com/comment/89137265
has text: already implemented and want to communicate between them, I said to believe that Celery would be the best approach but want to use flask + uWSGI + python daemon proces/service to run native multiprocessing module.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51072660

http://stackoverflow.com/q/51159849
linked to: http://stackoverflow.com/q/4376397
has comment: http://stackoverflow.com/comment/89303036
tagged with: http://stackoverflow.com/tag/c
has body: I have an old c and fortran application i need to convert to a python library that we could use on windows. i could use gcc and gfortran to compile the .c and .f files to .o files and then compile all of them to a .so file which works as a charm. gcc -c -fPIC 1.c $PYTHON_INCLUDE gfortran -Wall -Wsurprising -W -c -fPIC 2.f 3.f 4.f gfortran -shared 1.o 2.o 3.o 4.o -lc -o mylib But i now to need to convert them to a .pyd file. I tried to use the f2py from numpy. But f2py -c 1.c 2.f 3.f 4.f -m mylib could not compile them correctly. There are a lot of "undeclared" errors. Any recommends?
has title: How to compile .c file and .f (fortran) file into .pyd
type: Question
tagged with: f2py
score: 0
has comment: http://stackoverflow.com/comment/89304260
has comment: http://stackoverflow.com/comment/89303035
tagged with: gfortran
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: fortran

http://stackoverflow.com/a/51138001
has comment: http://stackoverflow.com/comment/89260504
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89260640
answers question: http://stackoverflow.com/q/51137773
has comment: http://stackoverflow.com/comment/89262688
has body: This is a regression problem not a classification problem. What the model is trying to do is - fit X into classes defined by Y (which are continuous). This is unknown to SVC classifier. Update your code with SVR from sklearn.svm import SVR from sklearn.grid_search import GridSearchCV X_train = [[3.30049159], [2.25226244], [1.44078451]] #1. Y should be 1d array of dimensions (n_samples,) y_train = [0.2681013, 0.03454225, 0.02062136] #Grid Search parameters = [{'kernel': ['rbf'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5], 'C': [1, 10, 100, 1000]}, {'kernel': ['poly'], 'C': [1, 10, 100, 1000], 'degree': [1, 2, 3, 4]}] #2. Type of regressor reg = SVR(C=1) #3. Regression evaluation cannot be done using f1_macro, so updated NMSE clf = GridSearchCV(reg, parameters, cv=5, scoring='neg_mean_squared_error') clf.fit(X_train, y_train)
downvote count: 0
has comment: http://stackoverflow.com/comment/89279465
has comment: http://stackoverflow.com/comment/89260886
has comment: http://stackoverflow.com/comment/89260594
type: Answer

http://stackoverflow.com/comment/109288051
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55202492
type: Comment
has text: Hello, I find following confusing: According to the PyTorch documentation: torch.rand returns a tensor filled with random numbers from a uniform distribution on the interval [0,1) https://pytorch.org/docs/stable/torch.html#torch.rand. I saw some developers use the same code as you to create Gaussian distribution. I would appreciate if you can please elaborate further on this? Thank you

http://stackoverflow.com/q/51032853
duplicate of: http://stackoverflow.com/q/40248075
favorite count: 0
has title: Mocking a function that modifies an input argument in python
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: unit-testing
linked to: http://stackoverflow.com/q/40248075
score: 3
upvote count: 3
tagged with: python-unittest
type: Question
has comment: http://stackoverflow.com/comment/89122894
tagged with: python-mock
tagged with: mocking
downvote count: 0
has body: I have the following file, main.py: def modify_in_place(obj): obj['foo'] = 'bar' def foo(obj): modify_in_place(obj) I also have a test for this: import main import unittest from mock import patch def side_effect(s): s.update(foo='bar') class MainTest(unittest.TestCase): @patch('main.modify_in_place', side_effect=side_effect): def test_foo(self): state = {} main.modify_in_place(state) m_fn.assert_called_once_with({}) self.assertEqual(state, {'foo': 'bar'}) This, however, returns the following error: AssertionError: Expected call: fn({}) Actual call: fn({'foo': 'bar'}) The argument state is being modified in-place by modify_in_place, and the side effect in the mock does the same thing. When it's originally added to the call stack, the state variable is empty. When it's modified by the side effect, though, it has the (unintentional) side effect of modifying the object on the call stack. As a result, the assertion fails. I locally modified this line to be import copy _call = _Call(copy.deepcopy((args, kwargs)), two=True) When I did, the test passed. Any ideas on how I can solve this without modifying the mock library?

http://stackoverflow.com/q/51061948
tagged with: path
tagged with: janusgraph
tagged with: python
has title: Search path in gremlin upto a given distance
type: AnsweredQuestion
has body: I want to find path(s) between 2 vertices until either I find the path or the distance exceeds a given value (say 10). For an example, say a graph (A)-&gt;(B)&lt;-(C)&lt;-(D)&lt;-(E)-&gt;(F)&lt;-(G)&lt;-(H)-&gt;(I). And maximum distance is 4. So if I search for a path (A-E), I get ABCDE, but if I search (B-G), I would get "too far away". I currently use this for finding path(s) between 2 vertices : g.V(nodeID1).repeat(__.both().simplePath()).until(__.hasId(nodeID2)).path().limit(limit).toList() By the way, I'm doing this using gremlin_python I found this question (Limiting depth of shortest path query using Gremlin on JanusGraph), that would have helped me. But it isn't answered yet.
score: 1
has answer: http://stackoverflow.com/a/51067708
upvote count: 1
tagged with: gremlin
type: Question
accepted answer: http://stackoverflow.com/a/51067708
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/50528738
favorite count: 0

http://stackoverflow.com/comment/89045215
has text: thanks for your quick response. But your solution cannot be used when there are many variables that depend on each other. like var2 = var1 +1, there can be many other variables that use var1, say var3 = var2 +1, var4 = var2 + var2 etc... Also the getter or update function just return some values but not update the module variables.
comment on: http://stackoverflow.com/a/51026024
score: 0
type: AnswerComment
type: Comment

odoo
tags question: http://stackoverflow.com/q/51039970
tags question: http://stackoverflow.com/q/51123587
tags question: http://stackoverflow.com/q/51145928
tags question: http://stackoverflow.com/q/51041425
tags question: http://stackoverflow.com/q/51100276
tags question: http://stackoverflow.com/q/51020408
type: Tag
tags question: http://stackoverflow.com/q/51131325
tags question: http://stackoverflow.com/q/51040357
tags question: http://stackoverflow.com/q/51025073
tags question: http://stackoverflow.com/q/51050329
tag name: odoo

http://stackoverflow.com/q/51122294
type: Question
has title: converting URI to URL using python
tagged with: uri
has comment: http://stackoverflow.com/comment/89229755
tagged with: url
downvote count: 0
tagged with: printers
has comment: http://stackoverflow.com/comment/89229999
favorite count: 0
has comment: http://stackoverflow.com/comment/89231344
tagged with: python
tagged with: pycups
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I have a list of printers and I got their URI using pycups. now I need to know their IP addresses and to do that, I need to know their URL. How can I convert those URIs to URLs? for example, I have this URI: dnssd://HP%20LaserJet%20M402dn%20(0988D9)-0._ipp._tcp.local/ And I need to know the ip address of my printer. how can I do it? when I use socket.gethostbyaddr() to find it, I get an exception that name or service not known
score: 2

http://stackoverflow.com/comment/89150930
has text: I can't replicate on 0.19, I've posted an example. If you can run the script I've provided below on your setup and share the results, then this may help us pinpoint the issue. Also indicate your Pandas version.
comment on: http://stackoverflow.com/q/51080943
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51112420
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89216818
has body: Actually the dimention of my Numpy file id (350,1) and my network is of size (?,7) hpw can i change the shape of my numpy to feed into network?
score: -1
has answer: http://stackoverflow.com/a/51112570
has title: Cannot feed value of shape (350,) for Tensor 'TargetsData/Y:0', which has shape '(?, 7)'
tagged with: numpy
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51149221
tagged with: django
type: AnsweredQuestion
tagged with: django-models
has title: no such column: Schedule_footballscore.match_played
has answer: http://stackoverflow.com/a/51149317
type: Question
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51149317
has body: class FootballScore(models.Model): team = models.ForeignKey(Team, related_name='teams_football', on_delete=models.CASCADE) match_played = models.IntegerField(default='0') lose = models.IntegerField(default='0') win = models.IntegerField(default='0') Initially i have team and win field only, Now i am adding new fields match_played and lose . When i am doing python manage.py makemigrations , no change is displayed, i even tried python manage.py makemigrations (my_app_name) . i also tried all the previous answers of Stackoverflow related to this topic. migrations.CreateModel( name='FootballScore', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('match_played', models.IntegerField(default='0')), ('lose', models.IntegerField(default='0')), ('win', models.IntegerField(default='0')), ], ), I have seen this migration type of thing in one of the folder, is this the migrated list, because here all my fields are mentioned? Any help will be appreciated! Thanks.

http://stackoverflow.com/comment/89057339
comment on: http://stackoverflow.com/q/51031839
has text: Possible duplicate of [Is it possible to use Django with an Access database?](https://stackoverflow.com/questions/40476729/is-it-possible-to-use-django-with-an-access-database)
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89088634
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51047051
has text: Specific value of what? what are you currently getting? help understand your code..

http://stackoverflow.com/comment/89198786
type: QuestionComment
type: Comment
has text: @VPfB Seems viable for many usecases, but unlike ``object()`` or my simple ``Symbol`` implementation it won't work with dictionaries, as they compare by ``==`` semantics.
comment on: http://stackoverflow.com/q/51098714
score: 0

pyqt5
tags question: http://stackoverflow.com/q/51089331
tags question: http://stackoverflow.com/q/51144336
tags question: http://stackoverflow.com/q/51025716
type: Tag
tags question: http://stackoverflow.com/q/51108478
tags question: http://stackoverflow.com/q/51163854
tags question: http://stackoverflow.com/q/51090424
tags question: http://stackoverflow.com/q/51098103
tags question: http://stackoverflow.com/q/51032877
tags question: http://stackoverflow.com/q/51123581
tags question: http://stackoverflow.com/q/51135444
tags question: http://stackoverflow.com/q/51054054
tags question: http://stackoverflow.com/q/51112877
tags question: http://stackoverflow.com/q/51046153
tags question: http://stackoverflow.com/q/51040636
tags question: http://stackoverflow.com/q/51091969
tags question: http://stackoverflow.com/q/51133034
tags question: http://stackoverflow.com/q/51131805
tags question: http://stackoverflow.com/q/51149314
tags question: http://stackoverflow.com/q/51144540
tags question: http://stackoverflow.com/q/51076948
tags question: http://stackoverflow.com/q/51154871
tags question: http://stackoverflow.com/q/51070273
tags question: http://stackoverflow.com/q/51140483
tags question: http://stackoverflow.com/q/51092602
tags question: http://stackoverflow.com/q/51108974
tags question: http://stackoverflow.com/q/51114563
tags question: http://stackoverflow.com/q/51129840
tags question: http://stackoverflow.com/q/51070491
tags question: http://stackoverflow.com/q/51152036
tags question: http://stackoverflow.com/q/51051902
tags question: http://stackoverflow.com/q/51064581
tags question: http://stackoverflow.com/q/51106914
tags question: http://stackoverflow.com/q/51045775
tags question: http://stackoverflow.com/q/51036674
tag name: pyqt5
tags question: http://stackoverflow.com/q/51079515
tags question: http://stackoverflow.com/q/51063145
tags question: http://stackoverflow.com/q/51119616
tags question: http://stackoverflow.com/q/51068778
tags question: http://stackoverflow.com/q/51045539
tags question: http://stackoverflow.com/q/51066404

http://stackoverflow.com/q/51124869
has comment: http://stackoverflow.com/comment/89234714
has answer: http://stackoverflow.com/a/51125867
answer count: 2
tagged with: python-3.6
has title: Comparing two cards in list
has comment: http://stackoverflow.com/comment/89234671
score: 0
has comment: http://stackoverflow.com/comment/89234695
has comment: http://stackoverflow.com/comment/89234766
has body: I'm trying to write Russian Schnapsen (Thousand Schnapsen) but I'm stuck at comparing two cards on the table (table is list with only two cards). Here's not entire code, because entire is not necessery and I would have to translate all my variables from native language to english. import random class Cards: def __init__(self,rank,suit): self.rank = rank self.suit = suit def show(self): if self.rank == 10: rank = 'J' elif self.rank == 11: rank = 'Q' elif self.rank == 12: rank = 'K' elif self.rank == 13: rank = '10' elif self.rank == 14: rank = 'A' else: rank = self.rank print(rank,self.suit) class Deck: def __init__(self): self.cards = [] self.build() self.shuffle() def build(self): for suit in ['Spades', 'Clubs', 'Diamonds', 'Hearts']: for rank in range(9,15): self.cards.append(Cards(rank, suit)) def shuffle(self): random.shuffle(self.cards) And there is class Game with not working function check (list table is filled with two cards earlier) class Game: def __init__(self): self.table = [] def check(self): x = self.table[0] for card in self.table: if card &gt; x: # (rest of the code...) The error I get is: TypeError: '&gt;' not supported between instances of 'Cards' and 'Cards' My main and only question is how could I compare two cards in list (or maybe there is better solution than doing it in list) by their rank.
accepted answer: http://stackoverflow.com/a/51125867
has comment: http://stackoverflow.com/comment/89234804
has comment: http://stackoverflow.com/comment/89234987
tagged with: python
possible better answer: http://stackoverflow.com/a/51125016
has answer: http://stackoverflow.com/a/51125016
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89159146
has text: A duplicate was asked 5 minutes earlier!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51085180
score: 1

http://stackoverflow.com/q/51033549
tagged with: algorithm
tagged with: data-structures
has comment: http://stackoverflow.com/comment/89059609
has comment: http://stackoverflow.com/comment/89059616
score: 0
accepted answer: http://stackoverflow.com/a/51033936
answer count: 1
has comment: http://stackoverflow.com/comment/89059442
favorite count: 0
tagged with: multithreading
has title: Data structure to maintain a pair of files
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51033936
upvote count: 1
has comment: http://stackoverflow.com/comment/89059622
downvote count: 1
has comment: http://stackoverflow.com/comment/89059513
type: Question
has body: Background There are two files with name alertfile &amp; eventfile. This file pair is sitting in multiple folders(shown below), with each file pair having different content. Only way to recognise the names of file pair different from other pair is through the folder structure, they sit in. Files will always be opened in read-only mode using python file api in Linux. With respect to content, One file pair has no relation with other file pair. No clue on the depth of folder structure. Folder names are unknown(in advance). Every folder may not have these file pairs. Some folder may have only sub-folders that have these file pairs. So, a folder can be just empty. Size of each file pair is KB's in size and are static files. root_folder | | +---folder1 | | | |___ alertfile | |___ eventfile | +---folder2 | | | |___ alertfile | |___ eventfile | | | +--- folder_2_1 | | | |___alertfile | |___eventfile | | | +---folder_2_1_1 | | | |___alertfile | |___eventfile | | +---folder3 | | | |___ alertfile | |___ eventfile | +---folder4 | | | +---folder4_1 | | | |____ alertfile | |____ eventfile | | | +---folder4_1_1(empty) : : : Goal There is a need to access the content of all these file pairs in different areas of code, for different purpose. Program is a server program... that maintains the cache of these set of file pairs... 1) Which data structure should I use to efficiently access these file pairs? to actually parse the content in these file pairs....for multiple reasons 2) Does it be faster to have content of each file pair, in a pair of data structures? and keyed with a folder path.. 3) Can the file-reading be multi threaded before creating the cache? Because python GIL allows IO bound threads to interleave..
tagged with: filesystems
has comment: http://stackoverflow.com/comment/89059520

http://stackoverflow.com/comment/107927569
score: 0
has text: thanks for the answer and the discussion in the chat, It really helped me. I was facing a similar error in doing print('\u25cf') in python3. Setting the locale to en_US.utf8 helped.
type: Comment
comment on: http://stackoverflow.com/a/51027262
type: AnswerComment

http://stackoverflow.com/comment/89255654
score: 3
comment on: http://stackoverflow.com/a/51126393
type: AnswerComment
type: Comment
has text: Great answer! Thanks a lot for help! One notice I have: when adding callback handlers to dispatcher, we need to define the pattern attribute more clear: `pattern='^m1$'` or `pattern='^m1_1$'` — so that callback data `m1` doesn't trigger `'m1_1'`.

http://stackoverflow.com/q/51045775
answer count: 0
has comment: http://stackoverflow.com/comment/89085904
has body: While I am able to successfully implement a connection to a method from the linkActivated listener of my QTableWidget's QLabel, I can't figure out how to pass the link through the method despite the fact that the documentation says that the link is obtainable. linkActivated(const QString &link) What I can't figure out is how to get that '&link' data in Python. There are three questionmarks (???) in the place where I am trying to pass the link. def test(i = 1) qtbl = QtWidgets.QTableWidget(self.scrollAreaWidgetContents_2) qtbl.setGeometry(QtCore.QRect(0, 0, 870, 30)) qtbl.setObjectName("qtbl%s" % i ) widget = QtWidgets.QWidget() widgetText = QtWidgets.QLabel("foobar") widgetLayout = QtWidgets.QHBoxLayout() widgetLayout.addWidget(widgetText) widgetLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) widget.setLayout(widgetLayout) widgetText.linkActivated.connect(lambda ix, sf = self, lk = ??? : linkListener(sf, lk)) qtbl.setCellWidget(0, 0, widget) def linkListener(self, link): print(link) Design Class: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(896, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.scrDocumentTables = QtWidgets.QScrollArea(self.centralwidget) self.scrDocumentTables.setGeometry(QtCore.QRect(10, 10, 871, 541)) self.scrDocumentTables.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scrDocumentTables.setWidgetResizable(False) self.scrDocumentTables.setObjectName("scrDocumentTables") self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 869, 539)) self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") self.scrDocumentTables.setWidget(self.scrollAreaWidgetContents_2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry…
tagged with: pyqt5
upvote count: 1
downvote count: 1
has title: PyQt5 - How to pass link through method connected to QLabel's linkActivated signal?
type: Question
score: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89084459
tagged with: python
has comment: http://stackoverflow.com/comment/89098482
has comment: http://stackoverflow.com/comment/89098427
duplicate of: http://stackoverflow.com/q/45090982

http://stackoverflow.com/q/51085161
linked to: http://stackoverflow.com/q/41645898
type: Question
has answer: http://stackoverflow.com/a/51085263
has answer: http://stackoverflow.com/a/51085219
duplicate of: http://stackoverflow.com/q/41645898
has comment: http://stackoverflow.com/comment/89159407
has comment: http://stackoverflow.com/comment/89158717
has body: I have a list of floats as such: list_of_numbers = [6.983508046396359, 3.1427777550591887, -24.42539243473745] I wish to assign the list of floats into individual variables as such w1 = 6.983508046396359 w2 = 3.1427777550591887 w3 = -24.42539243473745 How do i go about assigning them into the desired variables?
favorite count: 0
tagged with: python-3.x
upvote count: 2
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51085308
tagged with: python
has comment: http://stackoverflow.com/comment/89158752
tagged with: list
has title: How do i iterate through a list of floats and assign them into variables?
score: 1
has answer: http://stackoverflow.com/a/51085304
has answer: http://stackoverflow.com/a/51085333
has comment: http://stackoverflow.com/comment/89158762
downvote count: 1

http://stackoverflow.com/comment/89289439
type: AnswerComment
has text: The code works great. I am trying now to sum up all the number of black pixels in each ring but finding that sum(v) is not working. If possible could you recommend how to do this?
type: Comment
comment on: http://stackoverflow.com/a/51083159
score: 0

http://stackoverflow.com/comment/98036675
type: Comment
has text: Is the last line, continue, necessary here? Does it make any difference? Wouldn't the while-loop just start a new iteration anyway?
comment on: http://stackoverflow.com/a/51087069
score: 0
type: AnswerComment

http://stackoverflow.com/a/51019331
has body: score is only scoped within the run_quiz function - you need to make it a global for it to be available in the penultimate line
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51019303
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89090478
type: Comment
type: QuestionComment
has text: I found this and it looks like there isn't a solution in a venv. https://github.com/unbit/uwsgi/issues/1770
comment on: http://stackoverflow.com/q/51049728
score: 0

http://stackoverflow.com/comment/89124733
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51063038
has text: Hm - could you try to change this code: `for row in rows: processedRow = map_schema(row) write_json(file, processedRow)` and do write to file not every one record but every say 100 or 1000 - I still thinking issue not with bq but with file writing

http://stackoverflow.com/comment/89269815
comment on: http://stackoverflow.com/a/51142713
type: AnswerComment
score: 0
type: Comment
has text: Do you know the guy who votes up for your and mine answer?(I vote up for you)

http://stackoverflow.com/comment/89186618
score: 0
has text: @neverwalkaloner I've just updated. im using Django User system. so i don't have user model. that's all.
type: QuestionComment
comment on: http://stackoverflow.com/q/51097943
type: Comment

http://stackoverflow.com/q/51148261
tagged with: python
has comment: http://stackoverflow.com/comment/89280841
tagged with: tkinter
answer count: 0
has body: from tkinter import * window = Tk() b1=Button(window, text="close", command=window.destroy) b1.grid(row=0,column=0) window.mainloop() In this code, when I execute and push a button of window "close", the window never close, infinite loading, until I task kill it. No error happens. Could you explain what happened or Is there another way to close a window? otherwise, this is my hardware problem? I am using: Macbook air 2012 model python 3.6.6 jupyter lab Thank you!
type: Question
has title: command = window.destroy doesn't work
score: 0
has comment: http://stackoverflow.com/comment/89280571
type: UnansweredQuestion

http://stackoverflow.com/comment/89237844
type: Comment
type: QuestionComment
has text: You need to be careful to distinguish between `Decimal` objects and string representations of those objects. A `Decimal` object isn't related to any particular representation: `Decimal("1e-7")` and `Decimal("0.0000001")` give the exact same object. In this question, you're asking for a specific *representation* of your `Decimal` object, and that's the domain of string formatting, as in @MatthewStory's answer.
score: 1
comment on: http://stackoverflow.com/q/51126233

http://stackoverflow.com/comment/89257949
has text: How come it got 3 more column? and why A and B shifted? sorry but got confuse.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51136806
type: Comment

http://stackoverflow.com/a/69602571
answers question: http://stackoverflow.com/q/51111626
score: 0
has body: according to Tensorflow official documents if you have a input shape with dimensions like [1 224 224 3] and lets say you have an image in your drawable directory called image23 then to get your desired input you have to follow this steps : Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.image23), 224, 224, true); ByteBuffer input = ByteBuffer.allocateDirect(224 * 224 * 3 *4).order(ByteOrder.nativeOrder()); for (int y = 0; y &lt; 224; y++) { for (int x = 0; x &lt; 224; x++) { int px = bitmap.getPixel(x, y); // Get channel values from the pixel value. int r = Color.red(px); int g = Color.green(px); int b = Color.blue(px); // Normalize channel values to [-1.0, 1.0]. This requirement depends // on the model. For example, some models might require values to be // normalized to the range [0.0, 1.0] instead. float rf = (r - 127) / 255.0f; float gf = (g - 127) / 255.0f; float bf = (b - 127) / 255.0f; input.putFloat(rf); input.putFloat(gf); input.putFloat(bf); } } the input now is ready to be fed to Tensorflow.run(input, output) function.
type: Answer

http://stackoverflow.com/comment/89216430
type: QuestionComment
comment on: http://stackoverflow.com/q/51097773
has text: I think the burden is on you to determine whether or not `glob.glob` is sufficient. Python is open-source, you can audit it yourself to determine whether or not it meets your requirements.
score: 0
type: Comment

http://stackoverflow.com/a/51070361
accepted answer of: http://stackoverflow.com/q/51069426
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51069426
type: Answer
score: 1
has body: I think you could update your regex to match the json without the semicolon at the end by adding that to the positive lookahead (?=;&lt;/script&gt;): (?&lt;=window\._sharedData = )(?P&lt;json&gt;.*)(?=;&lt;/script&gt;) Your code might look like this without the [3] in the first line for your given example: s = str(soup.find_all("script", type="text/javascript")) m = re.search(r"(?&lt;=window\._sharedData = )(?P&lt;json&gt;.*)(?=;&lt;/script&gt;)", s) if m: data = json.loads(m.group('json')) for i in data['entry_data']["ProfilePage"]: for j in i['graphql']['user']['edge_owner_to_timeline_media']['edges']: print(j['node']["id"])
upvote count: 1

http://stackoverflow.com/comment/89266493
has text: I don't know if `pandas` has an alternative. It seems to prefer `pytables` and `HDFStore`. `h5py` appears to be a better match with `h5write` (though I only glanced at its docs).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51139899

http://stackoverflow.com/q/51014551
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78432946
tagged with: python
has answer: http://stackoverflow.com/a/75610296
has title: Convert string of base64 back to base64 bytes
upvote count: 1
type: Question
has body: I've uploaded an image using OpenCV and then encode it with base64 encoding using base64's b64encode. &gt;&gt;&gt; import cv2 &gt;&gt;&gt; import base64 &gt;&gt;&gt; image = cv2.cvtColor(cv2.imread("some_image.jpg"), cv2.COLOR_BGR2RGB) &gt;&gt;&gt; image_64 = base64.b64encode(image) &gt;&gt;&gt; image_64 b'//////////////////... &gt;&gt;&gt; type(image_64) &lt;class 'bytes'&gt; Then I convert it into a string using the str() method. This creates a string of the encoded image. &gt;&gt;&gt; image_64str = str(image_64) &gt;&gt;&gt; image_64str b'//////////////////... &gt;&gt;&gt; type(image_64str) &lt;class 'str'&gt; Both of them (the &lt;class 'bytes'&gt; type and the &lt;class 'str'&gt;) looks similar. I attempted to decode them using base64's b64decode and the decode() function. However, an error occurred when I decoded the image_64str. &gt;&gt;&gt; image_64str.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'str' object has no attribute 'decode' &gt;&gt;&gt; base64.b64decode(image_64str) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding I fully understood what the errors were trying to tell me. But my question is, how can i convert the string of the encoded image (image_64str) back to bytes? I've tried to use base64's 'b64encode` again on the string. However, it returns an error. &gt;&gt;&gt; str_to_b64 = base64.b64encode(image_64str) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 58, in b64encode encoded = binascii.b2a_base64(s, newline=False) TypeError: a bytes-like object is required, not 'str' Please do tell if anybody noticed what i was miss…
score: 1
has comment: http://stackoverflow.com/comment/89026816
tagged with: base64
tagged with: aws-api-gateway
has comment: http://stackoverflow.com/comment/89026940
has comment: http://stackoverflow.com/comment/89047350
has comment: http://stackoverflow.com/comment/89021931
has answer: http://stackoverflow.com/a/51033919
downvote count: 0
has comment: http://stackoverflow.com/comment/89021886
favorite count: 0
linked to: http://stackoverflow.com/q/31077366
tagged with: python-3.x

http://stackoverflow.com/a/51155681
has body: setup.py files are created by you, to define the packaging information used for your project. I'd strongly recommend reading The Packaging Python Projects tutorial, as the topic is much larger than can be covered here. All you do is add those lines to the top of your setup.py file, prior to any other imports (which might end up being monkeypatched by Pyinstaller, causing the problem).
has comment: http://stackoverflow.com/comment/89295023
score: 0
answers question: http://stackoverflow.com/q/51155505
has comment: http://stackoverflow.com/comment/89299265
type: Answer

http://stackoverflow.com/q/51062531
has comment: http://stackoverflow.com/comment/89115864
tagged with: http://stackoverflow.com/tag/zip
has comment: http://stackoverflow.com/comment/89186493
score: 1
has body: I have written following python flask code to download zip file. @ns.route('/zip_file_download', strict_slashes=False) class ZipDownload(Resource): def get(self): output_path = os.path.abspath(os.path.join(os.getcwd(), './out')) out_file_name = os.path.join(output_path, 'sample.zip') r = send_file(out_file_name, mimetype='application/octet-stream', attachment_filename='sample.zip', as_attachment=True) return r This downloads the zip file but on extracting the zip file it gives an error - Error - 21 - is not a directory - Unable to expand probably because it gets corrupted. I also tried with send_from_directory but the same error crept there too. I am developing this on Mac machine but the downloaded files are also corrupted when opened on windows or an other OS. Any suggestions? PS: Moreover, this issue is only happening when running the API from a Mac machine. Things seem to be fine when ran from windows on linux machine. It's quite peculiar.
upvote count: 1
type: Question
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/89135109
has title: Python flask on downloading zip file gets corrupted
tagged with: unzip
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/53758523
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51122730
tagged with: python
has body: I am using pyperclip in Python 3.6 If i have a giant 2D array(640X480) how can I copy it in one program and paste it another program using pyperclip copy() and paste() functions.
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51443613
has title: Using Pyperclip to copy and paste a 2d array
type: Question
tagged with: pyperclip
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51443613
upvote count: 2
possible better answer: http://stackoverflow.com/a/51122832
has answer: http://stackoverflow.com/a/51122832
has comment: http://stackoverflow.com/comment/89837380

http://stackoverflow.com/a/51123453
score: 0
has comment: http://stackoverflow.com/comment/89233611
has comment: http://stackoverflow.com/comment/89233596
has comment: http://stackoverflow.com/comment/89233824
has comment: http://stackoverflow.com/comment/89236086
has comment: http://stackoverflow.com/comment/89233286
answers question: http://stackoverflow.com/q/51123275
has comment: http://stackoverflow.com/comment/89233204
type: Answer
has comment: http://stackoverflow.com/comment/89236049
has comment: http://stackoverflow.com/comment/89232906
has comment: http://stackoverflow.com/comment/89233660
has comment: http://stackoverflow.com/comment/89233356
has comment: http://stackoverflow.com/comment/89233471
has body: Hej Shrvya. Pandas is awesome and can do all you are asking without loops :) You could do that in one line df = data[data['age'] != 1].drop_duplicates() We have made a new df that removes all records where 'age' != 1 and then we drop duplicates :) I am not sure what is the aim of printing values out. Why do you want to print values on screen?
has comment: http://stackoverflow.com/comment/89236043
has comment: http://stackoverflow.com/comment/89233210
has comment: http://stackoverflow.com/comment/89234970
has comment: http://stackoverflow.com/comment/89233064

http://stackoverflow.com/a/51048723
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89089483
type: Answer
accepted answer of: http://stackoverflow.com/q/51048626
answers question: http://stackoverflow.com/q/51048626
has comment: http://stackoverflow.com/comment/89088681
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89088816
has body: change your project url from from django.conf.urls import url from .views import admins, index, ratings urlpatterns = [ url('admins', admins, name='admins'), url('index/', index, name='index'), url('user_id', ratings, name='rating') ] to from django.urls import include, path from .views import admins, index, ratings urlpatterns = [ path('admins', admins, name='admins'), path('index/', index, name='index'), path('&lt;int:pk&gt;/', ratings, name='rating') ]
has comment: http://stackoverflow.com/comment/89088679
has comment: http://stackoverflow.com/comment/89089535
has comment: http://stackoverflow.com/comment/89088720
has comment: http://stackoverflow.com/comment/89088782
upvote count: 1

http://stackoverflow.com/comment/89343902
has text: So this is to shift right, is there any way you can make it so that this works on board[0], board[4], board[8], board[12]
comment on: http://stackoverflow.com/a/51159560
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89156510
has text: Wow, I didn't even know that unique could be used in this way; for me it was always a 1D operator that seemed to do something different. Very interesting approach!
comment on: http://stackoverflow.com/a/51083687
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51124296
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51124422
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/19078325
type: Question
has answer: http://stackoverflow.com/a/51124422
accepted answer: http://stackoverflow.com/a/51124363
score: 4
has title: How do I access a pandas groupby dataframe by grouped index?
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/74438267
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51124363
has body: Following this example I can create a simple dataframe and groupby import pandas as pd # Create a sample data frame df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], 'B': range(5), 'C': range(5)}) # group by 'A' and sum 'B' gf = df.groupby('A').agg({'B': 'sum'}) The result is the grouped dataframe gf B A bar 7 foo 3 I would like to access gf by the grouped indices. Something like... gf['foo'] returns 3 gf['bar'] returns 7 I would also like to plot by the grouped indices. Something like... gf.plot('A', 'B') such that x=['foo','bar'], y=[3,7]
favorite count: 0

http://stackoverflow.com/a/51112219
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51111866
upvote count: 1
has body: You should not use time.sleep in a tkinter application; use root.after instead. You also do not need to create your own game loop inside a while loop; tk.mainloop does it for you. calling update or update_idle_tasks is rarely necessary; let tkinter handle all these low levels actions for you. Here is a working version of your Pong app that addresses the main issues, and answers your question. It does not restart the game, you will have to work this out by yourself. Maybe you will want to place the game logic in a class that will handle the restarting ans setting up for you? Please ask a new question if you are having difficulties. I changed the star import to import tkinter as tk which keeps the namespace tidy, and I renamed your variable tk using root instead. import tkinter as tk import random class Ball: def __init__(self, canvas, color, size, paddle): self.canvas = canvas self.paddle = paddle self.id = canvas.create_oval(15, 15, size, size, fill=color) self.canvas.move(self.id, 245, 100) self.xspeed = random.randrange(-3,3) self.yspeed = -1 self.hit_bottom = False self.score = 0 def draw(self): self.canvas.move(self.id, self.xspeed, self.yspeed) pos = self.canvas.coords(self.id) if pos[1] &lt;= 0: self.yspeed = 9 if pos[3] &gt;= 400: self.hit_bottom = True if pos[0] &lt;= 0: self.xspeed = 9 if pos[2] &gt;= 500: self.xspeed = -9 if self.hit_paddle(pos): self.yspeed = -9 self.xspeed = random.randrange(-3,3) self.score += 1 def hit_paddle(self, pos): paddle_pos = self.canvas.coords(self.paddle.id) if pos[2] &gt;= paddle_pos[0] and pos[0] &lt;= paddle_pos[2] and \ pos[3] &gt;= paddle_pos[1] and pos[3] &lt;= paddle_pos[3]: return True return False class Paddle: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_rectangle(0, 0, 168, 20, fill=color) self.canvas.move(self.id, 200, 300) self.xspeed = 0 self.canvas.bind_all('&lt;KeyPress-Left&gt;', self.move_left) self.canvas.bind_all('&lt;KeyPress-Right&gt;', self.move_right) def draw(self): …
type: Answer
has comment: http://stackoverflow.com/comment/89576447

http://stackoverflow.com/comment/89058153
type: QuestionComment
has text: If the code isn't running, the bot wont run, simple as that. Which means you either need to leave your computer on and connected all the time, or you need to get a dedicated server to run your code for you.
score: 4
comment on: http://stackoverflow.com/q/51032917
type: Comment

forms
tags question: http://stackoverflow.com/q/51126769
type: Tag
tags question: http://stackoverflow.com/q/51105988
tags question: http://stackoverflow.com/q/51091451
tags question: http://stackoverflow.com/q/51034802
tags question: http://stackoverflow.com/q/51146120
tags question: http://stackoverflow.com/q/51158769
tag name: forms
tags question: http://stackoverflow.com/q/51144193

http://stackoverflow.com/a/70065363
type: Answer
score: 4
upvote count: 4
downvote count: 0
has body: In my case this was caused by pytest settings - I had set that warnings should be treated as errors. I changed my pytest.ini by adding: filterwarnings = ignore:.*deprecated and ignored since IPython.*:DeprecationWarning seems to solve the issue for me
answers question: http://stackoverflow.com/q/51020750

http://stackoverflow.com/comment/89122018
type: Comment
has text: I think the for loop should be nested. In the code "for date, open, high, low, close, zero in data:", 'data' is a list of tuples which would require further processing.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51065834

http://stackoverflow.com/a/51104220
has body: Your current approach is bugged, as x will always be type str, so the isinstance check will always be False. Plus, even if you fixed that, your code will replace every single digit to its index in args (as long as you also change args(x) to args[x]). I would use a regex substitution to convert your string to a proper format literal. Then you can use string format to insert the arguments. import re def simple_format(format, *args): new = re.sub(r"%(\d+)", r"{\1}", format) return new.format(*args) print(simple_format("hello %0", "world", "Ben")) # hello world
downvote count: 0
answers question: http://stackoverflow.com/q/51104040
type: Answer
has comment: http://stackoverflow.com/comment/89195832
score: 1
has comment: http://stackoverflow.com/comment/89195713
has comment: http://stackoverflow.com/comment/89195694
upvote count: 1

http://stackoverflow.com/comment/89065260
has text: When I execute the program, I am getting below result in postman { "message": { "username": "Missing required parameter in the JSON body" } }
type: Comment
comment on: http://stackoverflow.com/q/51024025
type: QuestionComment
score: 1

http://stackoverflow.com/q/51099754
type: AnsweredQuestion
has title: Django Error while trying to migrate model on Postgre DB
has answer: http://stackoverflow.com/a/51100093
accepted answer: http://stackoverflow.com/a/51100093
type: Question
score: 0
answer count: 1
tagged with: postgresql
tagged with: django
tagged with: python
tagged with: psycopg2
has body: I'm still learning to use Django and I have an issue while trying to create a model. Here's my models.py class Identifiants(models.Model): id = models.AutoField(primary_key=True) taxon = models.IntegerField(unique=True) noms = models.TextField(blank=True, null=True) fiche = models.IntegerField(blank=True, null=True) comestible = models.TextField(blank=True, null=True) sms = models.NullBooleanField() a_imprimer = models.NullBooleanField() lieu = models.TextField(blank=True, null=True) apparition = models.TextField() class Meta: managed = True db_table = 'identifiants' The makemigrations command works with no issues but the migrate one is where I have problems Running migrations: Applying app.0001_initial...Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.DataError: NUMERIC precision 65535 must be between 1 and 1000 LINE 1: ...iants" ("id" serial NOT NULL PRIMARY KEY, "taxon" numeric(65... I'm using IntegerField method so I can't see why there is an issue ... Can anyone help me ? Thanks

http://stackoverflow.com/a/51031187
has comment: http://stackoverflow.com/comment/89055058
has body: The argument is being passed upstream, that is, to your mysql dbapi module - All sqlalchemy does is call the connect function from the chosen module. As you can see here https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html sslca is not a valid parameter to the connect function - the correct parameter name would be ssl_ca I think? In other words, you have to find out how to do what you want with python-mysql directly, without using sqlalchemy at all - sqlalchemy is not the culprit here Also you say However, I don't have MySQLdb installed, so it must be SQLAlchemy which is using it. SQLAlchemy is not a database, it doesn't connect to anything. It is only a layer, you have to provide a database module for it to use to connect to databases.
has comment: http://stackoverflow.com/comment/89054789
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89055609
has comment: http://stackoverflow.com/comment/89055050
score: 3
accepted answer of: http://stackoverflow.com/q/51031123
upvote count: 3
answers question: http://stackoverflow.com/q/51031123
has comment: http://stackoverflow.com/comment/89054924
downvote count: 0

http://stackoverflow.com/comment/89192833
type: Comment
type: QuestionComment
score: 0
has text: You use `k` as a loop variable twice
comment on: http://stackoverflow.com/q/51102752

http://stackoverflow.com/q/51120293
tagged with: python
score: 2
has body: I am trying to extract the contents from pandas dataframe without the index. Dataframe: L_No Exp_date LC_139 12/01/2019 When I do L_No = df["L_No"], I get the output with the index rather than just the L_No. Current output: 83919 LC_139 Expected output: LC_139
has answer: http://stackoverflow.com/a/51120309
type: Question
downvote count: 0
tagged with: dataframe
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 2
has title: print contents of pandas dataframe without its index
type: UnansweredQuestion

http://stackoverflow.com/comment/89144688
score: 1
type: AnswerComment
has text: I agree with @Manuel, this does not solve the memory issue (at least theoretically).
comment on: http://stackoverflow.com/a/51074176
type: Comment

http://stackoverflow.com/a/51049107
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51048950
has body: No, it is not possible. GUI widgets cannot be shared between processes. On some platforms, it just isn't possible at all; on other platforms, it would be possible, but only by doing things very differently from the way Tk does; on others, it sort of works, but the event loops are all screwed up. So, the result may be that nothing shows up, that one or both processes freezes, that the GUI doesn't respond to events, that tkinter raises an exception in the child, that tkinter creates a whole separate independent GUI, or, if you're really unlucky, that things unpredictably work sometimes but do one of the other things other times. However, that doesn't mean there's no way to do what you want, just that you can't do it directly. The simplest solution is to marshal your Canvas commands and pass them over a Pipe or Queue for the main process to execute. A fully general solution isn't that hard, but in your case, it should be even simpler: all you want the background process to do is process an image and then display it. So the only Canvas command you need is create_image. And, in fact, you can probably do with tasks on a Pool, which just return the image when they're done, with the main process doing the create_image with the results. Mixing waiting on multiprocessing async results with a tkinter event loop is a bit of a pain, but if you use concurrent.futures, you can just attach the create_image as a callback on the Future returned by the task. A different option is to have the background processes create off-screen Canvas objects, draw to them, then capture the results as a BitmapImage or a postscript rendering, which you can then pass to the main process to blit onto a Canvas of its own. But this is a lot more complicated; I think the other solution will probably work a lot better for you.
answers question: http://stackoverflow.com/q/51048950
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/51138190
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89282506
has comment: http://stackoverflow.com/comment/89287578
type: Answer
accepted answer of: http://stackoverflow.com/q/51137362
score: 2
answers question: http://stackoverflow.com/q/51137362
upvote count: 2
has comment: http://stackoverflow.com/comment/89283079
has body: It seems that a large part of your issues is having to recompute the entire lists min and max each time, e.g. your subplot x and y min/max values, rather than processing your entire appended list, you should use a variable to hold the lowest and highest values so far compare the current piece of input data to them, and if it meets condition update them, subplot1.set_ylim(min(y_data1)-1,max(y_data1)+1) subplot1.set_xlim(min(x_data)-1,max(x_data)+1) You also appear to be resetting up the subplot labels every single update, now I am not as familiar with GUI's in TKinter, but i feel this could be covered in an initilisation definition, subplot1.set_title('Channel 1') subplot1.set_xlabel('Time') subplot1.set_ylabel('Frequency') The first suggestion should keep your program running in a more consistent time, rather than incrementally slowing down, the other should be able to reduce how much your doing per update.

http://stackoverflow.com/comment/89170625
type: QuestionComment
has text: Lots of sub-questions in there, but to start off with it might be useful to look at [pandas dataframes](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) which are great for working with mixed datatypes like you have. You can make use of `.rstrip` to remove trailing characters, and then multiply as desired on your individual values.
score: 0
comment on: http://stackoverflow.com/q/51090877
type: Comment

http://stackoverflow.com/q/51119495
has body: I just started learning flask and I am stuck at setting up the Flask environment variables. I don't know how to setup the environment variables. Whenever I use the flask run command, I encounter the following error: Error message : Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory. I did a lot of google searches to setup environment variables on Windows but I am unable to find a solution and sometimes I am not able to understand the solution. How to do this ? How to get the "app.py" or "wsgi.py" ?
has answer: http://stackoverflow.com/a/61817098
has title: How to setup environment variables for `flask run` on Windows?
tagged with: flask
has answer: http://stackoverflow.com/a/68512087
has answer: http://stackoverflow.com/a/65694717
answer count: 25
has answer: http://stackoverflow.com/a/61454357
downvote count: 3
has answer: http://stackoverflow.com/a/56387789
tagged with: environment-variables
has answer: http://stackoverflow.com/a/56603506
linked to: http://stackoverflow.com/q/49238583
has answer: http://stackoverflow.com/a/51727266
favorite count: 0
score: 39
has answer: http://stackoverflow.com/a/66195368
has answer: http://stackoverflow.com/a/68797988
has answer: http://stackoverflow.com/a/56306670
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51138183
has answer: http://stackoverflow.com/a/70332920
has answer: http://stackoverflow.com/a/64729789
has answer: http://stackoverflow.com/a/51199314
tagged with: python
has answer: http://stackoverflow.com/a/71989245
upvote count: 42
has answer: http://stackoverflow.com/a/71489795
has answer: http://stackoverflow.com/a/70649418
has answer: http://stackoverflow.com/a/69185011
has answer: http://stackoverflow.com/a/69864316
has answer: http://stackoverflow.com/a/71586463
has answer: http://stackoverflow.com/a/73553437
has comment: http://stackoverflow.com/comment/89224918
type: Question
has answer: http://stackoverflow.com/a/57735648
has answer: http://stackoverflow.com/a/60785158
has answer: http://stackoverflow.com/a/71433623
has answer: http://stackoverflow.com/a/62209719

http://stackoverflow.com/q/51115713
has title: Error when trying to upgrade a python package
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/89217631
tagged with: python
has body: I have git pulled a python package (I think that is the correct terminology) that I already had installed and working. So now it is up to date, apparently I needed to update it using pip. I did the following: pip install the_package --upgrade But I got the following error message: Exception: Traceback (most recent call last): File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/req/req_set.py", line 666, in _prepare_file check_dist_requires_python(dist) File "/opt/work/python/2.7.13/lib/python2.7/site-packages/pip/utils/packaging.py", line 48, in check_dist_requires_python feed_parser.feed(metadata) File "/opt/work/python/2.7.13/lib/python2.7/email/feedparser.py", line 177, in feed self._input.push(data) File "/opt/work/python/2.7.13/lib/python2.7/email/feedparser.py", line 99, in push parts = data.splitlines(True) AttributeError: 'NoneType' object has no attribute 'splitlines' I'm not sure what the problem is. Could someone please point me in the right direction?
has comment: http://stackoverflow.com/comment/89217556
has comment: http://stackoverflow.com/comment/89224424
type: UnansweredQuestion
tagged with: pip
has answer: http://stackoverflow.com/a/51116025
type: Question

http://stackoverflow.com/comment/89189555
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51096570
type: Comment
has text: @Krishnamurthy - OK, can you send me sample data csv, expected output? I have email in my profile

http://stackoverflow.com/comment/129838225
type: AnswerComment
score: 4
type: Comment
has text: FLASK_ENV is going to be deprecated. FLASK_DEBUG=0 turns OFF debug mode, which may not be a good idea during development/testing.
comment on: http://stackoverflow.com/a/65676528

http://stackoverflow.com/comment/89204909
comment on: http://stackoverflow.com/q/51108874
has text: Sounds like `RList` is actually a numpy array or the like, not a `list`. Is it?
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51031458
downvote count: 0
has comment: http://stackoverflow.com/comment/89055355
score: 7
has body: You almost had it! Just remove the quotes, and store the function name directly. Functions in Python are just like variables: callout = [shooting, mugging] randomthing = random.choice(callout) print(randomthing())
has comment: http://stackoverflow.com/comment/89055485
has comment: http://stackoverflow.com/comment/89055464
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51031432
type: Answer
accepted answer of: http://stackoverflow.com/q/51031432
has comment: http://stackoverflow.com/comment/89055416

http://stackoverflow.com/a/51780164
score: 18
has body: First install python 3.6.5, then run pip install mysqlclient==1.3.12
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51062920
answers question: http://stackoverflow.com/q/51062920
type: Answer
upvote count: 19
downvote count: 1

http://stackoverflow.com/comment/89233498
has text: Thank you @hpaulj , `parse_known_args` should be a better workaround for my case for pre-3.7 python.
score: 0
comment on: http://stackoverflow.com/q/51113866
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51129201
has answer: http://stackoverflow.com/a/51131672
tagged with: python
type: AnsweredQuestion
tagged with: chatterbot
upvote count: 1
has title: Develop conversational chatbot for chinese language in python
downvote count: 1
accepted answer: http://stackoverflow.com/a/51131672
type: Question
has body: I want to develop a conversational chatbot for chinese language in python like the user says "你好" which means "hello" in chinese and chatbot respond. i think it will be very difficult to build from scratch and write every expected response for chatbot. i want to find an opensource library to connect with my API which is able to respond to user and do the conservation with the user. i already know about a chatbot developed by Microsoft called "Xiaobing" which is especially developed for chinese people but i don't know if they provide an API for developers or not.There is also another github project called brobot(https://github.com/lizadaly/brobot/) but i don't know if it provide chinese language support. Any suggestions or guidance from anyone here would be appreciated.
tagged with: wechat
tagged with: chatbot
score: 0
answer count: 1
favorite count: 0
tagged with: xiaomi

http://stackoverflow.com/q/51128298
has body: I am trying to do something that I am following in a tutorial. The code is for testing a dictionary and it is as it follows: cd = ConfigDict('config_file.txt') if len(sys.argv) == 3: key = sys.argv[1] value = sys.argv[2] print('writing data: {}, {}'.format(key, value)) cd[key] = value else: print('reading data') for key in cd.keys(): print(' {} = {}'.format(key, cd[key])) To test one can enter the name of the file alone or with the testing cases direct to the terminal as you can see below: I am using Pycharm and I did not find a way to do the same as it is done on this tutorial. I tried to Open on Terminal and to change *Run-&gt;Edit Configurations -&gt; Run with python console or Run-&gt;Edit Configurations -&gt; Emulate terminal in output console* I did not figure how to run it with the python file and the inputs to tests. Any hints are highly appreciated!
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89241589
answer count: 1
has answer: http://stackoverflow.com/a/51128373
accepted answer: http://stackoverflow.com/a/51128373
has title: Running my file from the terminal Pycharm
tagged with: console
tagged with: terminal
tagged with: python
type: AnsweredQuestion
tagged with: pycharm

http://stackoverflow.com/comment/89221678
comment on: http://stackoverflow.com/q/51117776
type: Comment
has text: Fairly small, I would assume not more than a few tens of players. I would say its more like tha partition problem, but it has to be done for a number of different combinations, so I am not sure how to keep it optimal.
type: QuestionComment
score: 0

http://stackoverflow.com/q/51086065
tagged with: python
linked to: http://stackoverflow.com/q/24681820
type: UnansweredQuestion
tagged with: whitespace
has answer: http://stackoverflow.com/a/51086176
has body: Running Python 2.6.6 and whenever I try to use 2 variables which are paths in another variable, I get a whitespace error: 'C:\Program' is not recognized as an internal or external command, operable program or batch file. This is my code and the issue is with the cmd variable: from subprocess import call, Popen, PIPE, STDOUT example = '"C:\\Program Files\\Example\\test.cmd"' output = '"C:\\test\\python\\reportFromPython.xml"' cmd = example + " -T 'testing title' " + output p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) output = p.stdout.read() print output If I change cmd = example + " -T 'testing title' " + output to cmd = example + " -T 'testing title' " Then it works but I need the output portion... How can I get it working with both variables?
has comment: http://stackoverflow.com/comment/89160660
has title: python whitespace issue with 2 variables
type: Question
answer count: 1
tagged with: variables
score: 0
tagged with: scripting

http://stackoverflow.com/q/51134686
accepted answer: http://stackoverflow.com/a/51141750
has comment: http://stackoverflow.com/comment/89265607
has comment: http://stackoverflow.com/comment/89253649
downvote count: 1
has comment: http://stackoverflow.com/comment/89266069
type: Question
linked to: http://stackoverflow.com/q/3939660
has comment: http://stackoverflow.com/comment/89266419
has comment: http://stackoverflow.com/comment/89265902
tagged with: sieve-of-eratosthenes
has comment: http://stackoverflow.com/comment/89265647
has comment: http://stackoverflow.com/comment/89267203
answer count: 1
has answer: http://stackoverflow.com/a/51141750
favorite count: 0
has title: Why is this prime sieve so slow in Python compared with the same algorithm in Java or C#?
upvote count: 2
has body: I'm trying to build a sieve for project Euler solutions. I need primes up until about 100M, preferably with option to go much higher. This implementation I have works fine, but is very slow: class Primes: __size = None __sieve = [] __primes = [] def __init__(self, size): self.__size = size self.__sieve = [True] * size for x in range(2, size): if self.__sieve[x]: self.foundPrime(x); def foundPrime(self, x): self.__primes.append(x) for duplicate in range(2 * x, self.__size, x): self.__sieve[duplicate] = False For a sieve sized 100M, this initialization takes about 70 seconds on my fairly high-end computer. Does anyone know why? Because in Java and C# this took me about 1 second... So, this post is different from other posts in that I do not want to know how to implement the algorithm, I want to understand why it is so slow in Python. Some prints give me the information that about 50% of the time is spent on finding the first 100K primes.
has comment: http://stackoverflow.com/comment/89253639
has comment: http://stackoverflow.com/comment/89361488
tagged with: python
tagged with: primes
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89253989
tagged with: performance
has comment: http://stackoverflow.com/comment/89266591
score: 1
tagged with: java

http://stackoverflow.com/a/51150869
upvote count: 1
type: AcceptedAnswer
has body: By using find you can get your list of files and process them one by one: for TGZ in $(find . -name "file.tar.gz") do WD=$(dirname $TGZ) cd $WD tar xzf file.tar.gz &lt;your python script&gt; rm *.faa cd - done That would be a direct translation of your words: uncompress the files in the same folder where they are, process them and remove the data. I'm assuming that the extracted files are only *.faa files. There is also quite a lot of directory movement due to your script only working with the filed in the current folder. Personally, I would feel safer by using a sligtly different approach: for TGZ in $(find . -name "file.tar.gz") do mkdir -p work cd work tar xzf $TGZ &lt;your python script&gt; cd .. rm -rf work done There is also folder movement, but you always move to the same place and you do a complete cleanup, in case there are other things besides *.faa files. Regarding your python script... did you though of using a dictionary instead of a bunch of single-letter vars? base = dict() base['A'] = 0 base['A'] += 1 That would reduce your code size quite a lot and make it more readable.
type: Answer
has comment: http://stackoverflow.com/comment/89323525
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89325966
answers question: http://stackoverflow.com/q/51150128
accepted answer of: http://stackoverflow.com/q/51150128

http://stackoverflow.com/comment/89242664
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51128783
type: Comment
has text: @PM2Ring: it's hard to tell. They didn't provide working code `<shrug>`. I assumed since he asked a question in the very first sentence, he wanted an answer to that question.

scheduled-tasks
tags question: http://stackoverflow.com/q/51102631
tag name: scheduled-tasks
type: Tag
tags question: http://stackoverflow.com/q/51116849

http://stackoverflow.com/comment/89221970
type: AnswerComment
has text: I think nested dictionaries looks very promising, I'll decide on what the best approach is for my use case but in general, your help really opens up the possibilities. Thanks much for all your help, I'll accept it as correct answer!
type: Comment
comment on: http://stackoverflow.com/a/51114689
score: 0

http://stackoverflow.com/q/51140916
has answer: http://stackoverflow.com/a/51143084
favorite count: 0
has comment: http://stackoverflow.com/comment/89266946
has comment: http://stackoverflow.com/comment/89268110
tagged with: python
has comment: http://stackoverflow.com/comment/89266783
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89267873
accepted answer: http://stackoverflow.com/a/51143084
upvote count: 1
has comment: http://stackoverflow.com/comment/89270309
type: Question
has title: Pandas DataFrame Advanced Indexing
has body: I am looking for some help with pandas DataFrame sorting. I have a Data frame of 8 columns that go like; ['Date' , 'S ID', 'Se ID', 'S #', 'File Size (Mb)', 'HD name', 'Start Time', 'End time'] I've then done a: DataFile.groupby(['HD Name','Date','Se ID','S ID'])['File Size (Mb)'].agg({'Sequence #':'count','File Size (Mb)':'sum'}).reset_index().rename(columns={'Sequence #':'# of Files'}) which takes my data and groups it by the matching grouby() parameters and sums the file sizes. I would like to add two columns on to this which holds the first 'Start Time' and last 'End Time' how would I go about doing that? I'm thinking my only option may be to loop over the data or create a duplicate dataframe to et start and end times of grouped data. Any ideas would be appreciated! Example dataframe: 'Hard Drive Name' : [H5 , H5 , H5 , H5 , H5] 'S ID' : [LA , LA , LA , SD , SD] 'Se ID' : [1200, 1200, 1200, 30, 30] 'Date' : ['10/01/2018' , '10/01/2018' , '10/01/2018' , '09/03/2018' , '09/03/2018'] '#' : [1 , 2 , 3 , 1 , 2] 'Start Time' : [[08:09:54] , [08:58:31] , [09:39:38] , [05:04:13] , [05:41:13] ] 'End Time' : [[08:28:54] , [09:17:31] , [09:58:38] , [05:23:12] , [06:00:12]] {'Date': {34: '10/01/2018', 35: '10/01/2018', 36: '10/01/2018', 37: '10/01/2018', 38: '10/01/2018', 39: '10/01/2018', 40: '10/01/2018', 41: '10/01/2018', 42: '10/01/2018', 661: '09/03/2018'}, 'End Time': {34: ['08:28:54'], 35: ['09:17:31'], 36: ['09:58:38'], 37: ['10:37:41'], 38: ['11:21:32'], 39: ['12:04:42'], 40: ['12:45:31'], 41: ['13:25:23'], 42: ['14:04:03'], 661: ['05:53:36']}, 'File Size (Mb)': {34: 1074.256284, 35: 1074.842244, 36: 1074.759444, 37: 1074.836956, 38: 1074.516156, 39: 1074.547044, 40: 1074.8363, 41: 1074.891492, 42: 1074.792068, 661: 1074.428204}, 'Hard Drive Name': {34: 'H5', 35: 'H5', 36: 'H5', 37: 'H5', 38: 'H5', 39: 'H5', 40: 'H5', 41: 'H5', 42: 'H5', 661: 'H5'}, 'Sensor ID': {34: '1207', 35: '1207', 36: '1207', 37: '1207', 38: '1207', 39: '1207', 40: '1207', 41: '1207', 42: '12…
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89266747
has comment: http://stackoverflow.com/comment/89267855
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/89268133
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/89270264

http://stackoverflow.com/q/51014687
upvote count: 6
type: AnsweredQuestion
tagged with: mysql
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/51018368
has body: I run out of ideas. I googled now more then one day and I still can't find any useful answer to my question. What I did until now, I tried to use raw SQL but without luck. locations = db.session.query(Location, select([text('( 6371 * acos( cos( radians("53.6209798282177") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians("13.96948162900808") ) + sin( radians("53.6209798282177") ) * sin( radians( lat ) ) ) )')]).label('distance')).having('distance' &lt; 25).all() When using this raw SQL query I get zero results returned, but when running the same query in mysql it returns correct results. Further more I figured out, that when printing the query to terminal, it does not handle the HAVING() clause correctly. My query looks like this when printed: SELECT location.id AS location_id, location.created_date AS location_created_date, location.zip AS location_zip, location.user_id AS location_user_id, location.lat AS location_lat, location.lng AS location_lng, location.city AS location_city FROM location HAVING false = 1 How do I convert this SQL query to SQLAlchemy SELECT *, ( 6371 * acos( cos( radians(53.6209798282177) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(11.96948162900808) ) + sin( radians(53.6209798282177) ) * sin( radians( lat ) ) ) ) AS distance FROM location HAVING distance &lt; 25 ORDER BY distance; My table looks like this: +--------------+----------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+----------------+------+-----+---------+-------+ | id | varchar(50) | NO | PRI | NULL | | | created_date | datetime | YES | | NULL | | | zip | varchar(5) | NO | UNI | NULL | | | user_id | varchar(50) | NO | | NULL | | | lat | decimal(15,13) | NO | | NULL | | | lng | decimal(15,13) | NO | | NULL | | | city | text | NO | | NULL | | +--------------+----------------+------+-----+---------+-------+ Any help is appreciated.
tagged with: geospatial
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51018368
favorite count: 0
has title: Convert a complex SQL query to SQLAlchemy
score: 6
tagged with: python

http://stackoverflow.com/a/51041857
score: 1
has body: Because you must explicitly alias it with AS when using old style joins instead select * from flight f, iata i where f.ORIGIN = i.IATA; write select * from flight AS f, iata AS i where f.ORIGIN = i.IATA;
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51039738
answers question: http://stackoverflow.com/q/51039738
type: Answer
upvote count: 1

http://stackoverflow.com/comment/89193805
comment on: http://stackoverflow.com/q/51103259
type: QuestionComment
has text: Please comment if the name of the question is wrong. I search for "duplicate rows" or "multiply columns" but always worng results appear.
score: 0
type: Comment

http://stackoverflow.com/q/51144283
has title: Finding all timestamps in a page using regular expressions
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89273947
tagged with: time
tagged with: timezone
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51159351
tagged with: regex
tagged with: web-scraping
type: Question
has body: I'm trying to find the publication date of newspaper articles published online using Python, but each website uses their own unique style for their html and the publication time in the page meta isn't consistent between different domains. I've tried using the dateparser package, but it includes a relative dating system that incorrectly reads some words (like the string: 'a day') as relative times. Is there a good list of regular expressions out there that someone knows of/can share that includes as many ways to format a timestamp as possible, including support for reading timezones?

http://stackoverflow.com/q/51047415
downvote count: 0
has answer: http://stackoverflow.com/a/51120715
has comment: http://stackoverflow.com/comment/89191535
has comment: http://stackoverflow.com/comment/89123306
tagged with: pyparsing
type: Question
has answer: http://stackoverflow.com/a/51156187
has comment: http://stackoverflow.com/comment/89119160
upvote count: 2
has comment: http://stackoverflow.com/comment/89292692
answer count: 3
has body: I'm new to python and I'm trying to parse some data using pyparsing that looks like this string2 = """ object1 { key1 = value1 key2 = value2 #key3 = value3 key4 = value4 #key5 = value5 key6 = value6 subobject1 { key1 = value1 key2 = value2 key3 = value3 } } """ And I can get a key=value pair using this code def parse_objects(source): LBRACE,EQ,RBRACE,HASH = map(Suppress, '{=}#') object_name = Word(printables) #disable = MatchFirst(map(Literal, '#'.split())) key = Word(printables) value = Word(printables) if LineStart() == HASH: key_and_value = Group(HASH + key('key') + EQ + value('value')) else: key_and_value = Group(key('key') + EQ + value('value')) collection = Forward() object_body = Group(LBRACE + ZeroOrMore(collection | key_and_value) + RBRACE) collection &lt;&lt;= Group(object_name + object_body) return collection.parseString(source) collection = parse_objects(string2) print(collection.dump()) But I also need to parsing data that does not contain values in objects, only keys. For example object1 { key1 = value1 key2 #key3 = value3 key4 #key5 = value5 key6 = value6 subobject1 { key1 = value1 key2 = value2 key3 = value3 } } I tried to make changes to the code and add the checking expression if value is None. Something like this if value is None: key_and_value = Group(key('key')) else: if LineStart() == HASH: key_and_value = Group(HASH + key('key') + EQ + value('value')) else: key_and_value = Group(key('key') + EQ + value('value')) but I get an error Match W:(0123...) at loc 19(3,9) Matched W:(0123...) -&gt; ['key1'] Match W:(0123...) at loc 25(3,15) Matched W:(0123...) -&gt; ['value1'] Match W:(0123...) at loc 41(4,9) Matched W:(0123...) -&gt; ['key2'] Traceback (most recent call last): File "c:\Python27\my_projects\test_parser.py", line 86, in &lt;module&gt; collection = parse_objects(string2) File "c:\Python27\my_projects\test_parser.py", line 84, in parse_objects return collection.parseString(source) File "C:\Python27\lib\site-packages\pyparsing.py", line 163…
linked to: http://stackoverflow.com/q/44890040
has comment: http://stackoverflow.com/comment/89207901
favorite count: 0
tagged with: key-value
has title: Pyparsing: Parsing nested plaintext data with a key=value
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51110391
score: 2

http://stackoverflow.com/q/51053602
tagged with: pyodbc
upvote count: 6
type: AnsweredQuestion
tagged with: odbc
type: Question
answer count: 2
has title: pyodbc- connection failure to SQL Server
possible better answer: http://stackoverflow.com/a/51058356
downvote count: 0
has body: I have been trying to connect to Microsoft SQL Server. I have an ODBC connection set up and the test is successful. I am not using Windows Authentication to connect to SQL Server but it keep getting this error: Cannot be used with Windows authentication InterfaceError: ('28000', '[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452); [28000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') Here is my code: import pyodbc cnxn = pyodbc.connect(Driver='{SQL Server}', Server='servername.abc.xyz.co.com', username = 'user_xyz', password = 'abcdfgh') I am using Windows 7. Please help me debug this problem Thanks
tagged with: sql-server
has answer: http://stackoverflow.com/a/51072993
accepted answer: http://stackoverflow.com/a/51072993
tagged with: python
favorite count: 0
tagged with: windows-7
has answer: http://stackoverflow.com/a/51058356
score: 6

http://stackoverflow.com/comment/89298318
comment on: http://stackoverflow.com/q/51140483
score: 0
has text: Ok. Thanks for comment. I am new to Stack overflow so do not know
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89069888
has text: @Yes, That solved if it is possible, May you explain to me how did a Copy change it?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51038152
type: Comment

http://stackoverflow.com/q/51113138
favorite count: 0
possible better answer: http://stackoverflow.com/a/51113214
downvote count: 2
upvote count: 1
tagged with: python
has title: TypeError: must be real number, not Circle
tagged with: object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51113166
has body: import math as m class Circle: def __init__(self,radius): self.radius = radius count = 0 def area(r): k = m.pi * m.pow(r,2) return k I am not sure what wrong with the code above but when I am trying execute like below a = Circle(4) a.area() it throws an error like " k = m.pi * m.pow(r,2) TypeError: must be real number, not Circle" Unable to understand how it's considering the float value as an instance to the circle.
type: Question
answer count: 2
score: -1
has comment: http://stackoverflow.com/comment/89212849
tagged with: class
tagged with: typeerror
has comment: http://stackoverflow.com/comment/89214985
has answer: http://stackoverflow.com/a/51113166
has answer: http://stackoverflow.com/a/51113214

http://stackoverflow.com/a/51142427
has comment: http://stackoverflow.com/comment/89273462
has comment: http://stackoverflow.com/comment/89269966
has comment: http://stackoverflow.com/comment/89273593
downvote count: 0
has comment: http://stackoverflow.com/comment/89270072
type: Answer
answers question: http://stackoverflow.com/q/51142314
has body: As the documentation explains, when you seek on text files: offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour. In practice, what seek(1) actually does is seek 1 byte into the file—which puts it in the middle of a character. So, what ends up happening is similar to this: &gt;&gt;&gt; s = chr(12345)+chr(23456)+chr(34567)+'\n' &gt;&gt;&gt; b = s.encode() &gt;&gt;&gt; b b'\xe3\x80\xb9\xe5\xae\xa0\xe8\x9c\x87\n' &gt;&gt;&gt; b[1:] b'x80\xb9\xe5\xae\xa0\xe8\x9c\x87\n' &gt;&gt;&gt; b[1:].decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 3: invalid start byte So, seek(3) happens to work, even though it's not legal, because you happen to be seeking to the start of a character. It's equivalent to this: &gt;&gt;&gt; b[3:].decode() '宠蜇\n' If you want to rely on that undocumented behavior to try to seek randomly into the middle of a UTF-8 text file, you can usually get away with it by doing what you suggested. For example: def readchar(f, pos): for i in range(pos:pos+5): try: f.seek(i) return f.read(1) except UnicodeDecodeError: pass raise UnicodeDecodeError('Unable to find a UTF-8 start byte') Or you could use knowledge of the UTF-8 encoding to manually scan for a valid start byte in a binary file: def readchar(f, pos): f.seek(pos) for _ in range(5): byte = f.read(1) if byte in range(0, 0x80) or byte in range(0xC0, 0x100): return byte raise UnicodeDecodeError('Unable to find a UTF-8 start byte') However, if you're actually just looking for the next complete line before or after some arbitrary point, that's a whole lot easier. In UTF-8, the newline character is encoded as a single byte, and the same byte as in ASCII—that is, '\n' encodes to b'\n'. (If you have Windows-style endings, the same is true for return, so '\r\n' also encodes to b'\r\n'.) This is by design, to make it easier to handle this kind of problem. So, if you open the file in binary mode, you can seek forward or b…
score: 2
upvote count: 2

http://stackoverflow.com/q/51023652
has title: How to convert list to dictionary without messing up the sequence
has comment: http://stackoverflow.com/comment/89039816
has answer: http://stackoverflow.com/a/51023900
accepted answer: http://stackoverflow.com/a/51023900
type: Question
has answer: http://stackoverflow.com/a/51024060
possible better answer: http://stackoverflow.com/a/51024060
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89040040
answer count: 3
has answer: http://stackoverflow.com/a/51024230
has body: when i used a function it messed up the sequence of my dictionary arr = ['loyd1', 'loyd2', 'loyd3', 'loyd4'] list = {k: 0 for k in arr} {'loyd1': 0, 'loyd3': 0, 'loyd2': 0, 'loyd4': 0}
linked to: http://stackoverflow.com/q/1867861
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51104319
upvote count: 2
has body: If you copy all project with the virtualenv folder this is a bad practice, you need only to copy the project with the requirements.txt file, and install all packages from requirements.txt for example: # activate your virtualenv on your PC . env/bin/activate # now we need to create a requirements.txt file with `pip freeze` pip freeze &gt; requirements.txt # now in our folder we have a `requirements.txt` file with all our packages # after this copy all your packge without `virtualenv` folder, # but with `requirements.txt file # when you are on another PC create a new `virtualenv` activate it and install # the packages from `requirements.txt` with this command pip install -r requirements.txt some docs
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51103445
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51103445

http://stackoverflow.com/comment/89129317
comment on: http://stackoverflow.com/q/51069610
score: 1
type: Comment
has text: Basically because part of the code i want to write is taking "sentence" as input and instead of giving errors when some user adds strings i should just ignore them and make it function as a formula.
type: QuestionComment

http://stackoverflow.com/comment/89280538
comment on: http://stackoverflow.com/q/51148214
has text: If you type `list(range(0))` in your python interpreter it will return `[]`. So you can't iterate over an empty list.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51028444
has body: I am passing a generator object results from fx_rates view to template like this: def fx_rates(request): if request.method != 'POST': form = FxForm() results=[] else: form = FxForm(request.POST) if form.is_valid(): scraper = FxScraper() scraper.from_currencies.append(form.cleaned_data['from_currencies']) scraper.dates = form.cleaned_data['dates'].split(" ") scraper.to_currency = form.cleaned_data['to_currency'] results = scraper.results() context = {'form':form, 'results':results} return render(request, 'map_assistant/fx_rates.html',context) In the template for this view I am using the below to display results: &lt;ul&gt; {% for result in results %} &lt;li&gt;{{result}}&lt;/li&gt; {% endfor %} &lt;/ul&gt; (guess I can change it to {{next(results)}} once the issue described below is solved). The problem is I don't know how to prevent "[]" from displaying when the view is called using GET method (see if clause above). I cannot delete results=[] line because I will get an error when the view is called using GET. Guess I would need to somehow remove results from context dictionary when the method is GET?
has answer: http://stackoverflow.com/a/51028579
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51028546
has title: Django: how to alter context dictionary based on request method called
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/51054388
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51054334
has comment: http://stackoverflow.com/comment/89099812
has comment: http://stackoverflow.com/comment/89100033
has comment: http://stackoverflow.com/comment/89100505
type: Answer
has comment: http://stackoverflow.com/comment/89099676
has comment: http://stackoverflow.com/comment/89099651
has body: First day of each month? Easy. pd.to_datetime(df.assign(day=1)) 0 2015-12-01 1 2016-01-01 2 2016-02-01 dtype: datetime64[ns] If you run into conversion errors, try adding the errors='coerce' argument: pd.to_datetime(df.assign(day=1)) The thing to note here is that pd.to_datetime, when working with DataFrames, would need at least year, month, and day columns. Alternatively, pass a single string column to to_datetime. pd.to_datetime(df.assign(day=1).astype(str).agg('-'.join, axis=1)) # pd.to_datetime(df'col1', 'col2'.assign(day=1).astype(str).agg('-'.join, axis=1)) 0 2015-12-01 1 2016-01-01 2 2016-02-01 dtype: datetime64[ns]
has comment: http://stackoverflow.com/comment/89100289
has comment: http://stackoverflow.com/comment/89100370
has comment: http://stackoverflow.com/comment/89100045
upvote count: 1
has comment: http://stackoverflow.com/comment/89100343
score: 1
has comment: http://stackoverflow.com/comment/89099825
accepted answer of: http://stackoverflow.com/q/51054334
has comment: http://stackoverflow.com/comment/89099784

http://stackoverflow.com/comment/89278360
score: 2
comment on: http://stackoverflow.com/q/51147123
type: Comment
type: QuestionComment
has text: You should clarify "randomly generate" part.

http://stackoverflow.com/comment/89191891
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51102284
has text: I know my logic is missing and its still fails to reverse "abc(cba)ab(bac)c" and "The ((quick (brown) (fox) jumps over the lazy) dog)"

http://stackoverflow.com/q/51068354
type: Question
answer count: 2
upvote count: 1
favorite count: 0
has title: how to get the next line after if in python
has comment: http://stackoverflow.com/comment/89126618
tagged with: python
downvote count: 5
score: -4
possible better answer: http://stackoverflow.com/a/51069419
has answer: http://stackoverflow.com/a/51069148
accepted answer: http://stackoverflow.com/a/51069148
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51069419
has comment: http://stackoverflow.com/comment/89126734
has body: Hello I have a file like this: A. B. C. D. E. A. D. A. F. S. I'd like to print the lines immediately after A.
has comment: http://stackoverflow.com/comment/89127132

http://stackoverflow.com/comment/89291925
type: Comment
has text: I tried that since I am getting a json response through a API. but I am getting the same error as above
score: 0
comment on: http://stackoverflow.com/q/51153854
type: QuestionComment

http://stackoverflow.com/comment/96905708
comment on: http://stackoverflow.com/q/51018297
has text: I'm having the same problem. Did you manage to solve it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89195832
comment on: http://stackoverflow.com/a/51104220
score: 0
type: AnswerComment
type: Comment
has text: @dashiell I don't see the OP mentioning about that

http://stackoverflow.com/comment/89143980
type: Comment
has text: Nice solution, seems like I'm looking for!
type: AnswerComment
comment on: http://stackoverflow.com/a/51077613
score: 0

http://stackoverflow.com/a/51058992
answers question: http://stackoverflow.com/q/51058867
has comment: http://stackoverflow.com/comment/89111195
has comment: http://stackoverflow.com/comment/89109307
has comment: http://stackoverflow.com/comment/89111733
has comment: http://stackoverflow.com/comment/89111336
has comment: http://stackoverflow.com/comment/89111941
has body: You should set Selenium profile to enable downloading without asking: from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream') profile.set_preference("browser.safebrowsing.enabled", 'false') driver = webdriver.Firefox(profile) driver.get("http://yourpage.com") "application/octet-stream" is the file type, check MIME types if you don't know your file type With chrome you should be able to use: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option("prefs", { "download.default_directory": r"C:\Users\xxx\downloads\Test", # Insert the path where you want your files to be saved! "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True }) driver = webdriver.Chrome(chrome_options=chrome_options) Check also this answer for some more informations
score: 0
has comment: http://stackoverflow.com/comment/89111431
has comment: http://stackoverflow.com/comment/89112570
has comment: http://stackoverflow.com/comment/89110443
has comment: http://stackoverflow.com/comment/89112064
type: Answer

http://stackoverflow.com/comment/89181016
score: 0
type: Comment
type: QuestionComment
has text: Yes you are right, I am actually using that already but forgot to update the question. Thanks!
comment on: http://stackoverflow.com/q/51051902

http://stackoverflow.com/q/51128396
tagged with: database
tagged with: dataframe
tagged with: pandas
has body: I'm a beginner in coding and data in general so any help I can get would be really helpful. If I have a data frame as below,where every matchup is a tuple. df1 = Team A Player 1.1 Team A Player 2.1 Team A Player 3.1 ('Max', 'Hatteberg') ('Hatteberg', 'Tejada') ('Max', 'Rincon') ('Tejada', 'Brown') ('Hatteberg', 'Rincon') ('Hatteberg','Brown') and so on.. and I have a crosstable: df2 = Max Hatteberg Tejada Brown Rincon Max NaN -1.0 +2.0 -8.0 +5.0 Hatteberg +1.0 NaN +2.5 +3.0 0 Tejada -2.0 -2.5 NaN +5.5 -3.5 Brown +8.0 -3.0 -5.5 NaN +2.8 Rincon -5.0 0 +3.5 2.8 NaN And I wanted for each matchup to return a value as so df1 = matchups 1 matchups 2 matchups 3 +1.0 -2.5 -5.0 -5.5 0 -3.0 I've tried, df1.applymap(lambda x : df2.lookup([x[0]],[x[1]])[0]) But it returned, ('One or more row labels was not found', 'occurred at index Team A Player 1.1') I'm having issues referencing to both of the data frames and returning a value. Could someone help me out? Thanks in advance
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51128661
tagged with: data-science
favorite count: 0
has title: Linking 2 data frames and returning a value using lookup
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51045880
has answer: http://stackoverflow.com/a/51046146
has body: I have a list: listvalue = ['charity','hospital','carrefour'] I tried to concat two index from a list: twoconcat = [listvalue[i:i + 2] for i in range(len(listvalue))] The output I am getting is: [['charity', 'hospital'], ['hospital', 'carrefour'], ['carrefour']]` I want the output to be [['charity','hospital'],['charity','carrefour'],['hospital','charity'],['hospital','carrefour'],['carrefour','charity'],['carrefour','hospital']] Any suggestions?
type: Question
has answer: http://stackoverflow.com/a/51047682
accepted answer: http://stackoverflow.com/a/51046132
has title: python - how to concatenate two index from a list
has answer: http://stackoverflow.com/a/51046141
score: 0
possible better answer: http://stackoverflow.com/a/51046141
tagged with: python
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51046132
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/51121460
type: Question
has answer: http://stackoverflow.com/a/51121544
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51121544
tagged with: django
tagged with: python
has body: I am a beginner in DJango ORM and I want to make a queryset as follows This is the model that I have made: class Job(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) tags = models.CharField(max_length=255, choices=job_type) recruter_id = models.ForeignKey(User) def __str__(self): return self.title objects = JobManager() class StudentApplication(models.Model): job_fk = models.ForeignKey(Job) student_fk = models.ForeignKey(User) title = models.CharField(max_length = 255) def __str__(self): return self.title In this recruiter can list the job posting and data will be feed in Job Model, and student can apply to the job and that data will be feed in StudentApplication model, with student ID and Job ID as a foreign key.(I have a user model with user_type=1 for student and user_type=2 for recruiter) Now I want to make the query in which I want to show Recruiter the data, that which student have applied for which job posted by him. In the SQL, query will be: select * from StudentApplication as SA left join Job as j on j.id = sa.job_fk where j.recruiter_id = logged_in_user How can I do similar thing using ORM of DJango?
type: AnsweredQuestion
has title: DJango queryset filter with a foreign key of a different model
tagged with: orm

http://stackoverflow.com/q/51053219
has comment: http://stackoverflow.com/comment/89098819
has comment: http://stackoverflow.com/comment/89100598
downvote count: 1
type: Question
tagged with: numpy-ndarray
upvote count: 0
answer count: 1
score: -1
has answer: http://stackoverflow.com/a/51054280
tagged with: python-2.7
has body: I have data like the sample below. It's very large and I would like to sample first 10 items from it. It looks like a list of dicts, but if I try user_train[:5] I get an error. I can sample one item at a time like user_train[4] works. Any tips are greatly appreciated. code: user_train[0] output: [{u'asin': u'B00APT3MHO', u'helpful': [0, 0], u'overall': 5.0, 'productid': 1, u'reviewText': u"Good for someone who likes skinny jeans but doesn't look great in the legging-tight ones. A little stretchy. Not super tight in the knee or ankle, but snug on the thigh and calf.", u'reviewTime': u'11 17, 2013', u'reviewerID': u'A1JWX45KHE34AL', u'reviewerName': u'varnienarsil', u'summary': u'Love these jeans', u'unixReviewTime': 1384646400}, {u'asin': u'B00CJ5NH36', u'helpful': [0, 0], u'overall': 5.0, 'productid': 2, u'reviewText': u"This shirt with it's bold graphic is seriously adorable. I have pretty narrow shoulders, and like the way the sleeves slope off them. The shirt fits loosely in a way that is flattering and I liked the length. I'm no model, but the shirt looks on me as great as it looks in the photo.", u'reviewTime': u'11 17, 2013', u'reviewerID': u'A1JWX45KHE34AL', u'reviewerName': u'varnienarsil', u'summary': u'As cute as it looks', u'unixReviewTime': 1384646400}, {u'asin': u'B00F9NGAPM', u'helpful': [1, 1], u'overall': 3.0, 'productid': 4, u'reviewText': u"The shirt is a little flowy-er than I expected. I like the way it drapes, but the arms are a bit loose (and on me, short&amp;#8212;I'm pretty tall). Has a sort of after-yoga feel rather than the urban feel I was looking for. Super comfortable.", u'reviewTime': u'11 17, 2013', u'reviewerID': u'A1JWX45KHE34AL', u'reviewerName': u'varnienarsil', u'summary': u"Like, don't love", u'unixReviewTime': 1384646400}] Update: code: user_train[:5] error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-17-bb27c2e9fa75&gt; in &lt;module&g…
has comment: http://stackoverflow.com/comment/89097682
favorite count: 0
has title: sampling from list of dicts
accepted answer: http://stackoverflow.com/a/51054280
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51114987
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89216311
has comment: http://stackoverflow.com/comment/89216427
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/51115141
has answer: http://stackoverflow.com/a/51115141
tagged with: ironpython
has title: Search in a list for characters
accepted answer: http://stackoverflow.com/a/51115124
type: Question
has answer: http://stackoverflow.com/a/51115124
upvote count: 2
score: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/51115125
has body: I have done a large amount of searching but cannot find what I am after. I am using Iron Python. I have a large list of strings (MyList) that I have extracted and I would like to see if there are values that contain the Items in the SearchStrings Dictionary. The searchStrings Dictionary could have over 500 items within. MyList = ["123steel","MylistConcrete","Nothinginhere","45","56","steel","CONCRETE"] SearchStrings = {'concrete' : 'C','CONCRETE' : 'C','Steel' : 'S', 'STEEL' : 'S'} I need to return the index and then matching code from the SearchString. i.e If we find 'MylistConcrete' i will know the index '1' and can return 'C' I hope this makes sense to everyone. Let me know if you need any clarification Thanks in Advance, Geoff.
has comment: http://stackoverflow.com/comment/89216350
favorite count: 0
has comment: http://stackoverflow.com/comment/89216374
tagged with: python

http://stackoverflow.com/q/51105860
has comment: http://stackoverflow.com/comment/89199206
score: 1
has comment: http://stackoverflow.com/comment/89199029
has comment: http://stackoverflow.com/comment/89208217
type: Question
has comment: http://stackoverflow.com/comment/89204036
has comment: http://stackoverflow.com/comment/89199003
tagged with: amazon-web-services
upvote count: 1
favorite count: 0
tagged with: aws-lambda
type: UnansweredQuestion
tagged with: python
has title: AWS Lambda function unable to use os.system
has comment: http://stackoverflow.com/comment/128731117
has body: Im not sure if its a permission issue but I can't get anything to run with os.system. Here is a basic test I have for my Lambda function - import os def test(event, context): print(os.system('ls')) Am I doing something wrong? Update What Im ultimately trying to do is do a pg_dump of one of my databases to a /tmp folder, then save that file in S3, then delete the file in the lambda directory. Here are the logs Im receiving from the test above -
answer count: 0
downvote count: 0

http://stackoverflow.com/a/51042577
answers question: http://stackoverflow.com/q/51024301
has body: In case, columns to be selected (like P1, P2, and P3) are larger in number than those not to be selected, then writing the above would be a multi-line task (for hundreds of columns to be selected and almost negligible number of columns that are not to be selected). The right approach would be: Number of(columns to be selected) >> Number of(columns to be unselected) s = df1.loc[~df1['Data'].isin(['Total','P4']),['Quantity','Price']].sum() print (s) Using the following code, appends a row named as 'Total' to the end of dataframe df1.loc['Total_without_P4'] = pd.Series(df1.loc[~df1['Data'].isin(['Total','P4']),['Quantity','Price']].sum() , index=['Quantity','Price']) Output would be: Data Quantity Price 0 P1 1 5 1 P2 1 7 2 P3 2 3 3 P4 1 3 4 Total 5 18 Total_without_P4 4 15
score: 0
type: Answer

http://stackoverflow.com/q/51070784
has title: How to increment at different intervals python?
answer count: 5
has comment: http://stackoverflow.com/comment/89131455
tagged with: python
tagged with: ip-address
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/51071968
upvote count: 2
has comment: http://stackoverflow.com/comment/89131411
has answer: http://stackoverflow.com/a/51070998
has body: Say I had an IP address 192.168.1.1 How would I increment at different intervals like this? 192.168.1.2 192.168.1.3 ... and all the way to 192.168.1.999 then "roll over" to 192.168.2.1 ?
type: Question
has comment: http://stackoverflow.com/comment/89131505
has answer: http://stackoverflow.com/a/51070843
accepted answer: http://stackoverflow.com/a/51070843
has answer: http://stackoverflow.com/a/51070888
has answer: http://stackoverflow.com/a/51071968
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51070870
has comment: http://stackoverflow.com/comment/89131432

http://stackoverflow.com/a/51072652
has comment: http://stackoverflow.com/comment/89163085
accepted answer of: http://stackoverflow.com/q/51068361
type: AcceptedAnswer
has body: I got this format the floats to 1 decimal place. data = {'A Prime': {0: 3.26, 1: 3.24, 2: 3.22, 3: 3.2, 4: 3.18, 5: 3.16, 6: 3.14, 7: 1.52, 8: 1.5, 9: 1.48, 10: 1.46, 11: 1.44, 12: 1.42}, 'B': {0: 0.16608, 1: 0.16575, 2: 0.1654, 3: 0.16505999999999998, 4: 0.1647, 5: 0.16434, 6: 0.16398, 7: 0.10759, 8: 0.10687, 9: 0.10614000000000001, 10: 0.10540999999999999, 11: 0.10469, 12: 0.10396}, 'Proto Name': {0: 'Alpha', 1: 'Alpha', 2: 'Alpha', 3: 'Alpha', 4: 'Alpha', 5: 'Alpha', 6: 'Alpha', 7: 'Bravo', 8: 'Bravo', 9: 'Bravo', 10: 'Bravo', 11: 'Bravo', 12: 'Bravo'}} import pandas as pd df = pd.DataFrame(data) A Prime B Proto Name 0 3.26 0.16608 Alpha 1 3.24 0.16575 Alpha 2 3.22 0.16540 Alpha 3 3.20 0.16506 Alpha 4 3.18 0.16470 Alpha 5 3.16 0.16434 Alpha 6 3.14 0.16398 Alpha 7 1.52 0.10759 Bravo 8 1.50 0.10687 Bravo 9 1.48 0.10614 Bravo 10 1.46 0.10541 Bravo 11 1.44 0.10469 Bravo 12 1.42 0.10396 Bravo writer = pd.ExcelWriter(r'c:\temp\output.xlsx') # This method will truncate the data past the first decimal point df.to_excel(writer,'Sheet1',float_format = "%0.1f") writer.save() but that alas is not perhaps all cases - no joy with say larger numbers and thousands separator df.to_excel(writer,'Sheet1',float_format = ":,") However the following seems to work data = {'A Prime': {0: 326000, 1: 3240000}} df = pd.DataFrame(data) A Prime 0 326000 1 3240000 writer = pd.ExcelWriter(r'c:\temp\output.xlsx') df.to_excel(writer,'Sheet1') workbook = writer.book worksheet = writer.sheets['Sheet1'] format1 = workbook.add_format({'num_format': '#,##0.00'}) worksheet.set_column('B:B', 18, format1) #Alternatively, you could specify a range of columns with 'B:D' and 18 sets the column width writer.close() All taken from here: http://xlsxwriter.readthedocs.io/working_with_pandas.html
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89162668
upvote count: 14
answers question: http://stackoverflow.com/q/51068361
score: 14

http://stackoverflow.com/a/51067737
downvote count: 0
has body: Use zip: temperature_list = [[-10,0,10,20,30,40,50,60,70,80,90,100], [-23.33,-17.78,-12.22,-6.67,-1.11,4.44,10,15.56,21.11,26.67,32.22,37.78]] for f, t in zip(temperature_list[0], temperature_list[1]): print('Farenheit: {}, Celsius: {}'.format(f, t))
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51067654

http://stackoverflow.com/comment/89214378
score: 0
type: Comment
type: QuestionComment
has text: Done. Thanks for your response.
comment on: http://stackoverflow.com/q/51113895

http://stackoverflow.com/q/51054183
score: 6
has answer: http://stackoverflow.com/a/51077531
linked to: http://stackoverflow.com/q/11205254
answer count: 3
duplicate of: http://stackoverflow.com/q/11205254
has body: This is a question out of curiosity rather than trying to use it for a practical purpose. Consider I have the following simple example where I generate a list through list comprehension: &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = [2 * i for i in a] &gt;&gt;&gt; b [2, 4, 6] &gt;&gt;&gt; b.append(a) &gt;&gt;&gt; b [2, 4, 6, [1, 2, 3]] However if I try and do this all in one action &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = [2 * i for i in a].append(a) &gt;&gt;&gt; b == None True The result returns None. Is there any reason why this is the case? I would have thought that an action like this would either return an answer like in the first example or throw an error. For reference I'm using Python 3.6.5
favorite count: 0
has comment: http://stackoverflow.com/comment/89099222
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51054200
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51054273
upvote count: 7
downvote count: 1
has answer: http://stackoverflow.com/a/51054273
type: Question
has comment: http://stackoverflow.com/comment/89099247
has title: Appending to a list comprehension in Python returns None
accepted answer: http://stackoverflow.com/a/51054200
tagged with: list-comprehension

http://stackoverflow.com/comment/89280750
score: 0
type: Comment
has text: @jezrael I have already run for ```pd.unique``` check the **edit1**. set is actually better.
comment on: http://stackoverflow.com/a/51138044
type: AnswerComment

http://stackoverflow.com/q/51097173
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89182053
has body: An Excel spreadsheet like below (note: ID the column A has duplicated values). I want to find out sum of each Contract_type, taking each ID is counted once only (unique). data = {'ID': ["380689","380689","480562","480562","480562","14805","47089","56251","56251","56251","322624","322624","322624","85964","85964","85964","342225","342225","4589","23591","23591","235225"], 'Contract_type' : ["Other","Other","Type-I","Type-I","Type-I","Type-II","Type-II","Type-II","Type-II","Type-II","Type-II","Type-II","Type-II","Type-III","Type-III","Type-III","Part-time","Part-time","Part-time","Full-time","Full-time","Full-time"], 'Unit_Weight': [335,335,119,119,119,119,52,452,452,452,19,19,19,165,165,165,165,165,165,724,724,16], 'Test_time' : ["16:26","07:39","18:48","22:32","03:54","03:30","09:57","18:52","19:03","18:06","18:52","03:51","04:00","22:02","13:35","13:43","10:29","06:30","12:20","12:52","17:30","13:10"], 'Tested' : [1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0], 'Internal' : [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1]} df = pd.DataFrame(data) I tried: print pd.pivot_table(df, index = ["Contract_type", "ID"]).Unit_Weight It gives: Contract_type ID Full-time 23591 724 235225 16 Other 380689 335 .... But I only want it to show something like: Full-time 740 etc. I also tried: print pd.pivot_table(df, index = ["Contract_type"], values=["Unit_Weight"], aggfunc = np.sum) It gives: Full-time 1464 # this is not considering the duplicated IDs What's the right way to right the line? Thank you.
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89182268
has answer: http://stackoverflow.com/a/51097402
has comment: http://stackoverflow.com/comment/89182327
tagged with: python
possible better answer: http://stackoverflow.com/a/51097276
accepted answer: http://stackoverflow.com/a/51097402
has comment: http://stackoverflow.com/comment/89182205
has answer: http://stackoverflow.com/a/51097276
has comment: http://stackoverflow.com/comment/89181949
upvote count: 1
has title: Python, Pandas, sum only taking uniques
has comment: http://stackoverflow.com/comment/89181942

http://stackoverflow.com/q/51031680
duplicate of: http://stackoverflow.com/q/38481409
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89055851
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51031794
tagged with: python
has body: There seems to be a logical error. When I run the code, the last column is not removed. Any help is appreciated A = [['Roy', 80, 75, 85, 90, 95, 0], ['John', 75, 80, 75, 85, 100, 0], ['Dave', 80, 80, 80, 90, 95, 0]] A = pd.DataFrame(A) Here I do some operations to identify # Remove columns that meet a certain criteria. # This statement does not seem to be working because # at the end I get the same matrix without removing any column A.drop(A.columns[i], axis=1)
score: 3
has answer: http://stackoverflow.com/a/51031799
has title: Trouble with deleting a column in a dataframe based on the index of the column
upvote count: 3
linked to: http://stackoverflow.com/q/38481409
type: Question

http://stackoverflow.com/comment/89192008
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51102237
has text: Should just be a file with the name of the survey underscore final. But can't figure out how to get to that point.

http://stackoverflow.com/q/51085101
score: 0
accepted answer: http://stackoverflow.com/a/51085575
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/89158626
has comment: http://stackoverflow.com/comment/89159585
has comment: http://stackoverflow.com/comment/89159104
answer count: 1
has comment: http://stackoverflow.com/comment/89159239
has body: I come from a Rails background, and am new to Python. Unfortunately, my googling and searching SO has been unsuccessful. We are building a Python app with no framework. We're using pytest for testing, and factory-boy for factories. I'm wondering if we need a database cleaner for our app. I have found the pytest_sessionstart and pytest_sessionfinish hooks, which would seem like a good place to do the cleaning. But I can't figure out if we even need such a thing as a database cleaner like we use in Rails testing. Any information or assistance is greatly appreciated! If I do need some sort of cleaner, explicit instructions or links to docs would be very useful.
has answer: http://stackoverflow.com/a/51085575
tagged with: python
has title: Do I need a database cleaner in Python?
type: AnsweredQuestion
tagged with: pytest

http://stackoverflow.com/a/51162029
answers question: http://stackoverflow.com/q/51161705
type: Answer
accepted answer of: http://stackoverflow.com/q/51161705
has comment: http://stackoverflow.com/comment/89311610
has comment: http://stackoverflow.com/comment/89311402
has comment: http://stackoverflow.com/comment/89311361
has comment: http://stackoverflow.com/comment/89312142
has comment: http://stackoverflow.com/comment/89311548
has comment: http://stackoverflow.com/comment/89311598
has body: This usually happens when you have multiple versions of python are installed with different paths in your computer. You try import sys sys.version sys.path on both CMD and IDLE and see they are matching.(They probably aren't) And you can choose which version you like to keep and remove the other. Or you can remove both versions and perform a clean installation and all the modules using pip.
has comment: http://stackoverflow.com/comment/89311515
has comment: http://stackoverflow.com/comment/89311706
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89311593

apache-spark-sql
tags question: http://stackoverflow.com/q/51084621
tags question: http://stackoverflow.com/q/51129312
tags question: http://stackoverflow.com/q/51158135
tags question: http://stackoverflow.com/q/51077948
tags question: http://stackoverflow.com/q/51078195
tags question: http://stackoverflow.com/q/51159672
tags question: http://stackoverflow.com/q/51145204
tags question: http://stackoverflow.com/q/51091931
tags question: http://stackoverflow.com/q/51072816
tags question: http://stackoverflow.com/q/51019490
tags question: http://stackoverflow.com/q/51053179
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/51034680
tags question: http://stackoverflow.com/q/51070251
tags question: http://stackoverflow.com/q/51130711
type: Tag
tags question: http://stackoverflow.com/q/51024285
tags question: http://stackoverflow.com/q/51082758

http://stackoverflow.com/a/51074226
has comment: http://stackoverflow.com/comment/89155696
downvote count: 0
answers question: http://stackoverflow.com/q/51071020
type: Answer
score: 1
upvote count: 1
has body: Regarding the tcp46 output from netstat, I can't find any documentation but I did find the relevant source. From network_cmds-543/netstat.proj/inet.c: void protopr(uint32_t proto, /* for sysctl version we pass proto # */ char *name, int af) { ... struct xinpcb_n *inp = NULL; ... const char *vchar; #ifdef INET6 if ((inp-&gt;inp_vflag &amp; INP_IPV6) != 0) vchar = ((inp-&gt;inp_vflag &amp; INP_IPV4) != 0) ? "46" : "6 "; else #endif vchar = ((inp-&gt;inp_vflag &amp; INP_IPV4) != 0) ? "4 " : " "; xinpcb_n is defined in bsd/netinet/in_pcb.h. * struct inpcb captures the network layer state for TCP, UDP and raw IPv6 * and IPv6 sockets. Elsewhere in that file, the inp_vflag is documented as /* INP_IPV4 or INP_IPV6 */. Those are in turn defined as: #define INP_IPV4 0x1 #define INP_IPV6 0x2 So basically, when a socket has both v4 and v6 bits set, it will display 46 in the protocol column. Regarding Go, there's this socket() function in the net package: func socket(ctx context.Context, net string, family, sotype, proto int, ipv6only bool, laddr, raddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) (fd *netFD, err error) { ... if err = setDefaultSockopts(s, family, sotype, ipv6only); err != nil { setDefaultSockopts() has per platform definitions, here's an excerpt from the BSD variant: func setDefaultSockopts(s, family, sotype int, ipv6only bool) error { ... if supportsIPv4map() &amp;&amp; family == syscall.AF_INET6 &amp;&amp; sotype != syscall.SOCK_RAW { // Allow both IP versions even if the OS default // is otherwise. Note that some operating systems // never admit this option. syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only)) So, allowing of both IP versions on a socket is driven by the ipv6Only boolean. After a little more digging, I found where this is decided and includes a detailed explanation of the logic: // favoriteAddrFamily returns the appropriate address family for the // given network, laddr, raddr and mode. // /…

http://stackoverflow.com/q/51111992
answer count: 4
type: AnsweredQuestion
has body: I need to extract the first number from a string, but I don't know the exact format of the number. The number could be one of the following formats...1.224 some decimal... 3,455,000 some number with unknown number of commas... 45% a percentage ... or just an integer 5 it would be something like blah blah $ 2,400 or blah blah 45% or blah blah $1.23 or blah blah 7 would be interesting if it was intelligent enough to do word numbers too like blah blah seven I don't need the dollar sign, just the number
accepted answer: http://stackoverflow.com/a/51112201
upvote count: 1
has answer: http://stackoverflow.com/a/51112209
has comment: http://stackoverflow.com/comment/89210835
downvote count: 1
type: Question
has title: python regex: extracting number from string, unknown number format
has answer: http://stackoverflow.com/a/51112198
score: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51112200
has answer: http://stackoverflow.com/a/51112200
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51112201

http://stackoverflow.com/comment/89249390
score: 0
type: QuestionComment
type: Comment
has text: There's "wsgi.load" (see above) and "wsgi.conf" (all the lines are commented)
comment on: http://stackoverflow.com/q/51132010

http://stackoverflow.com/comment/89262281
type: QuestionComment
comment on: http://stackoverflow.com/q/51138832
score: 0
has text: @UnholySheep, that is exactly what it was changed to. I understand why it was printing and returning none. This is all a learning experience for me, and I really, really appreciate your input! Have a great day.
type: Comment

function-parameter
type: Tag
tag name: function-parameter
tags question: http://stackoverflow.com/q/51061685

http://stackoverflow.com/a/69986809
has body: Just to pile on: ls has an overhead limit to the number of files in the directory you are trying to use it on. os.listdir() suffers no such limitation. If you can use it, then os.listdir() seems to be the superior choice.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51163112

http://stackoverflow.com/q/51018233
tagged with: python
has answer: http://stackoverflow.com/a/51023181
linked to: http://stackoverflow.com/q/51015563
downvote count: 0
has answer: http://stackoverflow.com/a/51018721
type: UnansweredQuestion
tagged with: tensorflow
type: Question
score: 1
has body: I have a 2D tensor having K*N dimension in TensorFlow, For each row vector in the tensor, having N dimension, I can calculate the square of pairwise difference using the approach in How to construct square of pairwise difference from a vector in tensorflow? However, I need to average the results of the K row vectors: performing each vector's square of pairwise difference and averaging the results. How can I do? Need your help, many thanks!!!
has comment: http://stackoverflow.com/comment/89029480
tagged with: numpy
answer count: 2
upvote count: 1
favorite count: 0
has title: How to construct square of pairwise difference for each row vector in a matrix in tensorflow?
tagged with: matrix

http://stackoverflow.com/q/51166020
downvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/6020532
has comment: http://stackoverflow.com/comment/89315322
tagged with: function
has title: How function inside function work in python
has comment: http://stackoverflow.com/comment/89315291
duplicate of: http://stackoverflow.com/q/6020532
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/51166091
upvote count: 0
favorite count: 0
type: Question
has body: I'm a new python learner and start with some exercises of string. And i'm wondering how 'replace' function in 'matchcase' actually work. import re a = 'UPPER PYTHON, lower python, Mixed Python' def matchcase(word): def replace(m): text = m.group() if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace print (matchcase('conran')) print (re.sub('python',matchcase('conran'),a , flags=re.IGNORECASE)) the output: UPPER CONRAN, lower conran, Mixed Conran
tagged with: python
has comment: http://stackoverflow.com/comment/89315538

http://stackoverflow.com/comment/89256138
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51135798
has text: @Mani In python, it is better to use `if result.option` instead of `if result.option == True:` as you can find at https://www.python.org/dev/peps/pep-0008 `Don't compare boolean values to True or False using ==`

http://stackoverflow.com/q/51072884
has title: Pygame mouse click and rect intersection
type: Question
has body: I am designing a survival based game, and I am having trouble allowing the player to collect wood from trees. The function below checks if my mouse is pressed, and if the player has collided with any tree rects, their wood count increases by one. I use the ticks to make sure that only one wood gets added every nine ticks. def check(self): global tick if pygame.mouse.get_pressed()[0]: for tree in resources: tree_rect=tree.rect if self.rect.colliderect(tree_rect) and tick&gt;=9: self.inventory['wood']+=1 tick=0 However, whenever I click, wood is sometimes added and sometimes not, regardless of whether my player class has collided with any trees. I tried using pygame.sprite.spritecollide(), but the result was the same. Any help is appreciated. Full code: import pygame from pygame.locals import * import sys import math import pygame.gfxdraw import random pygame.init() black=(0,0,0) white=(255,255,255) forest=(34,139,34) red=(255,0,0) blue=(0,0,255) green=(0,255,0) light_green=(0,120,0) dark_green=(0,90,0) skin=(255,224,189) yellow=(255,255,0) wood_image=pygame.image.load('./assets/images/wood.png') stone_image=pygame.image.load('./assets/images/stone.png') player_image=pygame.image.load('./assets/images/player.png') tick=0 def terminate(): pygame.quit() sys.exit() def drawTextcenter(text,font,screen,x,y,color): textobj=font.render(text,True,color) textrect=textobj.get_rect(center=(x,y)) screen.blit(textobj,textrect) def drawText(text, font, surface, x, y,color): textobj=font.render(text, 1, color) textrect=textobj.get_rect() textrect.topleft=(x, y) surface.blit(textobj, textrect) class Button(object): global screen_width,screen_height,screen def __init__(self,x,y,width,height,text_color,background_color,text): self.rect=pygame.Rect(x,y,width,height) self.x=x self.y=y self.width=width self.height=height self.text=text self.text_color=text_color self.background_color=background_color self.angle=0 def check(self): return self.rect.collidepoint(pygame.mouse.get_pos()) def d…
upvote count: 2
has answer: http://stackoverflow.com/a/51074501
accepted answer: http://stackoverflow.com/a/51074501
answer count: 1
tagged with: pygame
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/comment/89331892
comment on: http://stackoverflow.com/q/51133767
type: Comment
type: QuestionComment
has text: @phd turns out upgrading Python solved it, so it *is* a duplicate. But I can't seem to be able to close the question, is it possible? If not, just post "upgrade python" as an answer and I will accept it.
score: 0

http://stackoverflow.com/q/51153116
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89291073
has title: Object of type 'Decimal' is not JSON serializable Error when use request inherited object
linked to: http://stackoverflow.com/q/1960516
tagged with: python
answer count: 0
has body: I have a strange problem with creation of shopping cart I in Django 2.0. Sopping cart is and object inherited from request and stored in session: class Cart(object): def __init__(self, request, shop_u_id): self.session_key = str(settings.CART_SESSION_ID) self.session = request.session cart = self.session.get(self.session_key) if not cart: cart = self.session[self.session_key] = {} self.cart = cart I have no problem with set and get methods, but strange problem appeared in total sum function: def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) I got an error: Object of type 'Decimal' is not JSON serializable But get_total_price nothing stores in session, it just for representation. (item['price'] stored as string)
tagged with: django
upvote count: 1
type: Question
score: 1
tagged with: session
has comment: http://stackoverflow.com/comment/89293907
downvote count: 0
has comment: http://stackoverflow.com/comment/89289832
favorite count: 0
has comment: http://stackoverflow.com/comment/89290387

http://stackoverflow.com/comment/89127745
has text: i got the answer now but what im trying to do is make a script which will compile another script(which works) but then deletes the script it used to compile, basicly i have a script which compiles another script using cython but then because cython doesnt remove the non comiled script im removing it afterwards, but as the other users are running copies of the compiling scripts the directory will not be the same
score: 0
comment on: http://stackoverflow.com/q/51068738
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89189921
has text: @DrutaRuslan this comment, without any explanation, is not useful at all.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51101290

http://stackoverflow.com/comment/89250052
comment on: http://stackoverflow.com/a/51123015
type: Comment
has text: **note:** if you using ngrok.io you don't need use the cert in your bot. ngrok will get all requests with `https` and redirect to app port.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51148129
has comment: http://stackoverflow.com/comment/89281579
has comment: http://stackoverflow.com/comment/89280279
linked to: http://stackoverflow.com/q/8884335
type: Question
has comment: http://stackoverflow.com/comment/89280594
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/89280407
has title: Identify C functions (opening and closing braces) in a file
upvote count: 2
has comment: http://stackoverflow.com/comment/89280324
has comment: http://stackoverflow.com/comment/89280417
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/13781941
has comment: http://stackoverflow.com/comment/89280356
favorite count: 0
has comment: http://stackoverflow.com/comment/89280474
has answer: http://stackoverflow.com/a/51148212
tagged with: python
has body: I have a C file in which I would like to add a print at the beginning and end of each function that includes file name, function name and line number. I am trying to automate this for an entire folder of C files using python. Example: For function add in math.c file int add(int a, int b){ sum = a +b; return sum; } I would want the result file to look something like this: int add(int a, int b){ printf("Math.c, add, 12"); sum = a +b; return sum; } I am looking at the regex as suggested in this link Using Python Regex to Find C function in File Any other suggestions? Ctags is the other option I am exploring, but I prefer using python libraries if any for this purpose. Edit: Running the code on a microcontroller Not using Linux Debugger with limited capabilities (can get printf only)
has comment: http://stackoverflow.com/comment/89281361
score: 2
has comment: http://stackoverflow.com/comment/89281625
has comment: http://stackoverflow.com/comment/89280499
has comment: http://stackoverflow.com/comment/89280281
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/89603

http://stackoverflow.com/comment/89101004
has text: when `i=0, k=1` ; when `i = last element, k =last element +1` , so k is out of range. just do a minus 1 from your iterator `range(len(newS) - 1)` . assuming everything else is correct, should work fine
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51055063

http://stackoverflow.com/a/51210241
has body: I did it finally. def mysql_aes_decrypt(val, key): def mysql_aes_key(key): final_key = bytearray(16) for i, c in enumerate(key): final_key[i % 16] ^= ord(key[i]) return bytes(final_key) k = mysql_aes_key(key) cipher = AES.new(k, AES.MODE_ECB) return cipher.decrypt(val).decode()
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51134744
has comment: http://stackoverflow.com/comment/125917143
score: 5
answers question: http://stackoverflow.com/q/51134744
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/111597193

http://stackoverflow.com/comment/89029239
comment on: http://stackoverflow.com/q/51016220
type: Comment
type: QuestionComment
has text: You are correct, conv2D is the right place for the regularization. You can also think about adding dropout.
score: 1

tkinter-canvas
tags question: http://stackoverflow.com/q/51118695
tags question: http://stackoverflow.com/q/51086108
type: Tag
tags question: http://stackoverflow.com/q/51037616
tags question: http://stackoverflow.com/q/51143523
tags question: http://stackoverflow.com/q/51044836
tags question: http://stackoverflow.com/q/51048950
tag name: tkinter-canvas
tags question: http://stackoverflow.com/q/51117798
tags question: http://stackoverflow.com/q/51070261

http://stackoverflow.com/comment/89085851
has text: No, it is not closer to the solution I wish. So, is there any way to update list_of_points dynamically, and redraw the polygon by deleting the old one.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51046784
type: Comment

http://stackoverflow.com/comment/89174122
comment on: http://stackoverflow.com/q/51092894
score: 0
type: Comment
type: QuestionComment
has text: Can you provide the full stack trace?

http://stackoverflow.com/comment/89261068
comment on: http://stackoverflow.com/a/51095509
score: 0
type: AnswerComment
type: Comment
has text: @harm I'm not sure I'm following you 100%, but if `stop` calls `disconnect`, then it should await it. If it failed to do so, you would observe the effect of `disconnect` never being called.

http://stackoverflow.com/comment/89384338
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51201478
type: AnswerComment
has text: That sounds great. Can I give it to keras.train or tf.train methods and the data gets parsed accordingly? Sorry if this question is not clear, please ask if you need any clarifications.

http://stackoverflow.com/q/51107368
tagged with: python
tagged with: pypdf
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92385006
has comment: http://stackoverflow.com/comment/92280057
score: 2
has comment: http://stackoverflow.com/comment/136634720
has comment: http://stackoverflow.com/comment/92281619
has title: Add text in the content pages of the pdf using PyPDF2
linked to: http://stackoverflow.com/q/52499339
type: Question
has comment: http://stackoverflow.com/comment/136618730
has body: I am trying to add page number in the lower side of the page using pypdf2. I am able to add the relevant texts and syntax using the below code: def addText(page, text, position, ignoreByteStringObject=False, debug=False): """ Add user given text to a page content :page is the page on which text has to be added :text is the text string :position is the place where it has to be added, examples "top-right", "top-left", "bottom-right", "bottom-left", "bottom-center", "top-center" :param bool ignoreByteStringObject: optional parameter to ignore ByteString Objects. """ pageRef = page content = pageRef['/Contents'].getObject() print content # if not isinstance(content, ContentStream()): content = ContentStream(content, pageRef)#creating contentstream class instance if debug: print content.operations # append this line ([], 'BT'), ([1, 0, 0, 1, 52, 34.5], 'Tm'), (['/F1', 9], 'Tf'), ([0, 0, 0], 'rg'), ([u'Study: Classified #1'], 'Tj'), ([0], 'g'), ([], 'ET'), ([], 'BT'), # ([1, 0, 0, 1, 336.1, 34.5], 'Tm'), (['/F1', 9], 'Tf'), ([0, 0, 0], 'rg'), ([u'This document is Classified.'], 'Tj'), # ([0], 'g'), ([], 'ET'), ([], 'BT'), ([1, 0, 0, 1, 633.34, 34.5], 'Tm'), (['/F1', 9], 'Tf'), ([0, 0, 0], 'rg'), ([TextStringObject(text)], 'Tj'), ([0], 'g'), ([], 'ET') if position == "bottom-center": if not ignoreByteStringObject: operands = ArrayObject([]) operator = NameObject("BT") content.operations.append((operands, operator)) operands = ArrayObject([1, 0, 0, 1, 52, 34.5]) operator = NameObject("Tm") content.operations.append((operands, operator)) operands = ArrayObject(['/F1', 9]) operator = NameObject("Tf") content.operations.append((operands, operator)) operands = ArrayObject([0, 0, 0]) operator = NameObject("rg") content.operations.append((operands, operator)) operands = ArrayObject([TextStringObject('Study: Classified #1')]) operator = NameObject("Tj") content.operations.append((operands, operator)) operands = ArrayObject([0]) operator = NameObject("g") content.operations.append(…
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/78973467
tagged with: python-2.7
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/a/51065690
accepted answer of: http://stackoverflow.com/q/51063249
has body: As I don't have any info on ORM hence I am assuming Orm has the exact number of columns as the table has. results_10 = session.query(Disease_Data).all() # This will return the list of Disease_Data objects json_list= [] for result in results_10: temp_dict = result.__dict__ temp_dict.pop('_sa_instance_state',None) json_list.append(temp_dict) # OR # temp_dict = dict(result) # temp_dict.pop('_sa_instance_state',None) # removing unwanted key # json_list.append(dict(result)) #Either of two should work json2010 = json.dumps(json_list) return jsonify(results_10) I could not test it on my local but should give an idea. In case you want to keep the format of the data: column_list = Disease_Data.__table__.columns.keys() results_10 = session.query(Disease_Data).all() # This will return the list of Disease_Data objects json_list= [] for result in results_10: temp_dict={} for col in column_list: temp_dict[col] = getattr(result,col) json_list.append(temp_dict) json2010 = json.dumps(json_list) return jsonify(results_10)
upvote count: 1
answers question: http://stackoverflow.com/q/51063249
has comment: http://stackoverflow.com/comment/89122522
has comment: http://stackoverflow.com/comment/89127134
has comment: http://stackoverflow.com/comment/89124310
has comment: http://stackoverflow.com/comment/89122151
has comment: http://stackoverflow.com/comment/89123385
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89122606
type: Answer
has comment: http://stackoverflow.com/comment/89122556
score: 1
has comment: http://stackoverflow.com/comment/89125639
has comment: http://stackoverflow.com/comment/89125118

http://stackoverflow.com/q/51062866
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51914835
type: Question
tagged with: interactive
has answer: http://stackoverflow.com/a/51914835
tagged with: python-2.7
tagged with: visualization
has title: Interactive visualization interface using Python
answer count: 1
downvote count: 0
has body: I created a tower of Hanoi code using python. Now, I want to visualize the steps after running the code. For example, when my code prints 'Move from A to C', one disc will move from Stack A to Stack C. Then next maybe B to C. I want to visualize the steps using some python code. I know it can be done using R shiny, but I have to do it using python only. Does anyone have any idea what are the possible options for this.
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51155235
type: Answer
has comment: http://stackoverflow.com/comment/89293978
score: 2
has comment: http://stackoverflow.com/comment/89294004
downvote count: 0
has comment: http://stackoverflow.com/comment/89294301
has comment: http://stackoverflow.com/comment/89294793
answers question: http://stackoverflow.com/q/51155172
has body: This is one approach. Demo: from string import ascii_lowercase d = {v: i for i,v in enumerate(ascii_lowercase, 1)} Name = "abc" print( sum(d[i] for i in Name) ) Output: 6
has comment: http://stackoverflow.com/comment/89293715
upvote count: 2
has comment: http://stackoverflow.com/comment/89293779
has comment: http://stackoverflow.com/comment/89294100
has comment: http://stackoverflow.com/comment/89294051

http://stackoverflow.com/comment/89165072
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51088119
has text: You're result can be achieved with `df.groupby('cluster').cumcount().add(1)`
score: 1

http://stackoverflow.com/comment/89160838
comment on: http://stackoverflow.com/q/51085919
has text: Using Pandas 0.23.1. Sorry if this is an issue that has already been reported!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51101834
answer count: 8
has body: I'm trying to condense my code by putting my conditional statement onto one line. def get_middle(s): if len(s)%2 == 1: return(s[int(len(s)/2)]) else: return(s[int(len(s)/2)-1] + s[int(len(s)/2)]) This works just fine. I tried to do it this way: return(s[int(len(s)/2)]) if len(s)%2 == 1 else return(s[int(len(s)/2)-1] + s[int(len(s)/2)]) but I'm met with a syntax error at the end of that line. Error: Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; from solution import * File "/home/codewarrior/solution.py", line 5 return(s[int(len(s)/2)]) if (len(s)%2 == 1) else (return(s[int(len(s)/2)-1] + s[int(len(s)/2)])) ^ SyntaxError: invalid syntax Also: This is mainly just because I'm curious. I understand in a real-world application this code would be too hard to interpret.
tagged with: python
has comment: http://stackoverflow.com/comment/89206593
has answer: http://stackoverflow.com/a/51101969
has answer: http://stackoverflow.com/a/51101942
tagged with: syntax
has answer: http://stackoverflow.com/a/51102120
has comment: http://stackoverflow.com/comment/89190908
has answer: http://stackoverflow.com/a/51101986
has comment: http://stackoverflow.com/comment/89190999
downvote count: 1
tagged with: conditional-operator
has answer: http://stackoverflow.com/a/51108795
has comment: http://stackoverflow.com/comment/89191219
has comment: http://stackoverflow.com/comment/89206638
has comment: http://stackoverflow.com/comment/89206733
accepted answer: http://stackoverflow.com/a/51101969
has answer: http://stackoverflow.com/a/51103568
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51102052
score: 1
possible better answer: http://stackoverflow.com/a/51101898
has comment: http://stackoverflow.com/comment/89206146
favorite count: 0
has title: Using if/else on the same line with return statement
has comment: http://stackoverflow.com/comment/89190983
has answer: http://stackoverflow.com/a/51101898
tagged with: return
has comment: http://stackoverflow.com/comment/89191097
type: Question
upvote count: 2

http://stackoverflow.com/q/51121456
has answer: http://stackoverflow.com/a/51121896
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89228777
has comment: http://stackoverflow.com/comment/89228863
type: UnansweredQuestion
tagged with: c#
downvote count: 0
has title: C#: using Python.Runtime not found
type: Question
tagged with: python.net
has body: I tried to embedded a python script using Python for .NET. And in the C# program, I tried to import the class using Python.RunTime; but it cannot be found. I cannot find out the reason for that. I have already installed pythonnet in my python interpreter. I just want to test it out by codes like: using (Py.GIL) { dynamic np = Py.Import("numpy"); MessageBox.Show(np.cos(np.pi * 2)); } * UPDATE * I have add reference Python.Runtime.dll in the VS project. And when execute, it got System.BadImageFormatException. I have no clue why that happened.
answer count: 1
score: 4
favorite count: 0

http://stackoverflow.com/q/51162709
score: 1
has title: How can I create headings and columns in pandas from a dataset?
has comment: http://stackoverflow.com/comment/89308818
favorite count: 0
type: Question
has body: I know how to hard code heading names but I need to generate them from my array. Is this possible? My data is scraped dynamically, so I cannot hard code my headings or columns results_headings contains strings such as Animal, Mineral, Vegetable results_columns contains strings such as Bear, Quartz, Brocolli My code #Imports from bs4 import BeautifulSoup import requests import pandas as pd #Specify URL & Assign to page object url = 'http://www.example.com' page = requests.get(url) #Grab our page as text page.text soup = BeautifulSoup(page.text, 'html.parser') #Use the HTML Parser #Find our information boxinfo = soup.find("div", {"id": "box1"}) headings = boxinfo.find_all("td", {"class": "label"}) columns = boxinfo.find_all("td") #Get the headings results_headings = [] for result in headings: result_NoHTML = result.getText() results.append(result_NoHTML) #Get the columns results_columns = [] for result2 in columns: result2_NoHTML = result2.getText() results_columns.append(result2_NoHTML) df = pd.DataFrame(results_headings, results_columns) df.to_csv('index.csv', index=False, encoding='utf-8') Table structure I am scraping from Item1 Value1 Item2 Value2 Item3 Value3 Item4 Value4
tagged with: python
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/51163976
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51163097
has answer: http://stackoverflow.com/a/51162910
tagged with: dataframe
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89308786
tagged with: pandas
has comment: http://stackoverflow.com/comment/89309086
downvote count: 0

http://stackoverflow.com/q/51015247
upvote count: 1
accepted answer: http://stackoverflow.com/a/51016639
type: Question
has comment: http://stackoverflow.com/comment/89024062
tagged with: function
tagged with: exit-code
linked to: http://stackoverflow.com/q/47639826
answer count: 3
has title: Pygame won't quit after calling the function
has answer: http://stackoverflow.com/a/51015481
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51015525
possible better answer: http://stackoverflow.com/a/51015481
has body: I'm having some trouble while trying to quit from a function that I made. It just doesn't seem to break the loop. The game opens and I can play around but I can't quit, It just stays there without doing anything and the icon on the task bar goes full yellow. Here's my code: import pygame, os, sys, math black = (0,0,0) white = (255,255,255) grey = (128, 128, 128) gameDisplay = pygame.display.set_mode((800,600)) def game_menu(): os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.init() pygame.display.set_caption(".") menu = True events = pygame.event.get() while menu: for event in events: if event.type == pygame.QUIT: menu = False pygame.quit() quit() DISPLAYSURF = pygame.display.set_mode((800, 600)) DISPLAYSURF.fill(black) font = pygame.font.Font('MATRIX.ttf',60) TextSurf, TextRect = text_objects("MATRIX PASA PALABRA", font,white) TextRect.center = ((600/2),(50)) gameDisplay.blit(TextSurf, TextRect) #Jugar button("Jugar",300,200,200,50,None) button("Instrucciones",300,275,200,50,None) button("Dificultad",300,350,200,50,None) button("Salir",300,425,200,50,None) pygame.display.update() def text_objects(text, font,color): textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect() def button(msg,x,y,w,h,action=None): mouse = pygame.mouse.get_pos() events = pygame.event.get() if x+w&gt; mouse[0] &gt; (x) and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(gameDisplay,grey,(x,y,w,h)) for event in events: if event.type ==pygame.MOUSEBUTTONUP and msg=="Salir": pygame.quit() quit() elif event.type==pygame.MOUSEBUTTONUP and msg=="Jugar": None else: pygame.draw.rect(gameDisplay,white,(x,y,w,h)) smalltext= pygame.font.Font("MATRIX.ttf",30) textsrf,textrct=text_objects(msg,smalltext,black) textrct.center = ((x+(w/2)),(y+(h/2))) gameDisplay.blit(textsrf,textrct) if __name__ == "__main__": game_menu() Thanks and sorry for my bad english.
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/89023558
has answer: http://stackoverflow.com/a/51016639
type: AnsweredQuestion
tagged with: exit
score: 1

http://stackoverflow.com/a/51088793
has comment: http://stackoverflow.com/comment/89166112
answers question: http://stackoverflow.com/q/51088692
has body: It never did support arrays of dimension 0 or greater than 2. The docstring and error handling was just improved from 1.13 to 1.14 to better reflect this. You can see the commit for yourself in the pull request: ENH: Better error message for savetxt when X.ndim > 2 or X.ndim = 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89166091
downvote count: 0

http://stackoverflow.com/a/51149685
answers question: http://stackoverflow.com/q/51149550
downvote count: 0
type: Answer
has body: testline = 'London,Sold,2021-12-07,1000000,301909' id = 'London' j="testline2" seen = set() for element in testline.split(',') seen.add(element) if id not in seen: seen.add(j) print seen
score: 2
upvote count: 2

http://stackoverflow.com/q/51134970
has title: Why is my KNN algorithm built from scratch not working?
has body: I tried creating a KNN algorithm from scratch. My dataset is a pandas DataFrame. The algorithm always returns a 1.0 (predictions always perfectly match the actual outcome) and I'm worried something is wrong, though I don't know what. Any help in identifying is much appreciated. Here is my code: def get_neighbors(train,row,n): distances=list() for i in range(len(test)): dist=euclidean_distance(row,train.iloc[i]) distances.append((row,dist)) distances.sort(key=lambda tup: tup[1]) neighbors=list() for i in range(n): neighbors.append(distances[i][0]) return neighbors def predict_classification(train,row,n): neighbors=get_neighbors(train,row, n) output_values=[row.iloc[-1]for row in neighbors] prediction=max(set(output_values),key=output_values.count) return prediction import math def euclidean_distance(row1,row2): distance = 0.0 for i in range((row1.shape[0])): distance+=(row1[i] -row2[i]) ** 2 return math.sqrt(distance) def k_nearest_neighbors(train,test,n): predictions=list() for i in range(len(test)): output=predict_classification(train,test.iloc[i],n) predictions.append(output) return(predictions) train=dataset.iloc[0:500] test=dataset.iloc[500:600] df=po.DataFrame() df["Actual"]=test["Outcome"] df["Predicted"]=k_nearest_neighbors(train,test,5)
score: -1
has comment: http://stackoverflow.com/comment/89254310
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51135914
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: knn
upvote count: 0
type: UnansweredQuestion
tagged with: machine-learning
type: Question

http://stackoverflow.com/comment/89100297
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51054554
has text: check this link https://stackoverflow.com/questions/33665865/adjust-cell-width-in-excel

http://stackoverflow.com/comment/89230480
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51122495
has text: ndim is 0... maybe these errors are because I am pasting the array using pyperclip module..???

http://stackoverflow.com/comment/89099298
type: Comment
comment on: http://stackoverflow.com/a/51054181
has text: If instead we wanted to check with a boolean like: if e == "Jose", we would then need a for loop in order to iterate, correct?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89044324
type: Comment
comment on: http://stackoverflow.com/q/51025894
has text: Do you have to use a loop and do this by hand? Or can you use a library like pandas?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51110291
has body: I have one Estonian script, but It gives me error: Sorry: TabError: inconsistent use of tabs and spaces in indentation (function sheet1.py, line 8) [Finished in 0.2s with exit code 1] and code is: import sys import datetime end = False while end == False: def contin01(): print("Kas soovid jätkata?") exit = input("Vali [1] - JAH // Vali [2] - EI: ") if exit[0] == "1": print("********* Beginning of Line ********* ") elif exit[0] == "2": sys.exit() def sina(): nimi = input("Kirjuta enda nimi: ") def guest_name(): Guest_Name = input("Sisesta kliendi nimi: ") def guest_arrival(): Arrival = input("Sisesta kliendi saabumiskuupäev: ") def guest_dep(): Departure = input("Sisesta kliendi lahkumiskuupäev: ") def room(): Room_number = input("Sisesta kliendi toa number ") def special(): req = input("Kirjuta kliendi erisoovid, kui puuduvad pane "-": ") def WU(): wake = input("Kirjuta mis kell soovib klient äratust") def date(): päev = datetime.datetime.now().strftime("%d-%m-%Y T%H:%M") can't find the problem - tried deleting and trying again but nothing changes
type: UnansweredQuestion
tagged with: python
has title: Python : Taberror
has answer: http://stackoverflow.com/a/51110308
tagged with: syntax
type: Question
has comment: http://stackoverflow.com/comment/89207671
score: 0
tagged with: indentation
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/119673214
comment on: http://stackoverflow.com/q/51125013
score: 0
type: QuestionComment
has text: @DanielPryden imo pyenv should be recommended before going to the website to manually download and install. People that already use homebrew are probably searching for a nice commandline solution. For anyone scrolling through here, scroll down: https://stackoverflow.com/a/60189988/4600952
type: Comment

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/51094284
type: Tag

http://stackoverflow.com/comment/89045225
type: QuestionComment
comment on: http://stackoverflow.com/q/51026315
has text: @usr2564301 is there any way to tell Python3 to print everything in utf-8? just like I did in Python2?
score: 0
type: Comment

http://stackoverflow.com/q/51041562
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/89076556
has body: I have an odd problem at which when I run my code below in PyCharm or through the console (python script.py) the flask server takes an extremely long time to boot meaning when trying to access it it shows no content for a good few minutes. import threading from flask import render_template, request, logging, Flask, redirect def setupFlask(): appn = Flask(__name__) log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) @appn.route('/') def page(): return render_template('index.html') @appn.route('/submit', methods=['POST']) def submit(): token = request.form['ID'] ID = token return redirect('/') appn.run() a = threading.Thread(target=setupFlask) a.daemon = True a.start() while True: pass The odd thing is that when I run the same code above in the PyCharm debugger, the flask server takes about 5 seconds to boot, massively quicker than the few minutes it takes when run in the console. I would love that kind of speed when running the script normally and cant find a solution due to the problem fixing itself when in debugger! This code snippet is part of a larger application, however I have adapted it to be run on its own and the same problem occurs. I am not running in a virtualenv. All help appreciated. EDIT: The index.html document is very basic and only contains a few scripts and elements therefore I could not see it taking a long time to load.
score: 5
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/89075314
has answer: http://stackoverflow.com/a/51044369
has comment: http://stackoverflow.com/comment/89078668
has comment: http://stackoverflow.com/comment/89078831
upvote count: 5
downvote count: 0
tagged with: flask
accepted answer: http://stackoverflow.com/a/51044369
has comment: http://stackoverflow.com/comment/89076602
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89075123
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/89076163
has title: Python flask server taking long time to boot

http://stackoverflow.com/comment/89138217
has text: Hi! good morning I have tried the code but run into issue with `ImageGrab`. This actually works on Windows and MacOS only, mine is Ubuntu. Can we use pyscreenshot instead. Not finding any success.
comment on: http://stackoverflow.com/a/51065493
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89145988
has text: @jezrael Just a plain `ValueError` is what you'll see when using Python 2. Python 3 has the chained tracebacks.
score: 0
comment on: http://stackoverflow.com/q/51077487
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51153046
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89289989
has comment: http://stackoverflow.com/comment/89536281
has title: Recognition digit or math operator app
tagged with: java
tagged with: tensorflow
type: Question
has body: I have a problem and I can't find what it's wrong with my code. From beginning. I have application to recognize digits and math operators, the basic one +, -, /, *. I have a model ready which creates a graph. This graph is imported by an Android application. In my opinion, it should work but I don't know why it isn't? Model.py import tensorflow as tf import numpy as np import _pickle as pickle from matplotlib import pyplot as plt from tensorflow.examples.tutorials.mnist import input_data # mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True) # read CROHME_test_data with open("test.pickle", 'rb') as f: data = pickle.load(f) # np.random.shuffle(data) CROHME_test_data = {"features": np.array([d["features"] for d in data]), "labels": np.array([d["label"] for d in data])} # read CROHME_train_data with open("train.pickle", 'rb') as f: data = pickle.load(f) # np.random.shuffle(data) CROHME_train_data = {"features": np.array([d["features"] for d in data]), "labels": np.array([d["label"] for d in data])} # function for pulling batches from custom data def next_batch(num, data): idx = np.arange(0, len(data["features"])) np.random.shuffle(idx) idx = idx[:num] features_shuffle = [data["features"][i] for i in idx] labels_shuffle = [data["labels"][i] for i in idx] return np.asarray(features_shuffle), np.asarray(labels_shuffle) # Function to create a weight neuron using a random number. Training will assign a real weight later def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) # Function to create a bias neuron. Bias of 0.1 will help to prevent any 1 neuron from being chosen too often def biases_variable(shape, name): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=name) # Function to create a convolutional neuron. Convolutes input from 4d to 2d. This helps streamline inputs def conv_2d(x, W, name): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME', name=name)…
tagged with: neural-network
has comment: http://stackoverflow.com/comment/89510723
tagged with: android
has comment: http://stackoverflow.com/comment/89509928
answer count: 0
has comment: http://stackoverflow.com/comment/89290372

http://stackoverflow.com/comment/89031997
score: 0
has text: It would be helpful to know which screen scraping library you're using before providing an answer. [this thread](https://stackoverflow.com/questions/23102833/how-to-scrape-a-website-which-requires-login-using-python-and-beautifulsoup) and [this thread](https://stackoverflow.com/questions/13925983/login-to-website-using-urllib2-python-2-7) may be able to help
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51019623

http://stackoverflow.com/comment/89247977
type: AnswerComment
comment on: http://stackoverflow.com/a/51130020
score: 0
type: Comment
has text: Sorry, because I am a newer, could you please give me the example of how to use css-selector. In addition, I have use your script but it shows error and can not get the response. CSS: #wiki-edit-wikiEdit1 > div > div > div > div:nth-child(2) > a:nth-child(1) > span

http://stackoverflow.com/a/51168009
has body: You Must also Using Django F() and Count() annotate functions... Try Below code: Blog.objects.annotate( author_titles=Count('author__title'), author_likes=Count('author__likes') ).annotate( total=F('author_titles') + F('author_likes') ).annotate( name=Case( When(total__gt=0,total__lt=11, then=Value('B')), When(total__gt=10,total__lt=21, then=Value('C')), When(total__gt=20,total__lt=31, then=Value('D')), default=Value('A'), output_field=CharField(), ) )
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 25
accepted answer of: http://stackoverflow.com/q/51165089
has comment: http://stackoverflow.com/comment/89338073
upvote count: 25
answers question: http://stackoverflow.com/q/51165089

http://stackoverflow.com/q/51137573
upvote count: 2
has comment: http://stackoverflow.com/comment/89403211
tagged with: numba
tagged with: python
has title: Numba vectorize for function with no input
tagged with: vectorization
accepted answer: http://stackoverflow.com/a/51336044
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89265663
downvote count: 0
has answer: http://stackoverflow.com/a/51336044
score: 2
answer count: 1
favorite count: 0
has body: I want to parallelize a function using numba.vectorize, but my function doesn't take any input. Currently, I use a dummy array and dummy input for my function that is never used. Is there a more elegant/fast way (possibly without using numba.vectorize)? Code example (not my actual code, only for demonstration how I discard input): import numpy as np from numba import vectorize @vectorize(["int32(int32)"], nopython=True) def particle_path(discard_me): x = 0 for _ in range(10): x += np.random.uniform(0, 1) return np.int32(x) arr = particle_path(np.empty(1024, dtype=np.int32)) print(arr)

http://stackoverflow.com/comment/89060617
score: 1
comment on: http://stackoverflow.com/q/51034265
type: QuestionComment
type: Comment
has text: Should be `for x in string:` and string as the argument to start. But other problems too. X.lower() doesn’t replace x it returns the lower version and you shouldn’t use special words like string for variables.

http://stackoverflow.com/q/51146536
answer count: 2
has answer: http://stackoverflow.com/a/51146645
has body: Just a new user of scrapy.org and a newbie to Python. I have this values at brand and title properties (JAVA OOP Term) that contains tab spaces and new line. How can we trim it to make this 2 following object properties to have this plain string value item['brand'] = "KORAL ACTIVEWEAR" item['title'] = "Boom Leggings" Below is the data structure {'store_id': 870, 'sale_price_low': [], 'brand': [u'\n KORAL ACTIVEWEAR\n '], 'currency': 'AUD', 'retail_price': [u'$140.00'], 'category': [u'Activewear'], 'title': [u'\n Boom Leggings\n '], 'url': [u'/boom-leggings-koral-activewear/vp/v=1/1524019474.htm?folderID=13331&amp;fm=other-shopbysize-viewall&amp;os=false&amp;colorId=68136'], 'sale_price_high': [], 'image_url': [u' https://images-na.sample-store.com/images/G/01/samplestore/p/prod/products/kacti/kacti3025868136/kacti3025868136_q1_2-0._SH20_QL90_UY365_.jpg\n'], 'category_link': 'https://www.samplestore.com/clothing-activewear/br/v=1/13331.htm?baseIndex=500', 'store': 'SampleStore'} I was able to trim the prices to only get the number and decimal by using regex search method, which I think might be wrong when there is a price comma separator. price = re.compile('[0-9\.]+') item['retail_price'] = filter(price.search, item['retail_price'])
tagged with: python
possible better answer: http://stackoverflow.com/a/52248786
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52248786
has comment: http://stackoverflow.com/comment/89277253
accepted answer: http://stackoverflow.com/a/51146645
tagged with: scrapy
type: Question
has title: Python - Remove tab and new line in Object
tagged with: scrapy-pipeline
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/89281959
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51149055
has text: please read content submission rules. You should be using formatting tools to provide us your code instead of pasting a screenshot of the code.
type: Comment

http://stackoverflow.com/q/51038762
has comment: http://stackoverflow.com/comment/89069074
accepted answer: http://stackoverflow.com/a/51039261
has comment: http://stackoverflow.com/comment/89068927
type: Question
tagged with: forkjoinpool
score: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89069584
favorite count: 0
has answer: http://stackoverflow.com/a/51039261
linked to: http://stackoverflow.com/q/3044580
tagged with: python
has title: Difference in parallel processing between java and python
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89069424
upvote count: 2
has body: I make parallel processing program using java.util.concurrent.ForkJoinPool. While proceeding this program, I checked top and htop, and noticed that in top there are only one java process but in htop there are many processes. My senior is writing parallel processing program using python, and he says that it is strange that there are only one process in top. And also he says that the "CPU usage" in top is usually over 90%. But my program uses only about 68%. I thought that the cause is the difference in how to realize parallel processing between java and python. But I do not know whether it is correct. Please tell me the correct cause of this difference. Thanks.
tagged with: java
has comment: http://stackoverflow.com/comment/89069697

http://stackoverflow.com/comment/89089777
has text: Try changing `SecID integer SET DEFAULT=10` to `SecID integer DEFAULT 10`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51026705

http://stackoverflow.com/q/51124706
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has body: I was studying "how to build a simple network sniffer" but I have a lot of problems. I created two scripts (really easy), but in both of these I get an error every time. First script: import socket import os import struct from ctypes import * host = "192.168.1.37" class IP(Structure): _fields_ = [ ("ihl", c_ubyte, 4), ("version", c_ubyte, 4), ("tos", c_ubyte), ("len", c_ushort), ("id", c_ushort), ("offset", c_ushort), ("ttl", c_ubyte), ("protocol_num", c_ubyte), ("sum", c_ushort), ("src", c_ulong), ("dst", c_ulong), ] def __new__(self, socket_buffer=None): return self.from_buffer_copy(socket_buffer) def __init__(self, socket_buffer=None): self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"} self.src_address = socket.inet_ntoa( struct.pack("&lt;L",self.src)) self.dst_address = socket.inet_ntoa( struct.pack("&lt;L",self.dst)) if os.name == "nt": socket_protocol = socket.IPPROTO_IP else: socket_protocol = socket.IPPROTO_ICMP sniffer = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket_protocol) sniffer.bind((host, 0)) sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) try: while true: raw_buffer = sniffer.recvfrom(65565)[0] ip_header = IP(raw_buffer[0:20]) print ("Protocol: %s %s -&gt; %s") % (ip_header.protocol, \ ip_header.src_adress, ip_header.dst_adress) except KeyboardInterrupt: if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) When I execute on my Android device I get this error: errno 99 invalid address (I changed the host address a lot of times but nothing happened) Second code: (really easy with Scapy) from scapy.all import * pkts = sniff(iface="eth0", count=10) When I try to execute this code I get this error: unknown network interface "eth0" (or wlan0 ecc..) Hope you can help me.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51132508
tagged with: python
tagged with: packet-sniffers
downvote count: 0
score: 1
has title: python errno 99/unknow interface

http://stackoverflow.com/comment/89310790
comment on: http://stackoverflow.com/a/51163302
score: 0
type: AnswerComment
has text: i replaced 'w' with 'a' , with no success
type: Comment

http://stackoverflow.com/q/51111017
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51111044
tagged with: python-2.7
score: 0
has body: Let's assume I am making a key-value pair that will not consist of any subkeys. self.profiles[server.id][author.id]['games']['accounts']['league'] already exists. Is there any benefit or purpose of using self.profiles[server.id][author.id]['games']['accounts']['league'].update({'plays': true}) over self.profiles[server.id][author.id]['games']['accounts']['league']['plays'] = True ?
has title: When creating a new dictionary key in Python, are there benefits to creating it with `update` rather than simply =?
has answer: http://stackoverflow.com/a/51111042
possible better answer: http://stackoverflow.com/a/51111042
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51111044
type: AnsweredQuestion

http://stackoverflow.com/q/51162636
has body: Keep in mind I just started Python today so I'm terrible. Hello, I am programming a bot for Discord, and I'm running into a problem when I run it. I'm trying to get it online and I've been getting the same error. I don't know where the error is coming from though. Can someone please help? Here is my code so far: import discord from discord.ext.commands import bot from discord.ext import commands import asyncio import time Client = discord.Client() client = commands.Bot(command_prefix = "~") @client.event async def on_ready(): print("I'm up on some BOOF!" + client.user.id) print("I am the" + client.user.name) @client.event async def on_message(message): if message.content == "Boof": await client.send_message(message.channel, ":b:") client.run("&lt;redacted&gt;") The error I am getting: Ignoring exception in on_ready Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "/Users/johnathanhelsel/Documents/Boof Bot/BoofBot.py", line 13, in on_ready print("I am the" + client.user.name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/idlelib/run.py", line 362, in write return self.shell.write(s, self.tags) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/idlelib/rpc.py", line 604, in __call__ value = self.sockio.remotecall(self.oid, self.name, args, kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/idlelib/rpc.py", line 216, in remotecall return self.asyncreturn(seq) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/idlelib/rpc.py", line 247, in asyncreturn return self.decoderesponse(response) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/idlelib/rpc.py", line 267, in decoderesponse raise what UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 8-8: Non-BMP character not supported i…
linked to: http://stackoverflow.com/q/32442608
has answer: http://stackoverflow.com/a/51162741
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has title: UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 8-8: Non-BMP character not supported in Tk
duplicate of: http://stackoverflow.com/q/32442608
type: Question
score: 3
tagged with: bots
has answer: http://stackoverflow.com/a/51162697
answer count: 2
favorite count: 0
upvote count: 3
tagged with: python-3.7
tagged with: python
tagged with: discord

http://stackoverflow.com/a/51132491
accepted answer of: http://stackoverflow.com/q/51065173
type: Answer
has body: Lot's of errors here: equadiff returns S which is not declared. Scilab indexing start at 1 subplot doesn't have an argument named "aspect". t0 is undefined. equadiff arguments must be t,var in that order. x argument must be a column vector if t is a row vector. Oscillateur returns T which is not declared. disp cannot returns this empty return. x_location property doesn't exist for axes handle Fixing all theses errors gives you : m1=1;m2=1; k1=1;k2=1;k3=1; m=1; k=1; a=1; // added k1,k2,k3 m1,m2 as argument function S=equadiff(t,x,k1,k2,k3,m1,m2) x1=x(1) x2=x(2) v1=x(3) v2=x(4) a1=(k2*x2-(k1+k2)*x1)/m1 a2=(k2*x1-(k2+k3)*x2)/m2 S=[v1;v2;a1;a2] // now equadiff returns an 4 by 1 vector endfunction // added k1,k2,k3 m1,m2 as argument // Removed T as not used function Oscillateur(x10,x20,v10,v20,tmax,equadiff,k1,k2,k3,m1,m2) t=linspace(0,tmax,300) figure() var0=[x10;x20;v10;v20] // x is 4 by 1 vector solution=ode(var0,0,t,list(equadiff,k1,k2,k3,m1,m2)) // k1 ,etc ar now passed as additionnal argument for equadiff // since equadiff returns a 4 by 1 vector and t is 1 by 300 // solution is 4 by 300 x1=solution(1,:) x2=solution(2,:) v1=solution(3,:) v2=solution(4,:) plot(t,x1,t,x2) legend('x1','x2') a=gca() //a.x_location = "zero"; // what was that for ? set(a,"tight_limits","on"); endfunction // Display is only for printing value. Oscillateur(a,a,0,0,10,equadiff,k1,k2,k3,k1,m2) Oscillateur(a,-a,0,0,10,equadiff,k1,k2,k3,k1,m2) Oscillateur(2*a,0,0,0,50,equadiff,k1,k2,k3,k1,m2)
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51065173
downvote count: 0

http://stackoverflow.com/q/51112761
tagged with: python
has body: I'm trying to use 'argv' into my python script. For this i'm using following code: from sys import argv script, file_name = argv print(file_name) python3 e.py e.txt This code works fine. But when I use: import sys and try to use 'argv', I get error: 'NameError: name 'argv' is not defined '. I don't understand this as by importing 'sys' full module becomes usable into my code. Can you explain why does this happen? How to packages work? Thank you.
has answer: http://stackoverflow.com/a/55042458
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/89212214
type: Question
has comment: http://stackoverflow.com/comment/89212397
has title: Python packages.'import sys' vs 'from sys import argv'
has comment: http://stackoverflow.com/comment/89212190
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89212185
favorite count: 0
tagged with: python-3.x
tagged with: package
score: -3
has answer: http://stackoverflow.com/a/51112956

http://stackoverflow.com/comment/89225631
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51120046
has text: Can you show what you have tried?

http://stackoverflow.com/a/51046569
has comment: http://stackoverflow.com/comment/89102222
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51046430
type: AcceptedAnswer
has body: I think there is the problem: urlpatterns = patterns('judging.views', url(r'^$', AppView.as_view(), name='judge_home') ) You should delete $ or ^ sign from url pattern.
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51046430
has comment: http://stackoverflow.com/comment/89100584

http://stackoverflow.com/comment/89169528
score: 0
type: Comment
has text: Can you just help me understand a bit? I know `/s` is space character and I'm guessing `{2,}` means look for this pattern at least 2 times? Still a bit confused but I'd like to understand how it works.
type: AnswerComment
comment on: http://stackoverflow.com/a/51090566

http://stackoverflow.com/comment/89096004
has text: changed the question
comment on: http://stackoverflow.com/q/51052364
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89172481
type: Comment
has text: Oh wow, just noticed that. I had only been reading the gentler tutorial but the full part says: "If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group." I still don't fully understand the implication but that should be enough to study, thanks!
score: 0
comment on: http://stackoverflow.com/q/51092015
type: QuestionComment

http://stackoverflow.com/a/51119107
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51119086
has body: Merge does not know how to differentiate those identical rows, so they are duplicated more times than necessary. I would suggest using a temporary column to record the cumcount, perform the merge-ing, and then removing the temp column after. df1['d'] = df1.groupby(df1.columns.tolist()).cumcount() df2['d'] = df2.groupby(df2.columns.tolist()).cumcount() df1.merge(df2, how='inner').drop('d', 1) a b c 0 foo None qux 1 foo bar None 2 foo None qux This works because df1 and df2 now have a 4th indicator column to differentiate duplicates: print(df1) a b c d 0 foo None qux 0 1 foo bar None 0 2 foo None None 0 3 foo None qux 1 4 foo None None 1 print(df2) a b c d 0 foo None qux 0 1 foo None qux 1 2 foo bar qux 0 3 foo bar None 0 4 foo bar None 1
type: Answer
has comment: http://stackoverflow.com/comment/89224283
has comment: http://stackoverflow.com/comment/89224137
upvote count: 1
answers question: http://stackoverflow.com/q/51119086
has comment: http://stackoverflow.com/comment/89224255
score: 1
has comment: http://stackoverflow.com/comment/89224128

http://stackoverflow.com/q/51045264
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51045320
type: Question
has answer: http://stackoverflow.com/a/51045326
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/51045320
answer count: 2
downvote count: 0
has body: Input code is: # Input data: S = pd.S = 2000 # Saturation flow L = pd.L = 5 # Lost time eb = pd.eb = 1000 wb = pd.wb = 600 sb = pd.sb = 400 nb = pd.nb = 500 # a) C_min = Minimum cycle length calculation Y_eb = pd.Y_eb = eb / S Y_wb = pd.Y_wb = wb / S Y_sb = pd.Y_sb = sb / S Y_nb = pd.Y_nb = nb / S Y_eb_wb_sb_nb = [Y_eb,Y_wb,Y_sb,Y_nb] Y_eb_wb_sb_nb Output: [0.5, 0.3, 0.2, 0.25] Then if Y_eb &gt; Y_wb: print(C_min = L / 1 - (Y_eb + Y_wb)) I want to: Get maximum values from (Y_eb;Y_wb) and (Y_sb;Y_nb) and apply these values to formula: C_min = L / (1- [max of (Y_eb;Y_wb)] + [max of (Y_sb;Y_nb)])
accepted answer: http://stackoverflow.com/a/51045326
favorite count: 0
has title: Want to get maximum values from output and apply them to equation

http://stackoverflow.com/q/51039541
has title: pandas how to count number of entries by id in a selected daterange
score: 0
has answer: http://stackoverflow.com/a/51041550
answer count: 2
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/89070550
tagged with: pandas
upvote count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51041151
type: Question
has comment: http://stackoverflow.com/comment/89070600
has body: I have a relatively big data frame (~10mln rows). It has an id and DateTimeIndex. I have to count a number of entries with a certain id for each row for a period of time (last week\month\year). I've created my own function using relativedelta and storing dates in a separate dictionary {id: [dates]}, but it works extremely slow. How should I do it fast and properly? P.S.: I've heard about pandas.rolling() but I can't figure out how to use it correctly. P.P.S.: my function: def isinrange(date, listdate, delta): date,listdate = datetime.datetime.strptime(date,format),datetime.datetime.strptime(listdate,format) return date-delta&lt;=listdate main code, contains tons of unnecessary operations: dictionary = dict() #structure {id: [dates]} for row in df.itertuples():#filling a dictionary if row.id in dictionary: dictionary[row.id].append(row.DateTimeIndex) else: dictionary[row.id] = [row.DateTimeIndex,] week,month,year = relativedelta(days =7),relativedelta(months = 1),relativedelta(years = 1)#relative delta init for row, i in zip(df.itertuples(),range(df.shape[0])):#iterating over dataframe cnt1=cnt2=cnt3=0 #weekly,monthly, yearly - for each row for date in dictionary[row.id]:#for each date with an id from row index_date=row.DateTimeIndex if date&lt;=index_date: #if date from dictionary is lesser than from a row if isinrange(index_date,date,year): cnt1+=1 if isinrange(index_date,date,month): cnt2+=1 if isinrange(index_date,date,week): cnt3+=1 df.loc[[i,36],'Weekly'] = cnt1 #add values to a data frame df.loc[[i,37],'Monthly'] = cnt2 df.loc[[i,38],'Yearly']=cnt3 Sample: id date 1 2015-05-19 1 2015-05-22 2 2018-02-21 2 2018-02-23 2 2018-02-27 Expected result: id date last_week 1 2015-05-19 0 1 2015-05-22 1 2 2018-02-21 0 2 2018-02-23 1 2 2018-02-27 2
tagged with: dataframe

http://stackoverflow.com/a/51567342
score: 10
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51150468
answers question: http://stackoverflow.com/q/51150468
upvote count: 10
has body: It seems the first Keras LSTM layer still requires an input_shape when using fit_generator which seems to be missing in the Keras documentation and results in the "You must compile your model before using it" error. To solve make sure you have an input_shape parameter in your first LSTM layer as shown by the example below: model.add(LSTM(100, input_shape=(n_timesteps, n_dimensions), return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(100, return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(10, activation='tanh')) model.compile(loss='mse', optimizer='adam')

http://stackoverflow.com/q/51069716
has comment: http://stackoverflow.com/comment/89129485
has answer: http://stackoverflow.com/a/70091711
has answer: http://stackoverflow.com/a/67138148
has answer: http://stackoverflow.com/a/51069794
has comment: http://stackoverflow.com/comment/89129343
has body: Please help me to find reason on MacOS why when I including library import wget I'm getting error File "/Users/xx/python/import.py", line 4, in &lt;module&gt; import wget ImportError: No module named wget This library is installed xx$ pip3 install wget Requirement already satisfied: wget in /usr/local/lib/python3.6/site-packages (3.2) I just suppose that some path is not set, but I don't know how to prove this. Please help me find solution for this problem.
has answer: http://stackoverflow.com/a/65679809
has answer: http://stackoverflow.com/a/74658573
type: Question
score: 12
has comment: http://stackoverflow.com/comment/89129401
upvote count: 12
has comment: http://stackoverflow.com/comment/89129527
tagged with: wget
has title: ImportError: No module named wget
downvote count: 0
has answer: http://stackoverflow.com/a/71844818
has comment: http://stackoverflow.com/comment/89129336
has answer: http://stackoverflow.com/a/61220453
has comment: http://stackoverflow.com/comment/89131612
tagged with: python
has answer: http://stackoverflow.com/a/51069893
tagged with: macos
favorite count: 0
answer count: 9
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51070083

http://stackoverflow.com/q/51034031
has comment: http://stackoverflow.com/comment/89060423
accepted answer: http://stackoverflow.com/a/51034466
has comment: http://stackoverflow.com/comment/89060357
answer count: 3
has answer: http://stackoverflow.com/a/51034509
tagged with: pandas
has title: Cumulative count between two columns in a pandas df
has comment: http://stackoverflow.com/comment/89060511
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89060823
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/89060637
has body: I am trying to return a cumulative count of the amount of times there's a change of values in a column. So for the df below, I want to return a running count of the times that 'Home' changes to 'Away' and vice versa. I don't want to return the amount of times a value is displayed. import pandas as pd d = ({ 'Who' : ['Home','Away','','','Home','Away','Home','Home','Home','','Away','Home'], }) df = pd.DataFrame(data = d) I tried this. df['Home_count'] = (df['Who'] == 'Home').cumsum() df['Away_count'] = (df['Who'] == 'Away').cumsum() Which returns: Who Home_count Away_count 0 Home 1 0 1 Away 1 1 2 1 1 3 1 1 4 Home 2 1 5 Away 2 2 6 Home 3 2 7 Home 4 2 8 Home 5 2 9 5 2 10 Away 5 3 11 Home 6 3 But I'm trying to count the amount of times it changes. Not the total count of each value. So if it reads Home, Home, Home, Away, there should only be a count next to Away. Not 1,2,3 against Home. Home 1 #Theres a change so provide a count Home #No change so no count Home #No change so no count Away 1 #Theres a change so provide a count Home 2 #Theres a change so provide a count Please refer to intended output: Intended output: Count_Away Count_Home Who 0 1 Home 1 1 Away 2 3 4 2 Home 5 2 Away 6 3 Home 7 Home 8 Home 9 10 3 Away 11 4 Home
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89060830
upvote count: 1
has answer: http://stackoverflow.com/a/51034466
type: Question
possible better answer: http://stackoverflow.com/a/51034268
has answer: http://stackoverflow.com/a/51034268
linked to: http://stackoverflow.com/q/24870953

http://stackoverflow.com/q/51041014
has comment: http://stackoverflow.com/comment/89098658
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89076636
has body: If I have a keras layer L, and I want to stack N versions of this layer (with different weights) in a keras model, what's the best way to do that? Please note that here N is large and controlled by a hyper param. If N is small then this not a problem (we can just manually repeat a line N times). So let's assume N > 10 for example. If the layer has only one input and one output, I can do something like: m = Sequential() for i in range(N): m.add(L) But this is not working if my layer actually takes multiple inputs. For example, if my layer has the form z = L(x, y), and I would like my model to do: x_1 = L(x_0, y) x_2 = L(x_1, y) ... x_N = L(x_N-1, y) Then Sequential wouldn't do the job. I think I can subclass a keras model, but I don't know what's the cleanest way to put N layers into the class. I can use a list, for example: class MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.layers = [] for i in range(N): self.layers.append(L) def call(self, inputs): x = inputs[0] y = inputs[1] for i in range(N): x = self.layers[i](x, y) return x But this is not ideal, as keras won't recognize these layers (it seems not thinking list of layers as "checkpointables"). For example, MyModel.variables would be empty, and MyModel.Save() won't save anything. I also tried to define the model using the functional API, but it won't work in my case as well. In fact if we do def MyModel(): input = Input(shape=...) output = SomeLayer(input) return Model(inputs=input, outputs=output) It won't run if SomeLayer itself is a custom model (it raises NotImplementedError). Any suggestions?
has comment: http://stackoverflow.com/comment/89080923
has comment: http://stackoverflow.com/comment/89079205
has comment: http://stackoverflow.com/comment/89081146
answer count: 3
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/51041136
has title: How to stack layers in Keras without using Sequential()?
favorite count: 0
has comment: http://stackoverflow.com/comment/89074691
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89074779
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/69464119
has comment: http://stackoverflow.com/comment/89102413
upvote count: 6
has comment: http://stackoverflow.com/comment/89074822
has comment: http://stackoverflow.com/comment/89073267
has answer: http://stackoverflow.com/a/51064945

http://stackoverflow.com/q/51028154
linked to: http://stackoverflow.com/q/23303827
has comment: http://stackoverflow.com/comment/89049076
downvote count: 1
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51028295
accepted answer: http://stackoverflow.com/a/51028295
has comment: http://stackoverflow.com/comment/89048699
tagged with: function
has answer: http://stackoverflow.com/a/51028375
has comment: http://stackoverflow.com/comment/89048689
has body: This code returns False, but when I delete point from float it becomes True and I'm trying to understand why. Explain please def isDigit(string): string = string.strip() if string[:1] == "-": cuted = string[1:] if cuted.isdigit(): return True else: return False elif string.isdigit(): return True else: return False print isDigit("-234.4") also I know my code is not the best and I wonder how can I make it better
has comment: http://stackoverflow.com/comment/89049127
duplicate of: http://stackoverflow.com/q/23303827
favorite count: 0
has comment: http://stackoverflow.com/comment/89048897
has comment: http://stackoverflow.com/comment/89048647
has title: python float is not digit?
possible better answer: http://stackoverflow.com/a/51028375
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89049042
has comment: http://stackoverflow.com/comment/89048704
score: 1
has comment: http://stackoverflow.com/comment/89048820

http://stackoverflow.com/comment/89175557
comment on: http://stackoverflow.com/a/51093208
has text: `user_settings` is a model object - so the code you've given just shows nothing.
score: 0
type: AnswerComment
type: Comment

sorting
tags question: http://stackoverflow.com/q/51160753
tags question: http://stackoverflow.com/q/51117243
tags question: http://stackoverflow.com/q/51114887
tags question: http://stackoverflow.com/q/51110870
tags question: http://stackoverflow.com/q/51054293
tags question: http://stackoverflow.com/q/51087954
tags question: http://stackoverflow.com/q/51061845
tags question: http://stackoverflow.com/q/51072635
tags question: http://stackoverflow.com/q/51125432
tags question: http://stackoverflow.com/q/51074984
tags question: http://stackoverflow.com/q/51144561
tags question: http://stackoverflow.com/q/51105916
tags question: http://stackoverflow.com/q/51166266
tags question: http://stackoverflow.com/q/51030338
tags question: http://stackoverflow.com/q/51145985
tags question: http://stackoverflow.com/q/51056938
type: Tag
tag name: sorting
tags question: http://stackoverflow.com/q/51156170
tags question: http://stackoverflow.com/q/51069629
tags question: http://stackoverflow.com/q/51154187

http://stackoverflow.com/comment/89274987
type: Comment
comment on: http://stackoverflow.com/q/51144569
has text: Python2 or Python3?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89173081
type: QuestionComment
comment on: http://stackoverflow.com/q/51092258
score: 0
has text: yes exactly without reusing any chars
type: Comment

http://stackoverflow.com/comment/92301556
type: Comment
type: QuestionComment
has text: @SeverinPappadeux I will appreciate if you write the answer for this using LCG, thanks
score: 0
comment on: http://stackoverflow.com/q/51071212

http://stackoverflow.com/a/51145075
type: Answer
has comment: http://stackoverflow.com/comment/89277852
upvote count: 3
has body: First, the simplest, and probably most efficient, way to "widespace" an entire string is: ' '.join(s) This is because strings are iterables that iterate each individual character, so if you pass one to join, it joins up all of the characters with the separate in between each pair. So, how to you widespace part of the string? Easy: slice it, join just the part you want to widespace, then merge it back together: s[:start] + ' '.join(s[start:end]) + s[end:] This isn't quite the same interface you asked for, but then I'm not sure what word is supposed to do in your question, so I just wrote the simplest thing, that widespaces everything, and hopefully you can figure out how to map it to what you want: &gt;&gt;&gt; s = 'foo foo foo foo foo foo foo' &gt;&gt;&gt; s[:8] + ' '.join(s[8:15]) + s[15:] 'foo foo f o o f o o foo foo foo' Note that this also allows you to use start=None, end=None default values, and they'll automatically work with the same meanings as in slicing, range, etc.: None means start at the start or end at the end. This will be very efficient, but probably not as efficient as creating a custom C extension that reserves the space for len(s) + end - start at the start and then loops over the characters in C.
score: 3
has comment: http://stackoverflow.com/comment/89274455
has comment: http://stackoverflow.com/comment/89274458
accepted answer of: http://stackoverflow.com/q/51145039
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51145039
has comment: http://stackoverflow.com/comment/89274428

http://stackoverflow.com/comment/89317334
comment on: http://stackoverflow.com/a/51145398
type: Comment
has text: I'm using `pandas 0.19.2` and `matplotlib 2.2.2`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89331370
type: AnswerComment
comment on: http://stackoverflow.com/a/51097519
type: Comment
has text: Any idea why that doesn't work `zip -r ascrawler.zip venv/bin/activate_this.py venv/lib/python3.6/site-packages/raven venv/lib/python3.6/site-packages/raven-6.9.0.dist-info __main__.py common.py db.py` ? I want to use raven to capture errors, and I did like in your tutorial but I get an error `"error": "The action did not return a dictionary."`. And in logs `.....<module>", "2018-07-04T12:55:56.590718898Z stderr: from raven import Client", "2018-07-04T12:55:56.590724452Z stderr: ModuleNotFoundError: No module named 'raven'"`
score: 0

http://stackoverflow.com/q/51151850
tagged with: apache-spark
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52562261
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
tagged with: character-encoding
type: Question
tagged with: encoding
tagged with: pyspark
has title: PySpark DF and RDD encoding of latin letters
has body: I have to import CSV file in Spark and convert it in DF and then in RDD before process it. First I import the full CSV file as a DF stopwords_df = ( sqlc .read .format('csv') .option('header', True) .option('delimiter', ';') .option('encoding', 'latin1') .load('/mnt/sparkdata/stopwords.csv', schema = stopSchema) .repartition(72) ) Then I select the suitable words only and convert this into a set stopwords_set = set( stopwords_df .filter(f.col('retain').isNull()) .rdd .map(lambda x: x[0].encode('latin1')) # the [0] is to extract strings from Rows .collect() ) I'm messing up with the encoding and I don't know how to fix this. If I "show" the DF, the Latin letters will be shown correctly (sperò) stopwords_df.show(100, truncate = False) +--------------+--------+------+----------+------+ |word |language|type |doubletype|retain| +--------------+--------+------+----------+------+ |informava |IT |verbo |null |null | |sperò |IT |verbo |null |null | |four |EN |null |null |null | But this won't happen if I show the RDD ( stopwords_df .filter(f.col('word') == r'sperò') .rdd .first() ) Row(word=u'sper\xf2', language=u'IT', type=u'verbo', doubletype=None, retain=None) With UTF-8 encoding it will also go worst +--------------+--------+------+----------+------+ |word |language|type |doubletype|retain| +--------------+--------+------+----------+------+ |thanks |EN |saluto|null |null | |fossero |IT |verbo |null |null | |sper� |IT |verbo |null |null | Could you please suggest me how to fix this?

http://stackoverflow.com/a/51171618
answers question: http://stackoverflow.com/q/51167099
has comment: http://stackoverflow.com/comment/89350714
score: 15
upvote count: 15
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51167099
type: Answer
has body: Installing Ansible on Windows is cumbersome. My advice is not a direct solution on how to install Ansible on Windows, but rather a workaround. I use a Docker container with Ansible for developing playbooks on my Windows machine. You'd need Docker for Windows on your machine. Here's the Dockerfile: FROM alpine:3.7 ENV ANSIBLE_VERSION=2.5.4 ENV BUILD_PACKAGES \ bash \ curl \ tar \ nano \ openssh-client \ sshpass \ git \ python \ py-boto \ py-dateutil \ py-httplib2 \ py-jinja2 \ py-paramiko \ py-pip \ py-setuptools \ py-yaml \ ca-certificates RUN apk --update add --virtual build-dependencies \ gcc \ musl-dev \ libffi-dev \ openssl-dev \ python-dev &amp;&amp; \ set -x &amp;&amp; \ apk update &amp;&amp; apk upgrade &amp;&amp; \ apk add --no-cache ${BUILD_PACKAGES} &amp;&amp; \ pip install --upgrade pip &amp;&amp; \ pip install python-keyczar docker-py boto3 botocore &amp;&amp; \ apk del build-dependencies &amp;&amp; \ rm -rf /var/cache/apk/* &amp;&amp; \ mkdir -p /etc/ansible/ /ansible &amp;&amp; \ echo "[local]" &gt;&gt; /etc/ansible/hosts &amp;&amp; \ echo "localhost" &gt;&gt; /etc/ansible/hosts &amp;&amp; \ curl -fsSL https://releases.ansible.com/ansible/ansible-${ANSIBLE_VERSION}.tar.gz -o ansible.tar.gz &amp;&amp; \ tar -xzf ansible.tar.gz -C /ansible --strip-components 1 &amp;&amp; \ rm -fr ansible.tar.gz /ansible/docs /ansible/examples /ansible/packaging ENV ANSIBLE_GATHERING=smart \ ANSIBLE_HOST_KEY_CHECKING=false \ ANSIBLE_RETRY_FILES_ENABLED=false \ ANSIBLE_ROLES_PATH=/ansible/playbooks/roles \ ANSIBLE_SSH_PIPELINING=True \ PYTHONPATH=/ansible/lib \ PATH=/ansible/bin:$PATH \ ANSIBLE_LIBRARY=/ansible/library \ EDITOR=nano WORKDIR /ansible/playbooks ENTRYPOINT ["ansible-playbook"] Build the docker container with the docker build command. Afterwards you can create a small bash script that executes the docker run command and mounts your current directory into the container. You may call it ansible-playbook.sh: winpty docker run --rm -it -v /$(pwd):/ansible/playbook…

http://stackoverflow.com/q/51109036
has answer: http://stackoverflow.com/a/51109302
type: Question
score: 0
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/51109072
has title: count total, total nulls, mean and median
tagged with: python-3.x
has body: Let us say I have a data frame with a column called values, and for this column, I want to calculate the total observations, total null observations, mean and median values per group. I.e., mydf = pd.DataFrame({'date_ym':['2018-01', '2018-01','2018-01','2018-01','2018-02','2018-02','2018-03'],'category':['A','A','A','B','A','B','B'], 'values':[np.nan,4.0,5.1,np.nan,6.2,np.nan,np.nan]}) mydf Out[134]: category date_ym values 0 A 2018-01 NaN 1 A 2018-01 4.0 2 A 2018-01 5.1 3 B 2018-01 NaN 4 A 2018-02 6.2 5 B 2018-02 NaN 6 B 2018-03 NaN If I use groupby and agg, I get the following output: mydf.groupby(['date_ym','category']).agg(['count', 'mean', 'median']).reset_index() Out[135]: date_ym category values count mean median 0 2018-01 A 2 4.55 4.55 1 2018-01 B 0 NaN NaN 2 2018-02 A 1 6.20 6.20 3 2018-02 B 0 NaN NaN 4 2018-03 B 0 NaN NaN But the output I'd really want is as follows: date_ym category values count countNAs mean median 0 2018-01 A 2 1 4.55 4.55 1 2018-01 B 0 1 NaN NaN 2 2018-02 A 1 0 6.20 6.20 3 2018-02 B 0 1 NaN NaN 4 2018-03 B 0 1 NaN NaN
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51109072
possible better answer: http://stackoverflow.com/a/51109302

http://stackoverflow.com/comment/89051465
has text: That's correct, it is related to dir(), I just observed while testing dir().
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51029551
type: Comment

http://stackoverflow.com/q/51108226
tagged with: windows
has body: I upgraded python from 32-bit version to the 64-bit one, I did this by uninstalling python using add or remove programs and installing a new one from the official installer. While doing so, I also upgraded it from python 3.6 to 3.7. Now when I try running pip I get the following error The code execution cannot proceed because python36.dll was not found. Reinstalling the program may fix this problem. It didn't. python -m pip works for me but I would still like to fix the original functionality.
tagged with: python
has comment: http://stackoverflow.com/comment/89203929
has title: Upgrading python from 32 bit to 64 bit messed up pip (Windows)
type: UnansweredQuestion
tagged with: pip
has answer: http://stackoverflow.com/a/54843975
type: Question
has comment: http://stackoverflow.com/comment/89203574
tagged with: python-3.6
score: 0
tagged with: python-3.7
answer count: 1
has comment: http://stackoverflow.com/comment/89203736

http://stackoverflow.com/comment/89092451
has text: Second one should be valid over all numbers, since the normalization constant is 2pi
score: 0
comment on: http://stackoverflow.com/q/51050658
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89061616
score: 0
comment on: http://stackoverflow.com/a/51034622
has text: @coldspeed yep I know what you mean, how about right now : -)
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51069334
tagged with: append
linked to: http://stackoverflow.com/q/16922214
has body: I am trying to parse through a file with consistent formatting: a header and several lines of text split by spacing. I want to start a new dictionary key when a line has one value, read the following lines into a list of lists with each list being the split words. I first tried to use this to try to get the program to identify the new marker and use an index counter to set a new key. I then initially used this to split the lines accordingly. Here is what my code currently looks like: import sys def openfile(file): frames = {} index = 0 with open(file, 'r') as f: for line in f: if line.strip() == '5310': index +=1 else: newline = line print newline frames[index] = [] frames[index].append([newline.split()]) print frames openfile(sys.argv[1]) The index will correctly count and 'print newline' is printing all of the lines that I want, but the dictionary that is finally printed is a nested list: {1:'last', 'line', 'of', 'input', 'file'} What I want instead is: {1:[[line1],[line2] ...], 2:[[nextline], [nextline] ...], ... , key n : [[line], [line]....[lastline]]} I have also tried: def openfile(file): frames = {} index = 0 with open(file) as f: for line in f: if str(line.strip()) == '5310': index += 1 else: frames[index] = [] frames[index].append([line.split()]) return frames This will also not work. This leaves me with two questions: 1: why will my current code print but not append the lines I want? 2. what else can I try to get this to work? edit Thanks! I managed to get it to work. If someone is having a similar issue, here's my code that works: import sys def openfile(file): frames = {} index = 0 with open(file, 'r') as f: for line in f: if line.strip() == '5310': index +=1 frames[index] = [] else: newline = line print newline frames[index].append([newline.split()]) print frames openfile(sys.argv[1])
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37473770
downvote count: 0
score: 1
has title: Python parsing file into dictionary of list of lists: for loop is only appending last line
type: Question
has answer: http://stackoverflow.com/a/51069607
accepted answer: http://stackoverflow.com/a/51069607
has comment: http://stackoverflow.com/comment/89128591
tagged with: fileparsing
tagged with: for-loop
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89129072
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51143278
tagged with: apache-spark
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51147546
tagged with: sparse-matrix
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I have a PySpark dataframe with one of the columns (features) being a sparse vector. For example: +------------------+-----+ | features |label| +------------------+-----+ | (4823,[87],[0.0])| 0.0| | (4823,[31],[2.0])| 0.0| |(4823,[159],[0.0])| 1.0| | (4823,[1],[7.0])| 0.0| |(4823,[15],[27.0])| 0.0| +------------------+-----+ I would like to expand the features column and to add another feature to it, for example: +-------------------+-----+ | features |label| +-------------------+-----+ | (4824,[87],[0.0]) | 0.0| | (4824,[31],[2.0]) | 0.0| |(4824,[159],[0.0]) | 1.0| | (4824,[1],[7.0]) | 0.0| |(4824,[4824],[7.0])| 0.0| +-------------------+-----+ Is there a way to do this without unpacking the SparseVector to dense and then repacking it to sparse with the new column?
has answer: http://stackoverflow.com/a/51147546
type: Question
has title: Pyspark - add another column to a sparse vector column
tagged with: pyspark
tagged with: dataframe

http://stackoverflow.com/a/51067813
upvote count: 2
has comment: http://stackoverflow.com/comment/89126187
type: Answer
has body: There you go! I hope this will helps. &lt;?php $ingridients = array("Cheese", "Tomato", "Onion", "Pepperoni"); if (in_array("oni", $ingridients)) { echo "The letters 'oni' is available in the given ingredients"; } else { echo "The letters 'oni' is NOT available in the given ingredients"; } ?&gt;
score: 2
has comment: http://stackoverflow.com/comment/89126082
answers question: http://stackoverflow.com/q/51067701
has comment: http://stackoverflow.com/comment/89126386
downvote count: 0

http://stackoverflow.com/comment/89273257
score: 0
comment on: http://stackoverflow.com/q/51142617
type: Comment
type: QuestionComment
has text: i can handle that part i think. right now it's just a submit button.

http://stackoverflow.com/q/51021427
linked to: http://stackoverflow.com/q/29846087
answer count: 3
has body: when I am writing ' import scrapy ' to import this library in my python file, on running it is giving error "ModuleNotFoundError: No module named 'scrapy'" and i have also installed scrapy using pip install scrapy #enter code here import bs4 as bs import urllib.request import scrapy i = input('enter the item to be searched :') i = i.replace(" ","") sauce1 = urllib.request.urlopen('https://www.amazon.in/s/ref=nb_sb_noss? url=search-alias%3Daps&amp;field-keywords='+i).read() soup1 = bs.BeautifulSoup(sauce1,'lxml') s_url = [] ul_parent = soup1.find('div', class_='a-row s-result-list-parent-container') for url in ul_parent.find_all('a'): if "javascript" not in str(url.get('href')): s_url.append(str(url.get('href'))) print(s_url) what should I do to import scrapy as I want to extract items from Amazon website using "response.xpath". Please help Thank You
has comment: http://stackoverflow.com/comment/89035393
has answer: http://stackoverflow.com/a/51021746
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/51021645
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/89035460
has title: how to use 'import scrapy' in .py file
upvote count: 0
has answer: http://stackoverflow.com/a/51021711
favorite count: 0

http://stackoverflow.com/q/51134962
tagged with: hdfs
type: UnansweredQuestion
tagged with: python
has title: How to check file exists in HDFS using python
type: Question
tagged with: hadoop
has body: import subprocess def run_cmd(args_list): print('Running system command: {0}'.format(' '.join(args_list))) proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() return proc.returncode cmd = ['hadoop', 'fs', '-test', '-e', hdfs_file_path] code = run_cmd(cmd) if code: print 'file not exist' When I give this command to see whether file exists in HDFS, it is throwing me this error: RuntimeError: Error running command: hadoop fs -test -f /app/tmp/1.json. Return code: 1, Error: b'' How to resolve this issue?
score: 0
has answer: http://stackoverflow.com/a/51135038
answer count: 1

http://stackoverflow.com/q/51090580
type: Question
has answer: http://stackoverflow.com/a/51090825
has comment: http://stackoverflow.com/comment/89169607
has body: I'm using Pandas dataframe. And I have a dataFrame df as the following: time id ------------- 5:13:40 1 16:20:59 2 ... For the first row, the time 5:13:40 has no zero padding before, and I want to convert it to 05:13:40. So my expected df would be like: time id ------------- 05:13:40 1 16:20:59 2 ... The type of time is &lt;class 'datetime.timedelta'&gt;.Could anyone give me some hints to handle this problem? Thanks so much!
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51090825
tagged with: python
has comment: http://stackoverflow.com/comment/89169564
type: AnsweredQuestion
score: 0
has title: Pandas dataframe adding zero-padding before the datetime

http://stackoverflow.com/q/51022758
score: 0
type: Question
has answer: http://stackoverflow.com/a/51022946
answer count: 1
has body: There are these two dictionaries with the shapefile schemas from the Fiona library that eventually have their differences printed and I need to also provide which line belongs to which dictionary : from collections import OrderedDict from pprint import pprint &gt;&gt;&gt; d1 = {'properties': OrderedDict([('KAEK', 'str:12'), ... ('PROP_TYPE', 'str:4'), ... ('ORI_TYPE', 'int:1'), ... ('ORI_CODE', 'str:100'), ... ('DEC_ID', 'str:254'), ... ('ADDRESS', 'str:254'), ... ('NUM', 'str:9'), ... ('LEN', 'float:19.11'), ... ('AREA', 'float:19.11')]), ... 'geometry': 'Polygon'} &gt;&gt;&gt; d1 = d1['properties'] &gt;&gt;&gt; d2 = {'properties': OrderedDict([('OBJECTID_1', 'int:9'), ... ('OBJECTID', 'int:9'), ... ('FID_PERIVL', 'int:9'), ... ('DESC_', 'str:254'), ... ('PROP_TYPE', 'str:4'), ... ('Shape_Leng', 'float:19.11'), ... ('Shape_Le_1', 'float:19.11'), ... ('Shape_Area', 'float:19.11'), ... ('PARCEL_COD', 'str:254'), ... ('KAEK', 'str:50'), ... ('NUM', 'int:4'), ... ('DEC_ID', 'int:4'), ... ('ADDRESS', 'int:4'), ... ('ORI_CODE', 'int:4'), ... ('ORI_TYPE', 'int:4')]), ... 'geometry': 'Polygon'} &gt;&gt;&gt; d2 = d2['properties'] And I want the results to show from which dictionary originate in this final part where are listed the symmetric differences:See comments to see what I plan to do. pprint(set.symmetric_difference(set(d1.items()), set(d2.items()))) {('ADDRESS', 'int:4'),#somehow inform that this belongs to d2 and so on... ('ADDRESS', 'str:254'),#d1 ('AREA', 'float:19.11'),#d1 ('DEC_ID', 'int:4'),#d2 ('DEC_ID', 'str:254'), ('DESC_', 'str:254'), ('FID_PERIVL', 'int:9'), ('KAEK', 'str:12'), ('KAEK', 'str:50'), ('LEN', 'float:19.11'), ('NUM', 'int:4'), ('NUM', 'str:9'), ('OBJECTID', 'int:9'), ('OBJECTID_1', 'int:9'), ('ORI_CODE', 'int:4'), ('ORI_CODE', 'str:100'), ('ORI_TYPE', 'int:1'), ('ORI_TYPE', 'int:4'), ('PARCEL_COD', 'str:254'), ('Shape_Area', 'float:19.11'), ('Shape_Le_1', 'float:19.11'), ('Shape_Leng', 'float:19.11')} Simply,classify them by name of dictionary.…
accepted answer: http://stackoverflow.com/a/51022946
has title: Show from which dictionary each line is?
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/a/51048255
score: 0
has body: Just in case anyone was following this action, I figured it out and thought I would share the answer. The FindCell function was what I came up with, although there is probably a much more elegant way to do this. def run_analysis(): excel = Dispatch('Excel.Application') excel.DisplayAlerts = False x = 0 t = data_file_location_list while x &lt; len(t): # MATCHES ROW AND COL INPUT FOR CELL ADDRESS OUTPUT def FindCell(descriptor, banner): return(ws.Cells(excel.WorksheetFunction.Match(descriptor, ws.Range("B:B"), 0), excel.WorksheetFunction.Match(banner, ws.Range("A:A"), 0)).Address) try: print 'opening: ' + t[x].root_dir + "\\" + t[x].file_name wb = excel.Workbooks.Open(t[x].root_dir + "\\" + t[x].file_name) ws = wb.Sheets('Bandwidth Over Time') #find the cell below the cell containing "Total Traffic" total_traffic_calc_range = FindCell("Traffic", 'Bandwidth Over Time') total_traffic_calc_range_delimiter = int(total_traffic_calc_range.strip('$A$')) total_traffic_equation_cell = "C" + str(total_traffic_calc_range_delimiter) #add the equations for calculation ws.Range(total_traffic_equation_cell).Value = '=Sum(' + 'B' + str( total_traffic_calc_range_delimiter + 1) + ':B' + str( total_throughput_calc_range_delimiter - 2) + ')' wb.SaveAs(Filename = str(t[x].root_dir + "\\" + t[x].file_name)) except Exception as e: print e finally: wb.Close() excel.Quit() print x x += 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51032411
accepted answer of: http://stackoverflow.com/q/51032411
type: Answer

http://stackoverflow.com/a/51119424
has comment: http://stackoverflow.com/comment/89325369
answers question: http://stackoverflow.com/q/51117776
has comment: http://stackoverflow.com/comment/89327534
upvote count: 4
has body: Here's a reasonably efficient algorithm. It's ok on small data sets, but it will take time &amp; RAM for larger data sets. I won't claim it's the best algorithm, but it's certainly much better than brute-force checking each good - bad pairing. The key insight is that we don't need to look at the individual good - bad pairings, we can look at the total good - bad score of whole teams. Let the scores for two valid teams be (X, A) and (Y, B). That is, X is the total score of all the good players in team 1 and A is the total score of all the bad players in team 1. Similarly, Y is the score of the good players in team 2 and B is the score of the bad players in that team. Then X - A = Y - B X + B = Y + A 2(X + B) = X + B + Y + A X + B = (X + B + Y + A) / 2 Let M = (X + Y + A + B) / 2 Thus B = M - X So we just need to calculate M, the total of all players' scores, and then for each good player partition X we need to see if there's a matching bad player partition B. (Incidentally, the arithmetic above shows that X + Y + A + B must be even for a solution to exist, since B &amp; X must be whole numbers). To do that with reasonable efficiency, we create a dict of the bad player partitions. The dict key is the total score for that partition, the associated value is a list of all bad player partitions with that score. Then we loop over the good player partition pairs. We find the total score for the 1st partition in a pair, subtract it from M to get the required bad score, and see if that bad score's in the dictionary. If it is, we've found a solution. The function equal_parts is the fastest way I know in pure Python to split a list into all of its equal length partitions, see this answer I wrote a couple of years ago for details. The code below finds a single solution for the data given in the question; that solution yields 2 options for each team. I've included some extra code (currently commented out) to generate some random fake data in order to test the code on a larger dat…
downvote count: 0
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89262535
has comment: http://stackoverflow.com/comment/89284170
has comment: http://stackoverflow.com/comment/89289186
has comment: http://stackoverflow.com/comment/89262835
type: Answer
has comment: http://stackoverflow.com/comment/89260684
accepted answer of: http://stackoverflow.com/q/51117776
has comment: http://stackoverflow.com/comment/89327587

http://stackoverflow.com/q/51123275
has comment: http://stackoverflow.com/comment/89232776
has body: I am working on excel sheet: animal name age dog puppy 1 dog doggy 2 dog snooppy 3 cat pussy 1 pig piggy 1 pig cutty 2 rabit robby 1 rabbit bunny 2 Here I should check if animal age is 1 should delete that row and print next row and remove duplicates if there are no duplicates, should print that row and this output should print in other excel sheet. Can any help me out of this? import imatplotlib.pyplot as plt import pandas as pd data = pd.read_excel(r"C:\Users\c_ssaiva\Desktop\sampladata.xlsx") for index,row in data.iterrows(): print(index,row['animal'],row['name'],row['age']) for j,row in data.iterrows(): if a[i] == a[j]: if a[i] == 1 print a[j] else: print (a[i]) df = data df.to_excel(r"C:\Users\c_ssaiva\Desktop\selcol.xlsx")
answer count: 2
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/89231732
linked to: http://stackoverflow.com/q/23667369
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89237119
has comment: http://stackoverflow.com/comment/89232793
has title: How to remove duplicates from Excel file using pandas
has comment: http://stackoverflow.com/comment/89231659
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/72746401
score: -1
has answer: http://stackoverflow.com/a/51123453

http://stackoverflow.com/q/51067664
duplicate of: http://stackoverflow.com/q/1207406
has answer: http://stackoverflow.com/a/51067876
type: Question
has answer: http://stackoverflow.com/a/51067844
has comment: http://stackoverflow.com/comment/89125343
has comment: http://stackoverflow.com/comment/89125435
has comment: http://stackoverflow.com/comment/89125281
has comment: http://stackoverflow.com/comment/89125472
score: 0
has answer: http://stackoverflow.com/a/51067855
has title: Why my if statement gives false negatives?
tagged with: python
answer count: 4
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51067881
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1207406
tagged with: if-statement
has body: I want to iterate over a list of files in Python 3. They are CSV files containing matrices. I want to do the same with all of them so I wanted to create a list with their names, remove all other files in the folder from the list and do my transformation with the relevants. My target files all end with "2m.csv" (e.g.: 14-17_CCK_all_2m.csv) and my results at the end of the process will end with "1m.csv". Still when I run the following script in Jupyter notebook, the result contains some files ending with "1m.csv" (they remained there from an earlier cycle of the development) import os myfiles = os.listdir() for item in myfiles: if item[-6:] != "2m.csv": myfiles.remove(item) Interestingly, if I test one of the false negatives in a separate lines, I get a True answer, so the if statement should have eliminated it from my list in the script above - which it did with some of them, but not with some others: myfiles[1][-6:] != "2m.csv" &gt;&gt;&gt; True All the files in question have very similar name structure. Thanks for your help.

http://stackoverflow.com/comment/89140583
has text: Hi BcK, this is an interesting approach. How would I go about doing reverse deletion if I wanted to remove any random index within the length of the list?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51075737
type: Comment

http://stackoverflow.com/comment/96223414
has text: This answer is no longer accurate, see my answer.
comment on: http://stackoverflow.com/a/51089448
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51117963
favorite count: 0
accepted answer: http://stackoverflow.com/a/51117988
has comment: http://stackoverflow.com/comment/89222007
has body: I have a text.csv file with 6 columns. I want 2 columns read in as dates for later differences. However, I only get ONE column coming back as a datetime. Any ideas? Also, I have several empty dates that return nan NOT 0(zeros) as in na_values = 0?? import pandas as pd CSV = 'text.csv' df = pd.read_csv(CSV, skiprows = 0, na_values = 0, parse_dates = ['Date of Sign Up', 'Birth Date'], usecols = ['Date of Sign Up', 'A', 'B', 'C', 'D', 'Birth Date']) df.info() # Check info for column types and nan... RangeIndex: 969 entries, 0 to 968 Data columns (total 6 columns): Date of Sign Up 969 non-null datetime64[ns] A 969 non-null object B 969 non-null object C 969 non-null object D 969 non-null object Birth Date 969 non-null object ## &lt;== Why doesn't this column read as datetime? dtypes: datetime64[ns](1), object(5) memory usage: 45.5+ KB
tagged with: python
has comment: http://stackoverflow.com/comment/89222318
has answer: http://stackoverflow.com/a/51117988
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89222303
type: Question
has comment: http://stackoverflow.com/comment/89221995
has title: Would like to read in Two columns of dates but only get One
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89222059
answer count: 1
has comment: http://stackoverflow.com/comment/89222371

http://stackoverflow.com/comment/89301588
has text: does not matter, a random string, it is just to get every list with the same length!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51156042

http://stackoverflow.com/a/51048656
score: 0
answers question: http://stackoverflow.com/q/51048628
type: Answer
has comment: http://stackoverflow.com/comment/89088553
has body: You have extra indentation from if __name__ == '__main__': line. Look at this updated code: class Car: def __init__(self): self.speed = 0 self.odometer = 0 self.time = 0 def say_state(self): print("I'm going {} kph!".format(self.speed)) def accelerate(self): self.speed += 5 def brake(self): self.speed -= 5 def step(self): self.odometer += self.speed self.time += 1 def average_speed(self): return self.odometer / self.time if __name__ == '__main__': my_car = Car() print("I'm a car!") while True: action = input("What should I do?[A]ccelerate,[B]rake, show [O]dometer, or show average [S]peed?").upper() if action not in "ABOS" or len(action) != 1: print("I don't know thow to do that") continue if action == 'A': my_car.accelerate() elif action == 'B': my_car.brake() elif action == 'O': print("The car has driven {} kilometers".format(my_car.odometer)) elif action == 'S': print("The car's average speed was {} kph".format(my_car.average_speed())) my_car.step() my_car.say_state()
has comment: http://stackoverflow.com/comment/89088420

http://stackoverflow.com/comment/89172962
type: QuestionComment
comment on: http://stackoverflow.com/q/51092302
has text: Possible duplicate of [PyQT: how to open new window](https://stackoverflow.com/questions/36768033/pyqt-how-to-open-new-window)
score: 2
type: Comment

http://stackoverflow.com/comment/89104265
type: Comment
score: 1
has text: I didn't get your question. This code doesn't contain comments. By any chance you missed `"` after the # sign?
comment on: http://stackoverflow.com/q/51056840
type: QuestionComment

http://stackoverflow.com/a/51077262
has comment: http://stackoverflow.com/comment/121186099
score: 3
has body: You can use DTExec to run the SSIS package. You basically launch an external process to run the package. You can execute packages that are stored on the SQL Server as well as packages that are on he filesystem. It's a pretty flexible tool with command line arguments to support many scenarios.
has comment: http://stackoverflow.com/comment/89143609
answers question: http://stackoverflow.com/q/51077064
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51077064
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/89143319

http://stackoverflow.com/q/51051625
has title: Holoviews graph visualization: setting position based on attribute
tagged with: networkx
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/89094614
tagged with: bokeh
has answer: http://stackoverflow.com/a/51066003
score: 0
has body: When plotting a network in Holoviews, how can I set the position of the nodes based on an attribute? I have a network with timestamps for each node, and would like to position the nodes based on the associated time.
answer count: 1
tagged with: holoviews
tagged with: python
has comment: http://stackoverflow.com/comment/89121892
type: UnansweredQuestion

http://stackoverflow.com/comment/89264412
comment on: http://stackoverflow.com/q/51138424
has text: @nneonneo Thank you, that makes much more sense. I was over complicating things :)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51107968
answer count: 2
score: 5
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51504929
upvote count: 6
has title: Change 3D background to black in matplotlib
has answer: http://stackoverflow.com/a/51109329
type: UnansweredQuestion
downvote count: 1
tagged with: mplot3d
type: Question
tagged with: matplotlib
has body: I'm having trouble changing the background of my 3d graph to black. This is my current code. When I do set facecolor to black, it changes the inside of the graph to be grey, which is not what I want. fig = plt.figure() fig.set_size_inches(10,10) ax = plt.axes(projection='3d') ax.grid(False) ax.xaxis.pane.set_edgecolor('b') ax.yaxis.pane.set_edgecolor('b') ax.zaxis.pane.set_edgecolor('b') # plt.gca().patch.set_facecolor('white') # plt.axis('On') fig.patch.set_facecolor('black') ax.scatter(xs = Z['PC1'], ys = Z['PC2'], zs = Z['PC3'], c = Z['color'], s = 90, depthshade= False) ax.set(title = 'test', xlabel = 'PC1', ylabel = 'PC2', zlabel = 'PC3')

http://stackoverflow.com/comment/89152503
type: QuestionComment
has text: Thanks for your reply, but in reality, the class is in a lib file. I past my code to simplify like this. It's a error when we execut it from stackOverflow but, on my side, it's not comming from this part.
comment on: http://stackoverflow.com/q/51061898
score: 0
type: Comment

http://stackoverflow.com/a/51025355
has comment: http://stackoverflow.com/comment/89043494
type: Answer
has comment: http://stackoverflow.com/comment/89043318
has comment: http://stackoverflow.com/comment/89043575
has comment: http://stackoverflow.com/comment/89043612
has comment: http://stackoverflow.com/comment/89044013
score: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/89043462
upvote count: 4
answers question: http://stackoverflow.com/q/51025302
has body: You may use this regex with a negative lookahead and a capture group: ({{(?:(?!{{|}})[^-])*)-(.*?}}) RegEx Demo RegEx Details: (: Start capture group {{: Match {{ (?:: Start non-capture group (?{{|!}}): Negative lookahead to assert that we don't have {{ and }} at next position [^-]: Match any character except hyphen )*: End non-capture group. * matches 0+ instances of this group ): End capture group -: Match literal hyphen (.*?}}): Match remaining string up to }} and then match }} and capture this in 2nd capture group
has comment: http://stackoverflow.com/comment/89044120
has comment: http://stackoverflow.com/comment/89043962
has comment: http://stackoverflow.com/comment/89043521

http://stackoverflow.com/q/51130317
favorite count: 0
has title: How to make a timer more efficient
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 3
tagged with: performance
has body: I am quite new to coding and i am wondering how to make it more efficient. I am running it on a raspberry pi which will have other tasks so i want this to be as easy to run as possible. The code will use a magnetic sensor to record passes made by a magnet mounted on a wheel and from there determine the speed of the outside diameter of the wheel. It would be useful to implement something that takes the five last speed outputs and gives sort of an average but only if it does not affect the complexity of the code much. Would be really greatful for any help! from gpiozero import Button import time global t0 t0 = time.clock() raduis = 300 button = Button (21) from signal import pause def calculate_speed(radius): global t0 t1 = time.clock interval = t1 - t0 speed = radius/interval print (speed, 'mm/sek') y = True while y == True: button.when_pressed = calculate_speed(radius) time.sleep(0.2) #used to prevent one pass of the magnet from recording many passes
downvote count: 0
has comment: http://stackoverflow.com/comment/89247089
type: Question
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/51131626
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/89249949
upvote count: 3
answer count: 2
has comment: http://stackoverflow.com/comment/89247055
has answer: http://stackoverflow.com/a/51131244

http://stackoverflow.com/q/51144062
type: AnsweredQuestion
has body: I want to have my tests in a separate folder from my package code, such that from the top level directory of my project I can run python sample/run.py or python tests/test_run.py, and have both of them resolve all the imports properly. My directory structure looks like this: sample/ __init__.py helper.py run.py tests/ context.py test_run.py I know there are supposedly many ways to achieve this, as discussed here: Python imports for tests using nose - what is best practice for imports of modules above current package However, when I try to run python tests/test_run.py, I get a ModuleNotFoundError for 'helper', because 'sample/run.py' imports 'sample/helper.py'. In particular, I am trying to follow the convention (suggested in the Hitchhiker's Guide to Python) of explicitly modifying the path using: import os, sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) As a result, I have a blank sample/__init__.py, along with the following code files. sample/run.py: from helper import helper_fn def run(): helper_fn(5) return 'foo' if __name__ == '__main__': run() sample/helper.py: def helper_fn(N): print(list(range(N))) tests/context.py: import os, sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import sample tests/test_run.py: from context import sample from sample import run assert run.run() == 'foo' So I have two questions: Why is Python unable to find the 'helper' module? How do I fix things so that I can run both sample/run.py and tests/test_run.py from the top-level directory?
has title: Python imports for testing modules with additional dependencies
type: Question
has comment: http://stackoverflow.com/comment/89272406
tagged with: testing
tagged with: python-import
linked to: http://stackoverflow.com/q/6670275
has answer: http://stackoverflow.com/a/51144213
score: 0
accepted answer: http://stackoverflow.com/a/51144213
answer count: 1
has comment: http://stackoverflow.com/comment/89272373
tagged with: python-3.x
linked to: http://stackoverflow.com/q/6323860
tagged with: python

http://stackoverflow.com/comment/89199000
comment on: http://stackoverflow.com/q/51101217
has text: I'm very pre-occupied right now! Can I take more time to explain to you? If you liked my answer, and you're satisfied and it achieved what you want, feel free to TICK it and upvote! Because it really helps me out too!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/139361733
score: 0
type: AnswerComment
has text: The LLVM patch mentioned in OP has been reworked and merged in June 2024. See https://github.com/llvm/llvm-project/pull/98489. So `cursor.spelling` now does the same job, returning e.g. `&&`. Or we can use the newly added `cursor.binary_operator` which returns e.g. `BinaryOperator.LAnd`.
type: Comment
comment on: http://stackoverflow.com/a/64871498

http://stackoverflow.com/comment/89239350
has text: can you add this to your question ...
type: QuestionComment
comment on: http://stackoverflow.com/q/51126973
score: 0
type: Comment

http://stackoverflow.com/comment/89128534
comment on: http://stackoverflow.com/q/51068931
type: Comment
type: QuestionComment
score: 0
has text: They are working as documented. empty rows and columns have a size of zero.

http://stackoverflow.com/q/51109827
upvote count: 1
tagged with: python
tagged with: dictionary
has title: How to exclude repeated keys in dictionary of dictionaries when reading a csv file?
has body: I have made a code so far that reads a csv file and returns the data in the form of nested dictionaries. The first column of the table in the csv file holds the keys and its keys values are the values of the same row. I want to transform my code so it can exclude a key and its values if it is subsequently repeated in this column with the same string name. For example, if I have twice the string "Name" in a column I want to exclude the first "Name" as a key field and replace it (along with all its values) by the subsequent "Name" which may be some lines after. My code so far: def dict_of_dicts (filename, keyfield): tabledict= {} with open (filename, "rt", newline='') as csv_file: csvreader=csv.DictReader(csv_file, skipinitialspace=True) for row in csvreader: tabledict[row[keyfield]]=row return tabledict
score: 1
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89206963
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51112999
has comment: http://stackoverflow.com/comment/89206839
type: UnansweredQuestion

http://stackoverflow.com/a/51128020
answers question: http://stackoverflow.com/q/51126621
type: Answer
has body: Yep this worked. Had to re-add the import csv at the top and I'll change the page variable so that it'll from my csv that has a list of urls, but the output works. It puts both team names into their own rows. Thanks so much!
score: 0

http://stackoverflow.com/q/51152036
has title: Load QTableWidgets in a Scroll Area on Button Push
answer count: 1
has body: I have a method named 'test()' that loads 3 one-row tables into a scrollbar. For some reason that I cannot figure out, however, the while it works if I simply activate test() on load, it doesn't work if I comment it out and then try to activate it via the push of a button. Here is the main module (with test()) from PyQt5 import QtCore, QtWidgets from design import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) #test(self) def test(self): from random import randint x = randint(0, 99) print(x) height = 30 yPos = 0 for i in range(3): rowVals = ['test%s' % str(x + i)] qTbl = QtWidgets.QTableWidget(self.sawDoc) qTbl.setObjectName("tbl%s" % (i)) qTbl.setGeometry(QtCore.QRect(0, yPos, 880, height)) qTbl.horizontalHeader().setVisible(False) qTbl.verticalHeader().setVisible(False) yPos += height qTbl.setRowCount(1) qTbl.setColumnCount(len(rowVals)) for r, cell in enumerate(rowVals): item = QtWidgets.QTableWidgetItem() item.setText(str(cell)) qTbl.setItem(0, r, item) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) And here is the design module (with the button) from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(896, 453) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.scrDoc = QtWidgets.QScrollArea(self.centralwidget) self.scrDoc.setGeometry(QtCore.QRect(0, 0, 891, 391)) self.scrDoc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scrDoc.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.scrDoc.setWidgetResizable(False) self.scrDoc.setObjectName("scrTest") self.sawDoc = QtWidgets.QWidget() self.sawDoc.setGeometry(QtCore.QRect(0, 0, 869, 300)) self.sawDoc.setObjectName("sawDoc") sel…
has answer: http://stackoverflow.com/a/51152528
tagged with: pyqt
type: AnsweredQuestion
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51152528
score: 0
tagged with: pyqt5

http://stackoverflow.com/q/51089099
tagged with: python
has answer: http://stackoverflow.com/a/51089515
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89166882
has comment: http://stackoverflow.com/comment/89167267
has comment: http://stackoverflow.com/comment/89166592
type: Question
has title: unittest's assert.equal returning not failing when it should
accepted answer: http://stackoverflow.com/a/51089515
score: 0
answer count: 1
has body: The function get_full_name capitalizes the first and last name and returns the full_name as below: full_name = first + ' ' + last full_name = full_name.title() The following piece of code should fail but is passing. I'm using unittest. formatted_name = get_full_name('janis', 'joplin') self.assertEqual(formatted_name, 'anis Joplin') The unittest output is as below: Ran 0 tests in 0.000s OK Why is this test passing when it should fail? The full code is posted below: Here's the complete code for your review: import unittest def get_full_name(first, last): full_name = first + ' ' + last full_name = full_name.title() return full_name class NamesTestCase(unittest.TestCase): def test_first_last_name(self): formatted_name = get_full_name('janis', 'joplin') self.assertEqual(formatted_name, 'anis Joplin',) unittest.main()

http://stackoverflow.com/q/51013938
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51013960
type: Question
tagged with: rename
answer count: 2
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89020658
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51013971
tagged with: python
has body: I am new to coding and Pandas any help would be much appreciated. I have a column I wish to rename values Locations A-00-UD, A-01-UD, A-02-UD would = Audit, T-00-UD , T-02-UD, T-03-UD would = Transit and all other values would = stock. The problem I have is naming all the other values as Stock as in the full data-frame column is 15,000 lines long and has hundreds of different locations I wish to name stock. Location A-00-UD A-01-UD A-02-UD A-03-UD T-00-UD T-01-UD T-02-UD T-03-UD A-45-TR S-30-RT D-20-ED V-00-LM
has title: Pandas Rename one column Values when not equal to multiple conditions

http://stackoverflow.com/comment/89293715
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51155235
type: Comment
has text: Minor improvement: Don't use `dict` constructor + genexpr, just use a dict comprehension. `d = {v: i for i,v in enumerate(string.lowercase, 1)}`.

http://stackoverflow.com/comment/89185149
has text: @Sraw - the first one , I will edit the question
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51098782

http://stackoverflow.com/q/51111611
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89224346
has body: I am working on a machine learning project and I just set up a google cloud account. I have a VM instance up and running and Jupyter is working. I placed a couple of file folders on Google Cloud Storage assuming I could connect it to my VM and use the files in a Jupyter notebook running Python 3. I have not been able to find a way to access the files in storage from my virtual machine. Someone help please!?
favorite count: 0
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51119160
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89218126
has title: Using Google Cloud Storage Files with Jupyter Notebook on Cloud Compute
has comment: http://stackoverflow.com/comment/89210249
score: 4
has comment: http://stackoverflow.com/comment/89406761
tagged with: google-cloud-storage
upvote count: 4
tagged with: google-cloud-platform

http://stackoverflow.com/comment/89267741
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51141637
type: AnswerComment
has text: @sprogissd: Use a dict.

http://stackoverflow.com/comment/89279357
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51147176
has text: @Onyambu sorry I misplaced `,` instead of `.`. The Italian system doesn't help...
type: QuestionComment

http://stackoverflow.com/comment/89264878
comment on: http://stackoverflow.com/a/51139890
type: AnswerComment
score: 0
has text: @Gozie you have to check if authenticate method worked check this example https://docs.djangoproject.com/en/2.0/topics/auth/default/#authenticating-users
type: Comment

http://stackoverflow.com/comment/89148361
comment on: http://stackoverflow.com/a/51079320
has text: Sorry but I have this message: webDriverwait is not defined
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51079677
answers question: http://stackoverflow.com/q/51074956
has comment: http://stackoverflow.com/comment/89185629
upvote count: 1
has body: If you need GUI automation inside RDP window, you have to install pywinauto on remote machine and run the script there. This is true for any GUI automation tool because RDP or any other remote client doesn't provide GUI elements info to local machine. More details on what should be used is posted here: pywin32 / pywinauto not working properly in remote desktop when it is minimized Very useful thread is here: https://github.com/pywinauto/pywinauto/issues/401 Just need some time to compile all this knowledge into well structured document.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51038878
has body: I am training a model with data from multiple .csv files and I find that my code reads through the files but the model still trains on a single one. The relevant parts of my code are: def get_data(datasets_path): ''' Returns the dataframes. ''' full_path = datasets_path + "*.csv" for data_fname in glob.glob(full_path): df = pd.read_csv(data_fname) processed_df = __preprocessor(df) scaler = MinMaxScaler() transformed_df = scaler.fit_transform(processed_df) return transformed_df def batch_generator(X, batch_size=16, shuffle=False): ''' Return a random sample from X. ''' count = 0 while True: if shuffle: idx = np.random.randint(0, X.shape[0], batch_size) data = X[idx] else: indices = list(n for n in range(X.shape[0])) data = X[indices[count*batch_size : (count+1)*batch_size]] count +=1 yield (data, data) and data = get_data(path_to_datasets) x_train, x_test = train_test_split(data, test_size=0.2, random_state=42, shuffle=False) x_train = np.expand_dims(x_train, axis=1) x_test = np.expand_dims(x_test, axis=1) train_gen = batch_generator(x_train, batch_size=32) valid_gen = batch_generator(x_test, batch_size=32) then I define a simple model and train it with model.fit_generator( generator=train_gen, epochs=1, steps_per_epoch=x_train.shape[0] // 32, validation_data=valid_gen, validation_steps=x_test.shape[0] // 32) The problem is that this seems to train from a single .csv file and not go through all of them, and I don't understand why.
type: Question
tagged with: dataframe
has title: Generator will not go through all files
score: 0
answer count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/51041036
accepted answer: http://stackoverflow.com/a/51041036
tagged with: python
tagged with: generator
type: AnsweredQuestion

http://stackoverflow.com/comment/89181450
score: 1
comment on: http://stackoverflow.com/q/51096356
type: Comment
type: QuestionComment
has text: Dont know for sure, but it might be a lineending problem in the file. I guess that the line ends with DOS lineendings and the cygwin bash sees the carriage return as part of the filename, so "email_script.py" is seen as email_script.py\r". In the second version the carriage return "belongs" to `$1`. I suggest trying to save the script with Unix-Lineendings. The error mesage ending with `'email_script.py` (note the missing second quote) might hint that there is a linebreak after the .py and the bash thinks that character is part of the filename.

http://stackoverflow.com/q/51129987
score: 0
has answer: http://stackoverflow.com/a/51130275
downvote count: 1
has comment: http://stackoverflow.com/comment/89244806
tagged with: python
has comment: http://stackoverflow.com/comment/89244798
type: AnsweredQuestion
has title: Python 3.65 Anaconda Jupyter Object not being recognized from previous cells
has comment: http://stackoverflow.com/comment/89245027
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51130275
has body: In one cell, I am importing data from a .csv file into a pandas DataFrame. Then, in the next cell of the notebook, I am running a default function, .head(), which shows the first 5 entries. However, I am getting an error saying: name 'samples' is not defined My code: In[3]: %%timeit df201801F = pd.read_csv('01.csv') df201802F = pd.read_csv('02.csv') df201803F = pd.read_csv('03.csv') df201804F = pd.read_csv('04.csv') df201805F = pd.read_csv('05.csv') sample201801F = df201801F.sample(n) sample201802F = df201802F.sample(n) sample201803F = df201803F.sample(n) sample201804F = df201804F.sample(n) sample201805F = df201805F.sample(n) samples = pd.concat([df201801F, df201802F, df201803F, df201804F, df201805F]) In[4]: samples.head() In[4] doesn't run. Any ideas why?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89244945
favorite count: 0

http://stackoverflow.com/q/51139470
score: 0
has body: TL;DR I'm getting a timeout error on production: OperationalError: (QueryCanceledError) canceling statement due to statement timeout CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."tableY" x WHERE $1 OPERATOR(pg_catalog.=) "tableX_id" FOR KEY SHARE OF x" 'DELETE FROM tableX WHERE tableX.id = %(id)s' {'id': 42} and the main cause is SELECT 1 FROM ONLY "public"."tableY" x, because there's no index by the field tableX_id. I'm trying to figure out where this query comes from, I don't need this check. Full explaination I have 2 tables, tableX and tableY, and relation defined in TableY in sqlalchemy as: class TableY(Base): ... tableX = relationship( 'TableX', backref=backref( 'rows_y', uselist=True, lazy='dynamic', ), uselist=False, ) and in SQL as create table if not exists tableY ( ... tableX_id integer not null constraint fk_tableX_id_tableY references state_purchase on update cascade on delete restrict, ) I'm trying to remove a row from table tableX_obj.delete() SQLAlchemy is trying to delete also all related rows (with foreign key), so BEFORE doing the DELETE query it executes the SELECT id FROM tableY where tableX_id=42 but tableY is a many-to-many relationship table, so it doesn't have an index on tableX_id field - which leads to TIMEOUT. Creating index was not a good solution, because it will be useless: I'm sure that when I'm doing DELETE there will not be any related records, so I'll have pretty large index which will NOT contain any relevant information. It will contain just a garbage info. So, I wanted the DB to handle this situation and added passive_deletes=True state_purchase = relationship( 'StatePurchase', backref=backref( 'recommendations', uselist=True, lazy='dynamic', passive_deletes=True, ), uselist=False, ) It seemed to solve an issue, BUT now I'm getting new timeout error on production: OperationalError: (QueryCanceledError) canceling statement due to statement timeout CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."tableY" x WHERE $1 OPER…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/38112379
tagged with: python
tagged with: sqlalchemy
type: Question
answer count: 1
has title: SQLAlchemy is doing extra select when I'm trying to just remove a row
has answer: http://stackoverflow.com/a/51148155
tagged with: postgresql

http://stackoverflow.com/q/51061689
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51062284
tagged with: tensorflow
linked to: http://stackoverflow.com/q/16373510
type: Question
answer count: 2
downvote count: 0
tagged with: tflearn
has answer: http://stackoverflow.com/a/51062705
has title: Importing tflearn is very slow
accepted answer: http://stackoverflow.com/a/51062284
possible better answer: http://stackoverflow.com/a/51062705
has body: Importing tflearn takes a large amount of time compared to other modules. On a newly created virtual environment with only tflearn and minimal dependencies installed with pip: import numpy as np takes ~0.18s import tensorflow as tf takes ~0.90s import tflearn takes ~3.1s (and asks me to install h5py and scipy). After installing h5py and scipy as suggested, time consumed by import tflearn goes up to ~3.5s. How can I reduce importing time? (All tests above are done by putting the statement in test.py and run time python test.py several times. The reported time is the "real" time as reported by time builtin of bash.)
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89113597

http://stackoverflow.com/q/51144303
type: AnsweredQuestion
tagged with: data-conversion
type: Question
answer count: 2
has title: converting python list [1.] to [(1,)]
upvote count: 0
has answer: http://stackoverflow.com/a/51144309
has answer: http://stackoverflow.com/a/51144325
favorite count: 0
has comment: http://stackoverflow.com/comment/89272985
score: -3
possible better answer: http://stackoverflow.com/a/51144325
tagged with: python
tagged with: list
accepted answer: http://stackoverflow.com/a/51144309
has body: I have the following lists in python: a=[(0,) (0,) (0,) (0,) (0,) (0,) (0,) (0,) (0,) (0,)] b=[1. 1. 0. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 0. 0. 0. 1.] and I would like to convert b into the same format as a, but I can't figure out how to do this... Thanks in advance
downvote count: 3

http://stackoverflow.com/q/51019567
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89072899
has body: I have a Dataframe of 250 columns and 4562 rows. I want to use it in Julialang. I have tried using HDF5 to transfer the data but it gives an error reading the file. code: using HDF5 using DataFrames data=h5open("Database.h5") typeof(data) println("names \n",names(data)) println("\n dump") println(names(data)) m=data["nse"] println(names(m)) jj=m["table"] s=read(jj) This is the error I got: HDF5-DIAG: Error detected in HDF5 (1.10.2) thread 0: #000: H5O.c line 120 in H5Oopen(): unable to open object major: Object header minor: Can't open object #001: H5Oint.c line 553 in H5O_open_name(): unable to open object major: Object header minor: Can't open object #002: H5Oint.c line 589 in H5O_open_by_loc(): unable to determine object class major: Object header minor: Can't get value #003: H5Oint.c line 1575 in H5O_obj_class(): unable to load object header major: Object header minor: Unable to protect metadata #004: H5Oint.c line 889 in H5O_protect(): unable to load object header major: Object header minor: Unable to protect metadata #005: H5AC.c line 1763 in H5AC_protect(): H5C_protect() failed major: Object cache minor: Unable to protect metadata #006: H5C.c line 2565 in H5C_protect(): can't load entry major: Object cache minor: Unable to load metadata into cache #007: H5C.c line 6733 in H5C_load_entry(): invalid len with respect to EOA major: Object cache minor: Bad value #008: H5C.c line 6657 in H5C__verify_len_eoa(): len not positive after adjustment for EOA major: Object cache minor: Bad value String["_i_table", "table"] Any help is greatly appreciated!!
tagged with: python
accepted answer: http://stackoverflow.com/a/51023908
has title: transfer a data frame from python to julia
type: AnsweredQuestion
upvote count: 3
tagged with: hdf5
tagged with: julia
type: Question
score: 3
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89038178
has answer: http://stackoverflow.com/a/51023908
answer count: 1

http://stackoverflow.com/q/51061816
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/54428052
type: Question
tagged with: python-2.7
tagged with: vertica
answer count: 1
downvote count: 0
favorite count: 0
has body: I was using this code for 'COPY LOCAL' in python on Vertica 7.1: conn_info = {'host': '192.168.1.1', 'port': 5433, 'user': 'dbadmin', 'password': 'xxxxxx', 'database': 'db'} connection = vertica_python.connect(**conn_info) cur = connection.cursor() file_name="/tmp/tmp_file" temp_file = open(file_name,"w") temp_file .write(records) temp_file.close() os.system('gzip -cvf9 %s &gt; %s.gz'%(file_name,file_name)) qr="copy tmp_table(int_id, int_timestamp, ... ) from local '%s' GZIP delimiter ';' RECORD TERMINATOR E'\\r' NULL '\\N';"%(file_name+'.gz') cur.execute(qr) But i want to do same on Vertica 9.0.1 now and i got this error: Traceback (most recent call last): File "collector_as.py", line 264, in cur.execute(qr) File "/usr/local/lib/python2.7/dist-packages/vertica_python/vertica/cursor.py", line 126, in execute self.connection.process_message(self._message) File "/usr/local/lib/python2.7/dist-packages/vertica_python/vertica/connection.py", line 232, in process_message raise errors.MessageError("Unhandled message: {0}".format(message)) MessageError: Unhandled message: my vertica-python version: pip freeze | grep vertica --&gt; vertica-python==0.7.3 ------------------------ Also i tried new vertica-db-client from VERTICA (vertica-client-9.0.1-4.x86_64.tar.gz) my vertica-db-client version: pip freeze | grep vertica --&gt; vertica-db-client==9.0.1.4 and i got this error: Traceback (most recent call last): File "collector_as.py", line 265, in cur.execute(qr) NotSupportedError: COPY LOCAL is not supported
tagged with: python-3.x
has answer: http://stackoverflow.com/a/54428052
tagged with: python
has title: vertica-python Error on COPY LOCAL

http://stackoverflow.com/comment/89305511
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51160638
has text: At least give us the code which can be reproduced
type: Comment

http://stackoverflow.com/a/51084666
has comment: http://stackoverflow.com/comment/89161016
has comment: http://stackoverflow.com/comment/89173337
has body: The method originates from AbstractUser: class AbstractBaseUser(models.Model): @classmethod def normalize_username(cls, username): return unicodedata.normalize('NFKC', force_text(username)) This is logical, since if every function defined on a class, would simply be accessible by the name, this would result in completely unstable code. Imagine that you create a function send_email, and all of a sudden, your colleague also creates such function in a different class, then which function should be used? Python allows to write functions in a file (hence module) that are not bounded to a certain class, but then you still need to make sure which one you want. A good programming language is unambiguous, on the syntax level of course, but also in case a function is called, it should be clear what function is called. But you can make it more convenient, by importing the class itself. For example: from django.contrib.auth.models import User class UserProxy (User): foo = User.normalize_username ('abc') # OK bar = User.normalize_username ('abc') # OK class Meta: proxy = True
has comment: http://stackoverflow.com/comment/89161437
has comment: http://stackoverflow.com/comment/89161332
score: 0
answers question: http://stackoverflow.com/q/51084582
type: Answer
has comment: http://stackoverflow.com/comment/89161131

http://stackoverflow.com/a/51089161
has body: There are a couple probable reasons: You need to break (not continue) out of your inner loop once you've deleted the paragraph, otherwise you try to delete the same paragraph multiple times if it has more than one bold run. for j in range(0,len(document.paragraphs[i].runs)): if document.paragraphs[i].runs[j].bold == True: delete_paragraph(document.paragraphs[i]) length = length-1 break Your list of paragraphs is getting shorter each time you delete one, which changes the index of each paragraph that follows. If you traverse the paragraphs from bottom to top, that won't be a problem. Also, you can ditch all that (i, j) index management; Python rarely needs that. for paragraph in reversed(list(document.paragraphs)): for run in paragraph.runs: if run.bold: delete_paragraph(paragraph) break
has comment: http://stackoverflow.com/comment/89243067
type: Answer
accepted answer of: http://stackoverflow.com/q/51078706
answers question: http://stackoverflow.com/q/51078706
score: 0
has comment: http://stackoverflow.com/comment/89188855
has comment: http://stackoverflow.com/comment/89189676
has comment: http://stackoverflow.com/comment/89189989
type: AcceptedAnswer

http://stackoverflow.com/q/51068867
possible better answer: http://stackoverflow.com/a/51069032
tagged with: python
has answer: http://stackoverflow.com/a/51069032
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51069003
downvote count: 1
has comment: http://stackoverflow.com/comment/89127747
type: Question
upvote count: 4
has title: Trouble unpacking returned tuple during list comprehension
has body: I've got a function that takes input and returns a 3 item tuple: def f(a, b): x = a + 1 y = x + 2 z = y + 3 return (x, y, z) And I start with a set of tuples: my_set = {(1, 2), (3, 4), ... (m, n)} And I need to build a list, but the follow throws a TypeError: [(a, b, x, y, z, (x, y, z)) for a, b in my_set for x, y, z in f(a, b)] TypeError: 'int' object is not iterable I was reviewing this post which shows a similar process, but for some reason the for x, y, z ... is throwing the exception and I'm not sure if I am just overlooking something small or not.
has comment: http://stackoverflow.com/comment/89127785
has comment: http://stackoverflow.com/comment/89127627
has comment: http://stackoverflow.com/comment/89127716
has comment: http://stackoverflow.com/comment/89127691
has comment: http://stackoverflow.com/comment/89127833
has comment: http://stackoverflow.com/comment/89127695
answer count: 2
has comment: http://stackoverflow.com/comment/89127633
has comment: http://stackoverflow.com/comment/89127619
has answer: http://stackoverflow.com/a/51069003
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/28410577

http://stackoverflow.com/q/51141692
has answer: http://stackoverflow.com/a/51141752
has title: Calculations between different rows
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51141737
tagged with: dataframe
tagged with: rows
type: Question
answer count: 2
score: 0
tagged with: pandas
has body: I try to run loop over a pandas dataframe that takes two arguments from different rows. I tried to use .iloc and shift functions but did not manage to get the result i need. Here's a simple example to explain better what i want to do: dataframe1: a b c 0 101 1 aaa 1 211 2 dcd 2 351 3 yyy 3 401 5 lol 4 631 6 zzz for the above df I want to make new column ('d') that gets the diff between the values in column 'a' only if the diff between the values in column 'b' is equal to 1, if not the value should be null. like the following dataframe2: a b c d 0 101 1 aaa nan 1 211 2 dcd 110 2 351 3 yyy 140 3 401 5 lol nan 4 631 6 zzz 230 Is there any designed function that can handle this kind of calculations?

http://stackoverflow.com/q/51151523
type: Question
has comment: http://stackoverflow.com/comment/89286868
has comment: http://stackoverflow.com/comment/89286533
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89286517
favorite count: 0
linked to: http://stackoverflow.com/q/49793849
has body: I have only installed Python3.6 on my Mac. I have also installed miniconda. Whether I run the command: $python -V in my home directory, or a specific project directory, the output is Python 2.7.10. Why isn't it Python 3.6, and how can I change this default?
has comment: http://stackoverflow.com/comment/89286575
tagged with: bash
has answer: http://stackoverflow.com/a/51158417
has comment: http://stackoverflow.com/comment/89300850
tagged with: python
tagged with: macos
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51151738
score: 2
has title: When I type 'python -V' in my terminal...why do I see Python 2.7.10
has comment: http://stackoverflow.com/comment/89302224
tagged with: conda

http://stackoverflow.com/q/51061641
upvote count: 0
has answer: http://stackoverflow.com/a/51061767
has comment: http://stackoverflow.com/comment/89113171
type: Question
has comment: http://stackoverflow.com/comment/89113295
has title: How to solve this python error?
downvote count: 3
has body: Traceback (most recent call last): File "final.py", line 21, in lpd = LicensePlateDetector(image) TypeError: 'module' object is not callable I am actually running this program in two files first one consisting of this class functions from collections import namedtuple from skimage.filters import threshold_local from skimage import segmentation from skimage import measure from imutils import perspective import numpy as np import imutils import cv2 LicensePlate = namedtuple("LicensePlateRegion", ["success", "plate", "thresh", "candidates"]) class LicensePlateDetector: print("entered class") def __init__(self, image, minPlateW=60, minPlateH=20, numChars=7, minCharW=40): self.image = image self.minPlateW = minPlateW self.minPlateH = minPlateH self.numChars = numChars self.minCharW = minCharW def detect(self): lpRegions = self.detectPlates() for lpRegion in lpRegions: lp = self.detectCharacterCandidates(lpRegion) if lp.success: yield (lp, lpRegion) def detectCharacterCandidates(self, region): plate = perspective.four_point_transform(self.image, region) cv2.imshow("Perspective Transform", imutils.resize(plate, width=400)) V = cv2.split(cv2.cvtColor(plate, cv2.COLOR_BGR2HSV))[2] T = threshold_local(V, 29, offset=15, method="gaussian") thresh = (V &gt; T).astype("uint8") * 255 thresh = cv2.bitwise_not(thresh) plate = imutils.resize(plate, width=400) thresh = imutils.resize(thresh, width=400) cv2.imshow("Thresh", thresh) labels = measure.label(thresh, neighbors=8, background=0) charCandidates = np.zeros(thresh.shape, dtype="uint8") for label in np.unique(labels): if label == 0: continue labelMask = np.zeros(thresh.shape, dtype="uint8") labelMask[labels == label] = 255 cnts = cv2.findContours(labelMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] if len(cnts) &gt; 0: c = max(cnts, key=cv2.contourArea) (boxX, boxY, boxW, boxH) = cv2.boundingRect(c) aspectRatio = boxW / float(boxH) solidity = cv2.contourArea(c) / float(boxW * boxH…
has comment: http://stackoverflow.com/comment/89113069
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/q/51105648
answer count: 2
has answer: http://stackoverflow.com/a/51106906
has body: This seems so simple, but for the life of me I can't figure it out. I am new to Python and Seaborn, and I am doing all this online at PythonAnywhere. All I am trying to do is create a simple barplot in seaborn, with dates ordered properly (that is, ascending from left to right), on the x-axis. When I try this: import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime import pandas as pd import seaborn as sns emp = pd.DataFrame([[32, "5/31/2018"], [3, "2/28/2018"], [40, "11/30/2017"], [50, "8/31/2017"], [51, "5/31/2017"]], columns=["jobs", "12monthsEnding"]) fig = plt.figure(figsize = (10,7)) sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp, estimator = sum, ci = None) fig.autofmt_xdate() plt.show() I get this: Nice looking bar graph but with the dates ordered descending from left to right And then when I try to convert the objects to datetime: (note: i'm using pd.to_datetime() below in order to try and recreate what happens when I use parse_dates in pd.read_csv(), which is how I'm actually creating the dataframe.) emp = pd.DataFrame([[32, pd.to_datetime("5/31/2018")], [3, pd.to_datetime("2/28/2018")], [40, pd.to_datetime("11/30/2017")], [50, pd.to_datetime("8/31/2017")], [51, pd.to_datetime("5/31/2017")]], columns=["jobs", "12monthsEnding"]) fig = plt.figure(figsize = (10,7)) sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp, estimator = sum, ci = None) fig.autofmt_xdate() plt.show() I get this: Bar plot with the dates in the right order, but WRONG format I get the same bar plot, with the dates ordered properly, but in the full, long datetime format, with the time, etc. But all I want is the day/month/year. I've scoured stackoverflow for two days now and nothing has worked. I'm starting to wonder if part of the reason is because I'm working on PythonAnywhere. But I also can't find any reason why that would be. This is driving me nuts. Looking forward to any assistance. Thanks.
downvote count: 0
has answer: http://stackoverflow.com/a/77239784
tagged with: pandas
has comment: http://stackoverflow.com/comment/89200602
possible better answer: http://stackoverflow.com/a/77239784
tagged with: pythonanywhere
favorite count: 0
linked to: http://stackoverflow.com/q/56333790
accepted answer: http://stackoverflow.com/a/51106906
tagged with: seaborn
tagged with: python
has title: Ordering and Formatting Dates on X-Axis in Seaborn Bar Plot
type: AnsweredQuestion
score: 21
tagged with: matplotlib
upvote count: 21
type: Question

http://stackoverflow.com/comment/91842024
type: AnswerComment
has text: In utils where the Bot class is defined
type: Comment
comment on: http://stackoverflow.com/a/51128774
score: 0

http://stackoverflow.com/q/51042841
has title: Python: create csv from xml with different nested elements
has comment: http://stackoverflow.com/comment/89076884
has body: This is my xml file: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ccts="urn:oasis:names:specification:ubl:schema:xsd:CoreComponentParameters-2" xmlns:sdt="urn:oasis:names:specification:ubl:schema:xsd:SpecializedDatatypes-2" xmlns:udt="urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 UBL-Invoice-2.0.xsd"&gt; &lt;cbc:ID&gt;102165444&lt;/cbc:ID&gt; &lt;cac:InvoiceLine&gt; &lt;cbc:ID&gt;1.0000&lt;/cbc:ID&gt; &lt;cbc:Note /&gt; &lt;cbc:InvoicedQuantity unitCode="CT"&gt;1.0000&lt;/cbc:InvoicedQuantity&gt; &lt;cbc:LineExtensionAmount currencyID="DKK"&gt;142.3900&lt;/cbc:LineExtensionAmount&gt; &lt;cac:TaxTotal&gt; &lt;cbc:TaxAmount currencyID="DKK"&gt;138.24&lt;/cbc:TaxAmount&gt; &lt;cac:TaxSubtotal&gt; &lt;cbc:TaxableAmount currencyID="DKK"&gt;142.39&lt;/cbc:TaxableAmount&gt; &lt;cbc:TaxAmount currencyID="DKK"&gt;7.20&lt;/cbc:TaxAmount&gt; &lt;cac:TaxCategory&gt; &lt;cbc:ID schemeAgencyID="320" schemeID="urn:oioubl:id:taxcategoryid-1.1"&gt;3645&lt;/cbc:ID&gt; &lt;cac:TaxScheme&gt; &lt;cbc:ID schemeAgencyID="320" schemeID="urn:oioubl:id:taxschemeid-1.1"&gt;140&lt;/cbc:ID&gt; &lt;cbc:Name&gt;Afgift&lt;/cbc:Name&gt; &lt;cbc:TaxTypeCode listAgencyID="320" listID="urn:oioubl:codelist:taxtypecode-1.1"&gt;StandardRated&lt;/cbc:TaxTypeCode&gt; &lt;/cac:TaxScheme&gt; &lt;/cac:TaxCategory&gt; &lt;/cac:TaxSubtotal&gt; &lt;/cac:TaxTotal&gt; &lt;/cac:InvoiceLine&gt; &lt;cbc:ID&gt;2.0000&lt;/cbc:ID&gt; &lt;cbc:Note /&gt; &lt;cbc:InvoicedQuantity unitCode="CT"&gt;1.0000&lt;/cbc:InvoicedQuantity&gt; &lt;cbc:LineExtensionAmount currencyID="DKK"&gt;142.3900&lt;/cbc:LineExtensionAmount&gt; &lt;…
score: 0
tagged with: lxml
answer count: 1
tagged with: elementtree
accepted answer: http://stackoverflow.com/a/51109763
has comment: http://stackoverflow.com/comment/89084345
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89104003
tagged with: python
has answer: http://stackoverflow.com/a/51109763
type: AnsweredQuestion
tagged with: xpath
type: Question

http://stackoverflow.com/a/51055988
has body: Either: class Card: def __repr__(self): return self.__str__() Or convert your Card objects to string first: print([str(x) for x in hand.cards])
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51055696
answers question: http://stackoverflow.com/q/51055696
type: Answer
upvote count: 2

http://stackoverflow.com/a/51072417
type: Answer
accepted answer of: http://stackoverflow.com/q/51072205
downvote count: 0
answers question: http://stackoverflow.com/q/51072205
has comment: http://stackoverflow.com/comment/89134572
score: 2
upvote count: 2
type: AcceptedAnswer
has body: You can use pd.DataFrame.resample: df = df.resample('5Min', on='datetime').first()\ .drop('datetime', 1).reset_index() print(df) datetime value 0 2018-03-01 00:00:00 4.0 1 2018-03-01 00:05:00 NaN 2 2018-03-01 00:10:00 5.0 3 2018-03-01 00:15:00 NaN 4 2018-03-01 00:20:00 NaN 5 2018-03-01 00:25:00 NaN 6 2018-03-01 00:30:00 NaN 7 2018-03-01 00:35:00 NaN 8 2018-03-01 00:40:00 1.0

http://stackoverflow.com/q/51158652
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/51158919
type: Question
tagged with: python
has body: When you have your table columns type, how to test if they are of a particular type? types = {c.name: c.type for c in table.columns} for col_name, type_ in types.items(): print(col_name, type(type_), isinstance(VARCHAR, type(type_)), isinstance(type(type_), VARCHAR)) It always return lines like: REGION &lt;class 'sqlalchemy.dialects.mysql.types.VARCHAR'&gt; False False What is the correct method to test column type?
has title: Test SqlAlchemy column type
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/89228878
type: AnswerComment
comment on: http://stackoverflow.com/a/51121549
type: Comment
has text: @JackDaniel - Hard question, but it seems not.
score: 0

http://stackoverflow.com/comment/89428620
has text: how did you install it?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51155503
type: Comment

strftime
type: Tag
tags question: http://stackoverflow.com/q/51020781
tag name: strftime
tags question: http://stackoverflow.com/q/51110672

http://stackoverflow.com/comment/89325860
comment on: http://stackoverflow.com/a/51153885
type: AnswerComment
has text: Thanks, at the end I managed to do it following your path yesterday. Thanks anyway for the update.
type: Comment
score: 1

http://stackoverflow.com/comment/89118183
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51063969
has text: and also why adding layers inside loop?

http://stackoverflow.com/q/51103616
has answer: http://stackoverflow.com/a/51103896
has comment: http://stackoverflow.com/comment/89194738
tagged with: python
has comment: http://stackoverflow.com/comment/89194923
has comment: http://stackoverflow.com/comment/89194827
has comment: http://stackoverflow.com/comment/89194913
type: AnsweredQuestion
has title: JSON feed with unique IDs referenced using Python
accepted answer: http://stackoverflow.com/a/51103906
tagged with: http://stackoverflow.com/tag/json
has body: I am using Python to parse a JSON feed. The JSON feed updates every 30 seconds or so. I need to extract the information from match games but the unique ID node for the match game ID changes on each game. I have been able to parse the data I need by hard coding the uniqueID but when new games come into the feed, I will not know what the uniqueID is and therefore the code will fail. The below code does work but I need a way of looking up or wild-carding (which I know isn't possible in Python directly) the unique ID 1572805. import urllib2, cookielib, json, io import datetime url = "JSON URL - REMOVED" sportsFeed = r"c:\feeds\results.txt" try: scorepro = urllib2.urlopen(url) wjson = scorepro.read() wjdata = json.loads(wjson) today = str(datetime.datetime.today().strftime('%Y-%m-%d')) playerone = wjdata['list']['Sport']['2']['Matchday'][today]['Match']['1572805']['Home']['name'] print "playerone = " + playerone except: print "error" Below is an extract from the JSON where you can see each game's data is given a new uniqueID:- "timestamp":1530275075969, "list":{ "Sport":{ "2":{ "id":"2", "name":"TENNIS", "code":"TEN", "hid":"6268717", "Matchday":{ "2018-06-28":{ "date":"2018-06-28", "Match":{ "1572805":{ "ct":0, "id":"1572805", "lastPeriod":"Set4", "leagueCode":"43548", "leagueSort":0, "leagueType":"Tournament", "startTime":"10:05", "status":"Fin", "statustype":"fin", "type":2, "visible":"1", "Home":{ "id":"43095", "name":"BOLT A. (AUS)", "serve":"1", "seed":"", "standing":"" }, "Away":{ "id":"43035", "name":"KOKKINAKIS T. (AUS)", "serve":"0", "seed":"", "standing":"" }, "Results":{ "1":{ "id":"1", "name":"CURRENT", "value":"3-1" }, "Period":{ "1":{ "id":1, "name":"S1", "detail":"SCORE", "value":"7-6", "tiebreak":"8-6" }, "2":{ "id":2, "name":"S2", "detail":"SCORE", "value":"7-6", "tiebreak":"7-4" }, "3":{ "id":3, "name":"S3", "detail":"SCORE", "value":"4-6", "tiebreak":"" }, "4":{ "id":4, "name":"S4", "detail":"SCORE", "value":"7-5", "tiebreak":"" }, "5":{ "id":5, "name…
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51103906
has comment: http://stackoverflow.com/comment/89194676
possible better answer: http://stackoverflow.com/a/51103896

http://stackoverflow.com/q/51149314
has body: I m trying to resize a table widget inside a QVBoxlayout which I further add as a row to a QFormlayout in pyqt I m currently adding a QVboxlayout which contains a table widget inside it as a row in a Qformlayout. And the main aim is to strecth the Table widget till the end of the application window that it acquires the left over space on the window Using the below code - class PGSearchDetails(): def __init__(self,parent=None): self.widget_pgsd = QWidget() self.layout_pgsd = QFormLayout() self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1)) self.PG_Id = QLineEdit() #rx = QRegExp("^\\D+[!,@,#,$,%,\^,&amp;,*,(,),:,\",{,},?,&lt;,&gt;,|,+,-,~,]") #rx = QRegExp(" (?!(@,#,$|%|\^|&amp;|*|(|)|:|\"|{|}|?|&lt;|&gt;|\||+|-|~|!))[\\w]+") str_rx = QRegExp("^[A-Za-z*]{20}(?!@#$%^&amp;*():\"\{\}?&lt;&gt;\|+-~!_-)") adhr_rx = QRegExp("[A-Z0-9]{12}(?!@#$%^&amp;*():\"\{\}?&lt;&gt;\|+-~!_)") val = QRegExpValidator(str_rx) val3 = QRegExpValidator(adhr_rx) self.PG_Id.setValidator(val3) self.LastName = QLineEdit() self.LastName.setValidator(val) self.MobNum = QLineEdit() qint_val = QIntValidator() qint_val.setTop(10) self.MobNum.setValidator(qint_val) self.layout_pgsd.addRow("First Name",self.PG_Id) self.layout_pgsd.addRow("Last Name",self.LastName) self.layout_pgsd.addRow("Mobile Number",self.MobNum) update_layout_pgsd = QHBoxLayout() layout_test,table = dbv.Search_View(self.getT) #layout_test.setGeometry(QRect(200,200,50,50)) #table.setMaximumHeight(800) #table.setGeometry(200,200,200,200) #table.setGeometry(1,1,1000,600) table.resize(1000,600) update_btn_pgsd = QPushButton('Update') reset_btn_pgsd = QPushButton('Reset') update_layout_pgsd.addWidget(update_btn_pgsd) update_layout_pgsd.addWidget(reset_btn_pgsd) self.layout_pgsd.addRow(update_layout_pgsd) ##Adding the Table Widget to FormLayot self.layout_pgsd.addRow(layout_test) update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum, self.LastName)) #self.widget.setLayout(self.layout_pgsd) def return…
has comment: http://stackoverflow.com/comment/89282968
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89282412
has title: Unable to resize QTableWidget
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/89283207
has comment: http://stackoverflow.com/comment/89282913
has comment: http://stackoverflow.com/comment/89283070
has answer: http://stackoverflow.com/a/51151478
accepted answer: http://stackoverflow.com/a/51151478
tagged with: qlayout
has comment: http://stackoverflow.com/comment/89283014
tagged with: pyqt
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89283022
has comment: http://stackoverflow.com/comment/89282613
favorite count: 0
has comment: http://stackoverflow.com/comment/89282646
tagged with: python

http://stackoverflow.com/q/51039936
linked to: http://stackoverflow.com/q/29337928
has comment: http://stackoverflow.com/comment/89071193
has comment: http://stackoverflow.com/comment/89182264
tagged with: conda
answer count: 2
has title: How to uninstall (mini)conda entirely on Windows
downvote count: 0
has answer: http://stackoverflow.com/a/60013374
favorite count: 0
type: UnansweredQuestion
tagged with: uninstallation
tagged with: windows
tagged with: python
upvote count: 13
has answer: http://stackoverflow.com/a/65146967
tagged with: miniconda
score: 13
type: Question
has body: I was surprised to be unable to find any information anywhere on the web on how to do this properly, but I suppose my surprise ought to be mitigated by the fact that normally this can be done via Microsoft's 'Add or Remove Programs' via the Control Panel. This option is not available to me at this time, since I had installed Python again elsewhere (without having uninstalled it), then uninstalled that installation the standard way. Now, despite no option for uninstalling conda via the Control Panel, conda persists in my command line. Now, the goal is to remove every trace of it, to end up in a state as though conda never existed on my machine in the first place before I reinstall it to the necessary location. I have a bad feeling that if I simply delete the files and then reinstall, this will cause problems. Does anyone have any guidance in how to achieve the above?

http://stackoverflow.com/comment/89233805
has text: Also, in many cases if you need features the language doesn't implement, you're thinking about it in a wrong way. You might want to add the actual use case (why do you need such a class?), so people here could make proposals that are actually possible.
comment on: http://stackoverflow.com/q/51124328
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51145637
has answer: http://stackoverflow.com/a/51145776
tagged with: tags
has title: How to use BeautifulSoup to find multiple div with the same td tag
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: beautifulsoup
tagged with: python-3.x
type: UnansweredQuestion
has body: I want to extract the contents of the highlighted td div.(The actual code is more complex) I'm trying to use BeautifulSoup's Find_all() search for elements that have the tag "div" and the same "td" tag. But my attempt has failed. How can i correct my code? https://i.sstatic.net/nwoNS.png
tagged with: python
has comment: http://stackoverflow.com/comment/89275566
type: Question

http://stackoverflow.com/comment/89189468
comment on: http://stackoverflow.com/q/51101132
score: 0
type: QuestionComment
has text: can you post your piece of code ?
type: Comment

http://stackoverflow.com/q/51111218
score: 1
has body: Is it possible to improve the following code written with python 2.7? First of all forgive me if I have drawn the USA flag incorrectly. This is my first time python programming. I tried my best. By the way I drew 5 lines of stars with space and two extra space after the stars and 4 lines of stars with one less space. Then I have drawn the rest of the stripes. import sys first_time = True second_time = False first_stars = 6 second_stars = 5 total_lines = 11 stars1_col = 6 stars2_col = 5 total_tokens_per_line = 37 first_total_lines = 24 i = 0 for i in range(total_lines): if(first_time or second_time): # if second_time is true print space at the beginning of every # second line else just empty space if(second_time): sys.stdout.write(" ") # else no space else: sys.stdout.write("") # if first_time is true print a star and a space if(first_time): j = 0 for j in range(stars1_col): sys.stdout.write("* ") # first line is done reverse these two variables second_time = True first_time = False # if not first_time print "* " and at the end of stars # write space else: m = 0 for m in range(stars2_col): sys.stdout.write("* ") # write an extra space after every second line of stars sys.stdout.write(" ") # reverse these two variables again first_time = True second_time = False # write an extra space after every second line of stars sys.stdout.write(" ") # draw the underscore lines (the stripes besides stars) l = 0 for l in range(first_total_lines): sys.stdout.write("_") # now flush out or write stripes and stars besides stripes sys.stdout.flush() # if there are 8 lines printed print a newline print("") # if stars and stripes lines are total of 8 make these variables # false if (i == 8): first_time = False second_time = False # then draw the last lines, flush it and print new line if ((not first_time) and (not second_time)): k = 0 for k in range(total_tokens_per_line): sys.stdout.write("_") sys.stdout.flush() print("") The output of this code is:
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51111387
downvote count: 0
answer count: 1
has title: Is it possible to express this console based USA Flag drawn concisely with Python?
tagged with: console
favorite count: 0
has comment: http://stackoverflow.com/comment/89209462
accepted answer: http://stackoverflow.com/a/51111387
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/55651700
type: Answer
has body: Did you install PyTorch? Did you install PyTorch-Encoding? (see https://hangzhang.org/PyTorch-Encoding/notes/compile.html) You should install those packages (and all depencies are fetched automatically) with PIP. You can not just download the source and start! It is always a good idea to at least read the basic documentation of the package you are using.
answers question: http://stackoverflow.com/q/51156087
score: 0

http://stackoverflow.com/comment/89101095
type: Comment
comment on: http://stackoverflow.com/a/51055032
has text: due to name mangling itself they help to act as a private variable (the variables name is different inside and outside the class) and also should it not be @property (property instead of Property)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89323459
score: 0
type: AnswerComment
type: Comment
has text: It returns None even when the user details are correct
comment on: http://stackoverflow.com/a/51139890

http://stackoverflow.com/q/51165378
score: 1
has title: vim syntax keyword only highlight unbound occurrences
tagged with: syntax-highlighting
type: Question
has answer: http://stackoverflow.com/a/52948152
upvote count: 1
has body: I have a syntax file with the following definitions: syn keyword pythonBuiltinFunc __import__ abs all any \ bin bool bytearray \ callable chr classmethod compile complex \ delattr dict dir divmod \ enumerate eval \ filter float format frozenset \ getattr globals hasattr hash hex \ id input int isinstance issubclass iter \ len list locals \ map max min next \ object oct open ord pow property \ range repr reversed round \ set setattr slice sorted \ staticmethod str sum super \ tuple type vars zip \ nextgroup=pythonArgs skipwhite The problem is that this matches occurrences of next (e.g.) even when that name is referenced as an object's attribute, as in obj.next, and this messes up the highlighting. While I might buy that it's useful to not shadow built-in names, I'm not sure that I buy this for bounded names. Does any one have thoughts on how to apply the above definitions, but exclude the pathological case I mentioned below? I guess I'd be allowing whitespace in the word pattern, but ignoring it in the match?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: vim
downvote count: 0
tagged with: syntax

http://stackoverflow.com/comment/89197773
has text: There are a few hidden questions in here that you're trying to solve at once. Hopefully I gave you an elaborate answer, but feel free to ask if you do not understand.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51104534

http://stackoverflow.com/q/51122337
tagged with: python
tagged with: regex
type: UnansweredQuestion
has body: My doubt is that I came across a regex which checks whether a password is strong or not. What is the impact of ^ and $ in this expression. a = compile(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&amp;*-]).{8,}$') It has ^ and $ signs in it. But the below code works the same as above. a = compile(r'(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&amp;*-]).{8,}') If so why are they been used in the above code. Or is there reason for its usage. Thanks in advance!
downvote count: 3
has answer: http://stackoverflow.com/a/51122347
has answer: http://stackoverflow.com/a/51122391
type: Question
linked to: http://stackoverflow.com/q/5921699
score: -3
duplicate of: http://stackoverflow.com/q/5921699
answer count: 2
has title: Difference between r'^specific expression$' and r'specific expression'
upvote count: 0
has comment: http://stackoverflow.com/comment/89229986
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/61002941
has body: Try this code below: conda install geopandas
score: 0
answers question: http://stackoverflow.com/q/51095970
type: Answer

http://stackoverflow.com/q/51016638
accepted answer: http://stackoverflow.com/a/51016751
downvote count: 0
upvote count: 14
has body: I have a dataframe which has Dates and public holidays Date WeekNum Public_Holiday 1/1/2015 1 1 2/1/2015 1 0 3/1/2015 1 0 4/1/2015 1 0 5/1/2015 1 0 6/1/2015 1 0 7/1/2015 1 0 8/1/2015 2 0 9/1/2015 2 0 10/1/2015 2 0 11/1/2015 2 0 12/1/2015 2 0 13/1/2015 2 0 I have to create a conditional column named Public_Holiday_Week, which should return 1, if that particular week has a public holiday And I want to see an output like this Date WeekNum Public_Holiday Public_Holiday_Week 1/1/2015 1 1 1 2/1/2015 1 0 1 3/1/2015 1 0 1 4/1/2015 1 0 1 5/1/2015 1 0 1 6/1/2015 1 0 1 7/1/2015 1 0 1 8/1/2015 2 0 0 9/1/2015 2 0 0 10/1/2015 2 0 0 11/1/2015 2 0 0 12/1/2015 2 0 0 13/1/2015 2 0 0 I tried using np.where df['Public_Holiday_Week'] = np.where(df['Public_Holiday']==1,1,0) But it applies 0 for other days of the week when it is not a public holiday. Do I have to apply rolling here? Appreciate your help
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has title: Marking the entire group if condition is true for a single row
tagged with: python
possible better answer: http://stackoverflow.com/a/51016649
favorite count: 0
has comment: http://stackoverflow.com/comment/89026840
has answer: http://stackoverflow.com/a/51016674
has comment: http://stackoverflow.com/comment/89028119
has comment: http://stackoverflow.com/comment/89028413
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89028516
tagged with: group-by
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89028458
has comment: http://stackoverflow.com/comment/89028069
has answer: http://stackoverflow.com/a/51016649
type: Question
has answer: http://stackoverflow.com/a/51016751

http://stackoverflow.com/a/51055203
answers question: http://stackoverflow.com/q/51045347
downvote count: 0
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: Latest Spacy has a requirement of thinc as: thinc&gt;=6.10.1,&lt;6.11.0 Double check the requirements.txt and check which modules are installed with pip list. If the issue is with incorrect version of thinc then run pip uninstall thinc pip install thinc==6.10.1
score: 1
accepted answer of: http://stackoverflow.com/q/51045347

http://stackoverflow.com/a/59115565
downvote count: 0
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51074984
has body: Based on BERA's answer but as a class: code import math def class Sorter: @staticmethod def centerXY(xylist): x, y = zip(*xylist) l = len(x) return sum(x) / l, sum(y) / l @staticmethod def sortPoints(xylist): cx, cy = Sorter.centerXY(xylist) xy_sorted = sorted(xylist, key = lambda x: math.atan2((x[1]-cy),(x[0]-cx))) return xy_sorted test def test_SortPoints(): points=[(0,0),(0,1),(1,1),(1,0)] center=Sorter.centerXY(points) assert center==(0.5,0.5) sortedPoints=Sorter.sortPoints(points) assert sortedPoints==[(0, 0), (1, 0), (1, 1), (0, 1)]

http://stackoverflow.com/comment/89018816
comment on: http://stackoverflow.com/q/51012793
has text: Please can you show me a sample?I'm a new to this.@kabanus
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89133438
score: 0
type: Comment
has text: which version of numpy are you using? Did you use `transpose` as well?
type: AnswerComment
comment on: http://stackoverflow.com/a/51071791

http://stackoverflow.com/a/60785158
upvote count: 1
type: Answer
has body: A step-wise solution is provided below: Go to the folder where you have placed your flask app (on the command line) Create a virtual environment as using the command ($ py -m venv env) here 'venv' is the short form of the virtual environment and 'env' at the end represents the name of the environment which you want (I have named it as env). Thereafter you can see at from the file explorer that a folder named 'env' is created in the folder stated at point #1 above. Enter the following command ($env\Scripts\activate) by pressing enter this will turn on your virtual environment Thereafter, enter the following command ($set FLASK_APP=&lt;your app name&gt;.py) Enter the following command ($flask run)
answers question: http://stackoverflow.com/q/51119495
score: 1
downvote count: 0

http://stackoverflow.com/q/51139632
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/51139815
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89263476
tagged with: cpu-word
has answer: http://stackoverflow.com/a/51139759
tagged with: search
has answer: http://stackoverflow.com/a/51139765
downvote count: 0
has body: Hello dear Programmers, I want to find certain words within List Items. My Input looks like this: myInputList = ['Hauses\tNN\tHaus', 'guten\tADJ\tgut', 'geht\tVFIN\tgehen'...] I want to find and count \tNN\t or \tADJ\t or \tVFIN\t. The position of the words that I want to count is always the same, like you can see in the example. I tried the following code, but I get the following error: ValueError too many values to unpack (expected 3) from collections import Counter myInputList = Counter([b for a,b,c in myInputList]) print(myInputList) Actually, I can see why this code is not working. But I don't have another approach. So my goal is to count the Part of Speach tags that are between the \t. So at the end I want to say: There are 5 NN, 4 ADJA...
favorite count: 0
possible better answer: http://stackoverflow.com/a/51139739
has answer: http://stackoverflow.com/a/51139739
accepted answer: http://stackoverflow.com/a/51139759
tagged with: count
tagged with: python
has title: Python Find & Count Certain Word within (Strings) List Items
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/89212162
comment on: http://stackoverflow.com/q/51112728
type: Comment
score: 1
type: QuestionComment
has text: `for j in range(len(l)):` => `for j in range(i+1,len(l)):` and you can drop the i != j test

http://stackoverflow.com/comment/89018735
type: AnswerComment
score: 0
type: Comment
has text: @ericg - hmmm, if want use names of months, it is problem for selecting, because is not possible sorting. So possible solution should be change month names to numbers.
comment on: http://stackoverflow.com/a/51012794

http://stackoverflow.com/comment/89129140
type: Comment
comment on: http://stackoverflow.com/a/51069520
type: AnswerComment
has text: Thanks. That did the trick. Any suggestion on where I can become more familiar with the appropriate syntax? Early days here and I want to get off of relying on the community to debug basic errors.
score: 0

http://stackoverflow.com/q/51065181
score: 3
has title: Multiply many columns pandas
has body: I have a data frame like this, but with many more columns and I would like to multiply each two adjacent columns and state the product of the two in a new column beside it and call it Sub_pro and at the end have the total sum of all Sub_pro in a column called F_Pro and reduce the precision to 3 decimal places. I don't know how to get the Sub_pro columns. Below is my code. import pandas as pd df = pd.read_excel("C:dummy") df['F_Pro'] = ("Result" * "Attribute").sum(axis=1) df.round(decimals=3) print (df) Input Id Result Attribute Result1 Attribute1 1 0.5621 0.56 536 0.005642 2 0.5221 0.5677 2.15 93 3 0.024564 5.23 6.489 8 4 11.564256 4.005 0.45556 5.25 5 0.6123 0.4798 0.6667 5.10 Desire Output id Result Attribute Sub_Pro Result1 Attribute1 Sub_pro1 F_Pro 1 0.5621 0.56 0.314776 536 0.005642 3.024112 3.338888 2 0.5221 0.5677 0.29639617 2.15 93 199.95 200.2463962 3 0.024564 5.23 0.12846972 6.489 8 51.912 52.04046972 4 11.564256 4.005 46.31484528 0.45556 5.25 2.39169 48.70653528 5 0.6123 0.4798 0.29378154 0.6667 5.1 3.40017 3.69395154
has comment: http://stackoverflow.com/comment/89121032
answer count: 3
downvote count: 0
tagged with: multiple-columns
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51066531
has answer: http://stackoverflow.com/a/51066295
possible better answer: http://stackoverflow.com/a/51065863
accepted answer: http://stackoverflow.com/a/51066295
has comment: http://stackoverflow.com/comment/89121243
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51065863
upvote count: 3
type: Question

http://stackoverflow.com/comment/89234775
type: AnswerComment
has text: @Florian: don't confuse `classobject.__new__` there with `metaclass.__new__` which I helped you with the implementation of in this question. The latter produces class objects, the former instances of the class.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51124294

http://stackoverflow.com/q/51165549
accepted answer: http://stackoverflow.com/a/51168681
favorite count: 0
has body: I want to write an extension for VSCode that reuse refactor/rename function of vscode-python extension. So that, when the user executes my command, my extension will do rename on a variable of .py file. I don't know if vscode-python is just an extension only or it's implementing Language Server Protocol LSP. And how I call the rename/refactor function of vscode-python. Can you give me some hints? Thank you very much!
tagged with: python
tagged with: language-server-protocol
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51168681
type: Question
tagged with: vscode-extensions
has title: Is vscode-python extension for VSCode is a Language Service or just an extension only?
tagged with: visual-studio-code
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89252878
type: Comment
has text: Thank you captain.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51134043

http://stackoverflow.com/q/51123149
tagged with: python
has comment: http://stackoverflow.com/comment/89232585
has answer: http://stackoverflow.com/a/51130935
type: Question
tagged with: ffi
has body: I want to implement a system which consists of a Python UI and some Rust datastore and functions. The user executes the python code which in turn executes the Rust program in a subprocess. I want the Rust program to run in the background, waiting to exchange variables or function calls with the Python UI (for example every time a button is pressed). My obstacles are: I have tried to make a simple Rust FFI library that can be invoked with ctypes from Python but I don't know how this library will be able to communicate with the compiled rust program that is running on the background. Another approach is to use PyO3 to make a python module using rust. But again I cannot understand how this will cooperate with the rust program to exchange data
tagged with: rust
has title: What is the best practice to follow in order to use Python to call functions from inside a Rust program?
score: 0
tagged with: pyo3
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/51138654
score: 0
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/106324383
linked to: http://stackoverflow.com/q/49768770
has comment: http://stackoverflow.com/comment/89263204
accepted answer: http://stackoverflow.com/a/51140353
tagged with: tox
answer count: 1
has comment: http://stackoverflow.com/comment/89261355
has body: I am using MacOs Sierra 10.12.6 , when I want to install Tox (https://tox.readthedocs.io/en/latest/install.html ) . ~ $ pip install tox Collecting tox Could not fetch URL https://pypi.python.org/simple/tox/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement tox (from versions: ) No matching distribution found for tox ~ $ How can I install Tox?
tagged with: python
has comment: http://stackoverflow.com/comment/89261389
has title: Can't Install Tox
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89261795
tagged with: installation
has answer: http://stackoverflow.com/a/51140353

http://stackoverflow.com/comment/89270285
comment on: http://stackoverflow.com/a/51142662
score: 0
type: AnswerComment
type: Comment
has text: And the last one, sorry for the overtime. These "browse" requests they mention in the website, are ordinary requests, such as the one I would do in Python with: requests.get(URL) ?

http://stackoverflow.com/q/51030971
answer count: 1
has body: I'm running into an issue with argparse's optional arguments. I want to be able to set integer parameters on command line along with true/false flags like so python3 create.py k=7 split=9 My issue is that argparse ignores the equals and takes these arguments as [k=7,split=9]. As you can see, they end up being strings rather than the integers I want. How can I specify on the command line what arguments I want to be what integer? For the record this is what my code looks like parser = argparse.ArgumentParser() parser.add_argument('k', nargs='?', default=6) parser.add_argument('split', nargs='?', default=0.67) arg = parser.parse_args()
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51031169
tagged with: python
has title: Parsing only optional arguments with argparse
tagged with: command-line-arguments
type: Question
has comment: http://stackoverflow.com/comment/89056616
score: 0
tagged with: argparse

http://stackoverflow.com/a/51027482
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/89049592
upvote count: 6
answers question: http://stackoverflow.com/q/51027453
has comment: http://stackoverflow.com/comment/89049301
has comment: http://stackoverflow.com/comment/89049037
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89048666
has body: Use split with stack for Series: a = df['column_name'].str.split('|', expand=True).stack().value_counts() print (a) book 3 fish 2 icecream 1 campfire 1 dtype: int64 Or Counter with list comprehension with flattening: from collections import Counter a = pd.Series(Counter([y for x in df['column_name'] for y in x.split('|')])) print (a) book 3 fish 2 icecream 1 campfire 1 dtype: int64
accepted answer of: http://stackoverflow.com/q/51027453

http://stackoverflow.com/a/51112316
score: 0
answers question: http://stackoverflow.com/q/51112096
type: Answer
has body: How did you install it ? For pip and conda, check if you are in correct environment. If you did an apt install (or apt-get install), the PYTHONPATH is not reflected until you source .bashrc in your home directory. Log-out and log-in (or type source ~/.bashrc in your terminal).

http://stackoverflow.com/q/51141408
answer count: 0
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
has title: How do I visualize the predicted and training data with time series data from a keras-built LSTM model?
tagged with: lstm
has body: I've been putting together a sample LSTM loosely based on this tutorial: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ However, the tutorial does not visualize the actual datapoints, only the error. Here is all of my data and then what happens when I try to put the training and predicted data on the same plot: Plot1 Plot2 The second is simply made with: plt.plot(yhat) plt.plot(test_y) plt.plot(train_y) I know it is due to the normalization of the data but I'm not exactly sure if there is a way to get back to something like my first graph except with the predicted rather than historical data. Is there a way to use the time-stamp independent variable I had before changing it all up to run the model? Ideally I would visualize the values over time from training to prediction. (I'm also trying to figure out how to predict beyond the training set with LSTM but that's a very different topic!) Full code here: from math import sqrt import numpy as np from numpy import concatenate from matplotlib import pyplot import pandas as pd from pandas import read_csv from pandas import DataFrame from pandas import concat from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_squared_error from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # convert series to supervised learning def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] df = DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)] # forecast sequence (t, t+1, ... t+n) for i in range(0, n_out): cols.append(df.shift(-i)) if i == 0: names += [('var%d(t)' % (j+1)) for j in range(n_vars)] else: names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)] # put it all together agg = c…
downvote count: 0
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51092859
has answer: http://stackoverflow.com/a/51092958
tagged with: python
has title: how to store all users input in the list?
has comment: http://stackoverflow.com/comment/89173979
type: AnsweredQuestion
tagged with: list
has body: I am having a trouble of making a while-loop to store all inputs in the list and break the loop while it inputs "quit" and then show ALL the inputs that users have done. my codes are as followings but it only shows ["quit"] after all. while True: list_names = [] enter_names = input("what's the name ") list_names.append(enter_names) if enter_names == "quit": break print(list_names)
accepted answer: http://stackoverflow.com/a/51092958
has comment: http://stackoverflow.com/comment/89173998
type: Question
score: 0
tagged with: while-loop
answer count: 1
has comment: http://stackoverflow.com/comment/89173983

http://stackoverflow.com/comment/89283618
type: AnswerComment
comment on: http://stackoverflow.com/a/51149670
type: Comment
has text: Coefficients don't really work that way. simply put, coefficients show you how important a column is in the calculation of your target vector y. 0.0011084 is an extremely low coefficient in your case. I would suggest you to add more features to your data or increase the size of your data.
score: 0

http://stackoverflow.com/a/52213176
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51049744
accepted answer of: http://stackoverflow.com/q/51049744
type: Answer
has body: You need to use the bellow line in your Procfile: web: gunicorn --worker-class eventlet -w 1 module:app More informations about Gunicorn Web Server on: https://flask-socketio.readthedocs.io/en/latest/#gunicorn-web-server Obs.: You need to install eventlet.
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51078376
has title: NAN loss tensorflow
score: 0
answer count: 1
has body: I am training a bounding box regression problem and using the coordinate component of the loss function described in the YOLO paper. Method 1: Used a HOG feature vector as input to an ANN. Same loss function. Gave me a good model. Method 2: Used images as input to a CNN. Final layer remains same as in method 1. Same loss function as well. But I am facing as issue with the loss being calculated. It is printing nan loss for training, dev and test, from the first epoch itself. How do I go about making the CNN work, when the same loss function works with the ANN perfectly well? And what could be the reason for such an occurrence? I would like to be able to use the same loss function.
tagged with: nan
has answer: http://stackoverflow.com/a/51078602
has comment: http://stackoverflow.com/comment/103384313
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89077053
type: AnswerComment
has text: No, I would need it, otherwise the date is wrong without the timezone.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51043021

matplotlib
tags question: http://stackoverflow.com/q/51156435
tags question: http://stackoverflow.com/q/51136116
tags question: http://stackoverflow.com/q/51090225
tags question: http://stackoverflow.com/q/51068397
tags question: http://stackoverflow.com/q/51027355
tags question: http://stackoverflow.com/q/51163018
tags question: http://stackoverflow.com/q/51039794
tags question: http://stackoverflow.com/q/51047051
tags question: http://stackoverflow.com/q/51062670
tags question: http://stackoverflow.com/q/51120072
tags question: http://stackoverflow.com/q/51155396
tags question: http://stackoverflow.com/q/51102607
tags question: http://stackoverflow.com/q/51107767
tags question: http://stackoverflow.com/q/51088995
tags question: http://stackoverflow.com/q/51031176
tags question: http://stackoverflow.com/q/51107968
tags question: http://stackoverflow.com/q/51123726
tags question: http://stackoverflow.com/q/51105220
tags question: http://stackoverflow.com/q/51011726
tags question: http://stackoverflow.com/q/51123526
tags question: http://stackoverflow.com/q/51033713
tags question: http://stackoverflow.com/q/51127363
tags question: http://stackoverflow.com/q/51091500
tags question: http://stackoverflow.com/q/51017519
tags question: http://stackoverflow.com/q/51040027
tags question: http://stackoverflow.com/q/51059406
tags question: http://stackoverflow.com/q/51059581
tags question: http://stackoverflow.com/q/51020231
tags question: http://stackoverflow.com/q/51128515
tags question: http://stackoverflow.com/q/51064304
tags question: http://stackoverflow.com/q/51042113
tags question: http://stackoverflow.com/q/51120020
tags question: http://stackoverflow.com/q/51076577
tags question: http://stackoverflow.com/q/51079739
tags question: http://stackoverflow.com/q/51101252
tags question: http://stackoverflow.com/q/51152043
tags question: http://stackoverflow.com/q/51076766
tags question: http://stackoverflow.com/q/51058479
tag name: matplotlib
tags question: http://stackoverflow.com/q/51163472
tags question: http://stackoverflow.com/q/51152563
tags question: http://stackoverflow.com/q/51098303
tags question: http://stackoverflow.com/q/51019134
tags question: http://stackoverflow.com/q/51084663
tags question: http://stackoverflow.com/q/51069728
tags question: http://stackoverflow.com/q/51050013
tags question: http://stackoverflow.com/q/51130383
tags question: http://stackoverflow.com/q/51130673
tags question: http://stackoverflow.com/q/51097971
tags question: http://stackoverflow.com/q/51151328
tags question: http://stackoverflow.com/q/51163479
tags question: http://stackoverflow.com/q/51164506
tags question: http://stackoverflow.com/q/51136829
tags question: http://stackoverflow.com/q/51104352
tags question: http://stackoverflow.com/q/51027717
tags question: http://stackoverflow.com/q/51106423
tags question: http://stackoverflow.com/q/51159950
tags question: http://stackoverflow.com/q/51105157
tags question: http://stackoverflow.com/q/51069226
tags question: http://stackoverflow.com/q/51141955
tags question: http://stackoverflow.com/q/51141889
tags question: http://stackoverflow.com/q/51101033
tags question: http://stackoverflow.com/q/51134375
tags question: http://stackoverflow.com/q/51089803
tags question: http://stackoverflow.com/q/51089872
tags question: http://stackoverflow.com/q/51088691
tags question: http://stackoverflow.com/q/51093355
tags question: http://stackoverflow.com/q/51090876
tags question: http://stackoverflow.com/q/51034408
tags question: http://stackoverflow.com/q/51051721
tags question: http://stackoverflow.com/q/51137774
tags question: http://stackoverflow.com/q/51105648
tags question: http://stackoverflow.com/q/51111216
tags question: http://stackoverflow.com/q/51088674
tags question: http://stackoverflow.com/q/51113429
tags question: http://stackoverflow.com/q/51159457
tags question: http://stackoverflow.com/q/51045011
tags question: http://stackoverflow.com/q/51053088
tags question: http://stackoverflow.com/q/51164291
tags question: http://stackoverflow.com/q/51136788

http://stackoverflow.com/a/51017861
downvote count: 0
type: Answer
has body: Your requirement can be served with simple javascript and HTML pages. The framework comes into picture when there are complexities in your project. Let's say your application needs multiple API calls and needs a database then you have to use a framework. A simple HTML and js with Apache server are adequate, based on your requirement. Since you have asked, let me explain the basic differences between those frameworks. Django is a well developed and tested framework. It will give 60-70% of predefined code to use in your project. We can use multiple applications or other libraries alongside Django or over Django. Coming to flask or bottle, they are microframeworks. In simple language, whatever was prebuilt in Django is to be customized and built separately in the flask.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51017725
score: 1
answers question: http://stackoverflow.com/q/51017725
type: AcceptedAnswer

http://stackoverflow.com/comment/89207993
has text: @MadPhysicist: I think it only answers itself if I'm not overlooking something-- which seemed likely with my lack of experience with this library. `pathlib` is quite complete, I was hoping that with the right call order it had a way of more closely mimicking the shell and doing a full expansion.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51108256

http://stackoverflow.com/comment/89300285
type: QuestionComment
comment on: http://stackoverflow.com/q/51139009
has text: urlopen blocks until you got your data. That can't be the problem. If you want it to timeout use the timeout parameter.
score: 0
type: Comment

http://stackoverflow.com/q/51089798
has comment: http://stackoverflow.com/comment/89168249
has title: Efficient algorithm to randomly find available places inside a list in Python
tagged with: python-2.7
type: Question
possible better answer: http://stackoverflow.com/a/51089842
tagged with: python
accepted answer: http://stackoverflow.com/a/51089832
has answer: http://stackoverflow.com/a/51089842
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51090224
upvote count: 2
has answer: http://stackoverflow.com/a/51092866
has answer: http://stackoverflow.com/a/51090125
tagged with: algorithm
answer count: 5
has answer: http://stackoverflow.com/a/51089832
has body: I need to randomly assign a place inside a list to an input. I need to check whether it is not occupied first and then use it. The best algorithm that I can come up with is the following: def get_random_addr(input_arr): while True: addr = random.randrange(1, len(input_arr)) if input_arr[addr] is None: break return addr This is obviously not efficient since as we occupy more slots, the loop takes longer to find an empty slot, and even it may take forever (suppose only one empty slot is left). Do you have any better solutions? How I did it Based on the chosen answer, this is how I ended up doing it. It is very fast and efficient compared to the solutions which search through the whole list and find the None elements and randomly choose from the retrieved set. I think the bottleneck was random.choice method which seems to be very slow. # Create a list of indexes at the beginning when all the values are None available_index = list(range(1, len(input_arr))) random.shuffle(available_index) # To get a random index simply pop from shuffled available index random_index = available_index.pop() While this method has extra O(n) memory complexity, in practice it is very efficient and fast.
has comment: http://stackoverflow.com/comment/89167916
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51082806
tagged with: selenium-webdriver
score: 0
tagged with: selenium
linked to: http://stackoverflow.com/q/50679605
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89154940
has title: How do i run a timer in a function , using python?
has body: I have this code: def Transalted_Content(content): driver= webdriver.Chrome("H:\\CI\\chromedriver.exe") driver.get('https://translate.shell.com/') translate_from = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea.form-control#translateText"))) translate_from._parent.execute_script(""" var elm = arguments[0], text = arguments[1]; if (!('value' in elm)) throw new Error('Expected an &lt;input&gt; or &lt;textarea&gt;'); elm.focus(); elm.value = text; elm.dispatchEvent(new Event('change')); """, translate_from, content) driver.find_element_by_css_selector("input#translate").click() time.sleep(3.5) translated_text_element= driver.find_element_by_id('translatedText') translated_text=translated_text_element.get_attribute('value') driver.close() return translated_text Sometimes chrome gets timed out, So is there a way i can write a while loop as a function separately and run it parallel whenever this function is called so that it can execute a: driver.refresh() and can keep doing this at a time interval(if it exceeds a time interval)?
has comment: http://stackoverflow.com/comment/89154802
tagged with: python-3.x
type: Question
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/51087733
has comment: http://stackoverflow.com/comment/89164001
has comment: http://stackoverflow.com/comment/89157520
answer count: 1

http://stackoverflow.com/q/51072792
has title: Trying to extract dynamic table (url doesn't change) with selenium/beautiful soup
favorite count: 0
tagged with: beautifulsoup
tagged with: python
accepted answer: http://stackoverflow.com/a/51074819
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: selenium
tagged with: web-scraping
has body: I've been trying to extract the following table that I get through using chromedriver to automate input and then an anti-captcha service and I saw an example where someone used beautiful soup after the table was generated. It's a multi-page table but I was just trying to even get the first page before trying to figure out how to click through the other pages, I'm not sure if I can use beautiful soup because when I try the code below I get the first row "No properties to display." which would be if there were no search results and there are. I can't embed an image here as my rank isn't high enough (sorry I'm new to this and annoying, I tried to figure this out before I posted for hours), but if you visit the website and search "Al" or any input you can see the table html https://claimittexas.org/app/claim-search here is my code- from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup from python_anticaptcha import AnticaptchaClient, NoCaptchaTaskProxylessTask import re import pandas as pd import os import time import requests parsed_table_date = [] url = "https://claimittexas.org/app/claim-search" driver = webdriver.Chrome() driver.implicitly_wait(15) driver.get(url) lastNameField = driver.find_element_by_xpath('//input[@id="lastName"]') lastNameField.send_keys('Al') api_key = #MY API key site_key = '6LeQLyEUAAAAAKTwLC-xVC0wGDFIqPg1q3Ofam5M' # grab from site client = AnticaptchaClient(api_key) task = NoCaptchaTaskProxylessTask(url, site_key) job = client.createTask(task) print("Waiting to solution by Anticaptcha workers") job.join() # Receive response response = job.get_solution_response() print("Received solution", response) # Inject response in webpage driver.execute_script('document.getElementById("g-recaptcha-response").innerHTML = "%s"' % response)…
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/51111093
has answer: http://stackoverflow.com/a/51074819
answer count: 1

http://stackoverflow.com/comment/89304722
comment on: http://stackoverflow.com/a/51159159
has text: That’s the line of code. I’m asking about the data, which in your question is `[['hfhf\xa0 fsdg','dsf'],['fsdgs fsdfs','fsdfsd'],['dsf\xa0 sf','asfg']]`. Can you try your data in small bits to see where exactly the error happens? For example, just the first record, then just the second record, etc.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51062526
has answer: http://stackoverflow.com/a/51063178
upvote count: 1
type: Question
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89135117
has body: I have a Dataframe with one column. I need to calculate the average of the difference between the min and max values over 600 seconds period (10 minutes). Or more clearly this : np.average(originalData[sensor1].rolling(600) .apply(lambda mylist : (max(mylist) - min(mylist)), raw = True).dropna()) The code works perfectly and returns me the results I need. The problem is that my Dataframe is pretty large (1.5 million lines, and 200 columns), and it takes a lot of time, specially if I want to go from 600 seconds to 3600 second. I want to improve it by not to calculating the difference on every row, but by skipping 10 rows each time, it shouldn't impact the results significantly. Meaning : Calculate max(list)-min(list) on row 0 to 600 Calculate max(list)-min(list) on row 10 to 610 Calculate max(list)-min(list) on row 20 to 620 Calculate max(list)-min(list) on row 30 to 630 This will speed up the calculation 10 times (hopefully), but I don't see how I can do it with rolling Any suggestions ? Edit: muzzyq requested sample data : a = np.ones(1500000) np.average(pd.Series(a).rolling(600). apply(lambda thing : (max(thing) - min(thing)), raw = True).dropna())
downvote count: 0
answer count: 1
has title: Calculate the maximum difference in rolling pandas - improve performance
favorite count: 0
has comment: http://stackoverflow.com/comment/89115821
has comment: http://stackoverflow.com/comment/89115360
tagged with: pandas
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/90336230
type: AnswerComment
has text: Thank you. Heroku was throwing a bunch of errors and this is the one that fixed it.
type: Comment
comment on: http://stackoverflow.com/a/51686647
score: 0

http://stackoverflow.com/comment/89028841
has text: It would help if you gave your loop variables meaningful names, like `link` or `page` instead of `i`
type: Comment
comment on: http://stackoverflow.com/a/51018027
score: 1
type: AnswerComment

http://stackoverflow.com/a/51087020
answers question: http://stackoverflow.com/q/51086964
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: If you have a string containing the repr of a binary string, you can go back using ast.literal_eval.

http://stackoverflow.com/comment/89230740
type: Comment
type: QuestionComment
has text: Years: int64, Values: float64
comment on: http://stackoverflow.com/q/51120555
score: 0

http://stackoverflow.com/q/51100483
answer count: 0
tagged with: regression
type: Question
has comment: http://stackoverflow.com/comment/89201894
tagged with: quantile
has comment: http://stackoverflow.com/comment/89229458
score: 0
has title: H2o Grid-Search for Quantile Regression/Prediction Interval
tagged with: h2o
tagged with: intervals
has body: I am currently working on calculation of prediction intervals derived through quantile regression with H2o DeepLearning and GradientBoosting. In H2o you have to build and train separate Models for each interval, e.g.: For the 95% Prediction Interval you would need a separate model for the lower bound (100-95)/2)=2.5% and the upper bound (100 - (100-95)/2)=97.5%. Now, I am trying to optimise model-parameter through Grid-Search. What would be the best approach? Running Grid-Search for one of the models and using the parameters of the best model of the grid for all models. Or running a separate grid for each model and getting two models with different parameters in the end? My concern is, that in option two the whole interval will be not consistent, as the two models are not comparable anymore. Has anyone experience with this?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51133631
type: AnsweredQuestion
score: 0
type: Question
has body: I have a problem which may be quite python-ignorant rather than kivy problem. I cant program kivy in python so I have KV file and py file. I have modified Recycleview with SelectableLabel from kivy documentation. However, unlike all other widget, this one works differently. This is main.py #!/usr/bin/env python # -*- coding: utf-8 -*- from kivy.config import Config try: import kivy except ImportError: raise ImportError("this backend requires Kivy to be installed.") from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.label import Label from kivy.properties import BooleanProperty from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.app import App from kivy.uix.boxlayout import BoxLayout class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): ''' Adds selection and focus behaviour to the view. ''' class SelectableLabel(RecycleDataViewBehavior, Label): ''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index return super(SelectableLabel, self).refresh_view_attrs( rv, index, data) def on_touch_down(self, touch): ''' Add selection on touch down ''' if super(SelectableLabel, self).on_touch_down(touch): return True if self.collide_point(*touch.pos) and self.selectable: return self.parent.select_with_touch(self.index, touch) def apply_selection(self, rv, index, is_selected): ''' Respond to the selection of items in the view. ''' self.selected = is_selected self.change_this_variable = 'Here' """I wish to change this variable that belongs to MainWindow instance """ if is_selected: print("selection changed to {0}".format(rv.data[index])) else: print("selection removed for {0}".forma…
tagged with: class
tagged with: recycle
answer count: 1
has answer: http://stackoverflow.com/a/51139691
has title: Kivy- Assign variables with on selection Recycleview
tagged with: python
tagged with: kivy
accepted answer: http://stackoverflow.com/a/51139691
tagged with: reference

http://stackoverflow.com/q/51101594
has comment: http://stackoverflow.com/comment/89190795
has comment: http://stackoverflow.com/comment/89191310
score: 2
has answer: http://stackoverflow.com/a/75952383
tagged with: jenkins
has comment: http://stackoverflow.com/comment/89194853
has comment: http://stackoverflow.com/comment/89191438
has comment: http://stackoverflow.com/comment/89190701
has title: Append unique fingerprint to file
has answer: http://stackoverflow.com/a/51105962
type: Question
tagged with: powershell
has comment: http://stackoverflow.com/comment/89190429
has comment: http://stackoverflow.com/comment/89192535
has comment: http://stackoverflow.com/comment/89190707
upvote count: 2
tagged with: bash
answer count: 3
has comment: http://stackoverflow.com/comment/89190673
has body: I have a set of files (compiled software) that I want to give an unique fingerprint before distribution. The idea is to write a script that: Randomly generates a character sequence Appends the character sequence to a file in the project Stores the fingerprint in a database with the addressee Distributes the software to the addressee The requirements for the fingerprint process is that: The fingerprint is difficult to detect (i.e. not stored in the file metadata or easily accessible areas) The fingerprint does not corrupt the data of the file the sequence is added to The fingerprint can be added to an executable or dll file It's easy to read the fingerprint if you know where to look Are there any open source solutions that is built for the purpose of fingerprinting files?
downvote count: 0
has answer: http://stackoverflow.com/a/51103405
favorite count: 0
has comment: http://stackoverflow.com/comment/89191358
type: UnansweredQuestion
tagged with: windows
tagged with: python

http://stackoverflow.com/q/51094361
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
has body: I am trying to get into a particular link(given in the code) and login using a user id and password. After logging in i want to click on a button named 'see all xxx reviews'. I am using selenium for this task. Unfortunately i am getting a error saying. **Traceback (most recent call last): File "C:/Users/xxxx/.PyCharmEdu2018.1/config/scratches/scratch_2.py", line 16, in username_box = driver.find_element_by_id('emailInput-input') selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"emailInput-input"} (Session info: chrome=67.0.3396.99) (Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)** This is my code: from selenium import webdriver from getpass import getpass from selenium.webdriver.support.ui import WebDriverWait ` usr = input('enter your user name : ') psd = input('enter the password : ') url = "https://www.coursera.org/courses?authMode=login&amp;languages=en&amp;query=big+data&amp;userQuery=big+data" # create a new Chrome session driver = webdriver.Chrome() driver.get(url) username_box = driver.find_element_by_id('emailInput-input') username_box.send_keys(usr) pass_box = driver.find_element_by_id('passwordInput-input') #FHSU pass_box.send_keys(psd) login_btn = driver.find_element_by_xpath('//*[@id="authentication-box-content"]/div/div[2]/div/div[1]/form/div[1]/button/span') login_btn.submit() driver.find_element_by_xpath('//*[@id="ratings"]/div[2]/button').click()
downvote count: 1
has comment: http://stackoverflow.com/comment/89176674
has answer: http://stackoverflow.com/a/51111348
type: Question
answer count: 1
score: 0
favorite count: 0
has title: What should i do to fix the NoSuchElementException error in my python code?

http://stackoverflow.com/comment/89219909
type: Comment
type: QuestionComment
has text: is there any way to get width and height by having only url?
score: 0
comment on: http://stackoverflow.com/q/51116907

http://stackoverflow.com/q/51131812
type: Question
answer count: 2
score: 5
favorite count: 0
possible better answer: http://stackoverflow.com/a/51133221
tagged with: python
has body: Is is possible to wrap text in row using tkinter treeview? I have tried to change row height but text wont wrap. basically i want to have multi line text in row. This is the code: from tkinter import* from tkinter import ttk myApp = Tk() NewTree= ttk.Treeview(myApp, height=5) NewTree['show'] = 'headings' s = ttk.Style() s.configure('Treeview', rowheight=40) NewTree["columns"]=("1","2") NewTree.column("1", width=60) NewTree.column("2", width=60) NewTree.heading("1", text="col a") NewTree.heading("2", text="col b") item = NewTree.insert("", "end", values=("i want to wrap this text","and this text")) NewTree.grid(row=0,column=0) myApp.mainloop() This is the second version of code (when you can manually add items in treeview), It just have one big function before the code that I posted above. I tried to put different values on lenght but the result is the same (It wont wrap): from tkinter import* from tkinter import ttk from tkinter import messagebox import textwrap def wrap(string, lenght=15): return '\n'.join(textwrap.wrap(string, lenght)) myApp = Tk() def editact(event): def double(event): # funkcija koja kreira celiju kada se klikne dupli klik try: if NewTree.identify_region(event.x, event.y) == 'cell': # the user clicked on a cell def ok(event): """Change item value.""" NewTree.set(item, column, entry.get()) entry.destroy() column = NewTree.identify_column(event.x) # identify column item = NewTree.identify_row(event.y) # identify item x, y, width, height = NewTree.bbox(item, column) value = NewTree.set(item, column) elif NewTree.identify_region(event.x, event.y) == 'heading': # the user clicked on a heading def ok(event): """Change heading text.""" NewTree.heading(column, text=entry.get()) entry.destroy() column = NewTree.identify_column(event.x) # identify column # tree.bbox work only with items so we have to get the bbox of the heading differently x, y, width, _ = NewTree.bbox(NewTree.get_children('')[0], column) # get x and width (same as the one of any cell in …
tagged with: tkinter
upvote count: 5
has title: Wrap text inside row in tkinter treeview
tagged with: treeview
accepted answer: http://stackoverflow.com/a/51132649
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51133221
has answer: http://stackoverflow.com/a/51132649

http://stackoverflow.com/comment/89071057
comment on: http://stackoverflow.com/q/51034522
has text: why not using a script to fix missing textures ? like deleting them or put placeholders ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89261683
comment on: http://stackoverflow.com/q/51138447
has text: What errors are you getting?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/89165770
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51070083
has text: not `import sys`. check if your path is in `sys.path`
type: AnswerComment

http://stackoverflow.com/comment/89253649
score: 1
comment on: http://stackoverflow.com/q/51134686
has text: Please write a clearer code without magic methods. A class is here useless.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51030350
has comment: http://stackoverflow.com/comment/89060573
accepted answer of: http://stackoverflow.com/q/51023116
score: 0
answers question: http://stackoverflow.com/q/51023116
type: AcceptedAnswer
has body: It is not necessary to create a thread to update the QTableWidget, you could use a QTimer, on the other hand remove QTableWidgetItem and set them again is expensive so I recommend you update them. import sys import time from PySide import QtCore, QtGui class TestTable(QtGui.QTableWidget): def __init__(self, parent=None): super(TestTable, self).__init__(parent) self.setRowCount(3) self.setColumnCount(1) for row in range(self.rowCount()): for col in range(self.columnCount()): self.setItem(row, col, QtGui.QTableWidgetItem(str(time.time()))) for each in range(self.rowCount()): self.setRowHeight(each, 100) self.setColumnWidth(each, 250) timer_refresh = QtCore.QTimer(self) timer_refresh.timeout.connect(self.refresh) timer_refresh.start(2000) def refresh(self): for row in range(self.rowCount()): for col in range(self.columnCount()): self.item(row, col).setText(str(time.time())) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) test = TestTable() test.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/89060596
has comment: http://stackoverflow.com/comment/89061045
type: Answer

http://stackoverflow.com/q/51120622
linked to: http://stackoverflow.com/q/51076889
type: Question
score: 0
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/89227181
answer count: 1
has title: why publish from paho raspberry pi to Mosca node js give me an error?
tagged with: paho
tagged with: mqtt
has answer: http://stackoverflow.com/a/51132652
tagged with: python
has comment: http://stackoverflow.com/comment/89227235
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89231139
has body: I am trying to sub and publish from Paho library running on my raspberry pi to MOSCA MQTT broker on my nodejs server running on windows machine but no thing happen so what is the problem Note: when i connect to the broker from nodejs client it works here is my nodejs code var mosca = require('mosca'); var settings = { port: 1883 }; //here we start mosca var server = new mosca.Server(settings); server.on('ready', setup); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running'); } // fired whena client is connected server.on('clientConnected', function(client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function(packet, client) { console.log('Published : ', packet.payload); }); // fired when a client subscribes to a topic server.on('subscribed', function(topic, client) { console.log('subscribed : ', topic); }); // fired when a client subscribes to a topic server.on('unsubscribed', function(topic, client) { console.log('unsubscribed : ', topic); }); // fired when a client is disconnecting server.on('clientDisconnecting', function(client) { console.log('clientDisconnecting : ', client.id); }); // fired when a client is disconnected server.on('clientDisconnected', function(client) { console.log('clientDisconnected : ', client.id); }); // this is my client request var mqtt = require('mqtt'); client = mqtt.connect('mqtt://192.168.10.99:1883'); client.subscribe('presence'); console.log('Client publishing.. '); client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date()); client.end(); and here is my python code running on my raspberry pi import time import paho.mqtt.client as paho broker="192.168.10.99" #define callback def on_message(client, userdata, message): time.sleep(1) print("received message =",str(message.payload.decode("utf-8"))) client= paho.Client("client-001") #create client object client1.on_publish = on_publish #assign function to callback…
has comment: http://stackoverflow.com/comment/89227222

http://stackoverflow.com/comment/89195393
comment on: http://stackoverflow.com/a/51058864
has text: @ThanksForHelping - Solution was changed, please check it.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89219681
type: QuestionComment
comment on: http://stackoverflow.com/q/51116785
has text: a view is not an iterator, right?
score: 0
type: Comment

scikit-learn
tags question: http://stackoverflow.com/q/51149351
tags question: http://stackoverflow.com/q/51144580
tags question: http://stackoverflow.com/q/51058337
tags question: http://stackoverflow.com/q/51064456
tags question: http://stackoverflow.com/q/51164281
tags question: http://stackoverflow.com/q/51119765
tags question: http://stackoverflow.com/q/51089814
tags question: http://stackoverflow.com/q/51091132
tags question: http://stackoverflow.com/q/51064269
tags question: http://stackoverflow.com/q/51065362
tags question: http://stackoverflow.com/q/51026841
tags question: http://stackoverflow.com/q/51163974
tags question: http://stackoverflow.com/q/51087854
tags question: http://stackoverflow.com/q/51161782
tags question: http://stackoverflow.com/q/51085553
tags question: http://stackoverflow.com/q/51040075
tags question: http://stackoverflow.com/q/51106254
tags question: http://stackoverflow.com/q/51160394
tags question: http://stackoverflow.com/q/51052131
tags question: http://stackoverflow.com/q/51032601
tags question: http://stackoverflow.com/q/51098715
tags question: http://stackoverflow.com/q/51126327
tags question: http://stackoverflow.com/q/51038820
tags question: http://stackoverflow.com/q/51069750
tags question: http://stackoverflow.com/q/51088761
tags question: http://stackoverflow.com/q/51023968
tags question: http://stackoverflow.com/q/51154607
tags question: http://stackoverflow.com/q/51140650
tags question: http://stackoverflow.com/q/51063762
tags question: http://stackoverflow.com/q/51070345
tags question: http://stackoverflow.com/q/51129498
tags question: http://stackoverflow.com/q/51012658
tags question: http://stackoverflow.com/q/51058488
tags question: http://stackoverflow.com/q/51089207
tags question: http://stackoverflow.com/q/51056437
tags question: http://stackoverflow.com/q/51033792
tag name: scikit-learn
tags question: http://stackoverflow.com/q/51083843
tags question: http://stackoverflow.com/q/51027885
tags question: http://stackoverflow.com/q/51160354
type: Tag
tags question: http://stackoverflow.com/q/51018963
tags question: http://stackoverflow.com/q/51151294
tags question: http://stackoverflow.com/q/51139150
tags question: http://stackoverflow.com/q/51120555
tags question: http://stackoverflow.com/q/51111080
tags question: http://stackoverflow.com/q/51143361
tags question: http://stackoverflow.com/q/51149995
tags question: http://stackoverflow.com/q/51137063
tags question: http://stackoverflow.com/q/51031235
tags question: http://stackoverflow.com/q/51154180
tags question: http://stackoverflow.com/q/51044904
tags question: http://stackoverflow.com/q/51047286
tags question: http://stackoverflow.com/q/51124315
tags question: http://stackoverflow.com/q/51037737
tags question: http://stackoverflow.com/q/51152330
tags question: http://stackoverflow.com/q/51084664
tags question: http://stackoverflow.com/q/51079983
tags question: http://stackoverflow.com/q/51037079
tags question: http://stackoverflow.com/q/51118195
tags question: http://stackoverflow.com/q/51078742
tags question: http://stackoverflow.com/q/51044761
tags question: http://stackoverflow.com/q/51052587
tags question: http://stackoverflow.com/q/51044044
tags question: http://stackoverflow.com/q/51077816
tags question: http://stackoverflow.com/q/51138066
tags question: http://stackoverflow.com/q/51087141
tags question: http://stackoverflow.com/q/51058959
tags question: http://stackoverflow.com/q/51148326
tags question: http://stackoverflow.com/q/51125696

http://stackoverflow.com/comment/89201922
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51090571
has text: @vy32 well, if your script uses certain modules, then there’s a transitive dependency graph attached to that; those modules don’t operate in isolation. If you only want direct imports, then do your own analysis.
type: Comment

http://stackoverflow.com/q/51165856
type: Question
upvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89330475
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89315126
type: UnansweredQuestion
has title: Created .json but it turns up empty
downvote count: 1
has answer: http://stackoverflow.com/a/51567776
has body: I'm following the tutorial found at the link. https://snips-nlu.readthedocs.io/en/latest/tutorial.html#snips-dataset-format I'm trying to use the dataset creation CLI that is contained in the lib. I ran the following in the terminal and the .json was created but was empty. Yes I am in the right directory. Any thoughts? snips-nlu generate-dataset en intent_turnLightOn.txt intent_turnLightOff.txt intent_setTemperature.txt entity_room.txt &gt; dataset.json Traceback (most recent call last): File "/Users/jbennett8/anaconda3/bin/snips-nlu", line 11, in &lt;module&gt; sys.exit(main()) File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/snips_nlu/__main__.py", line 29, in main plac.call(commands[command], sys.argv[1:]) File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/plac_core.py", line 328, in call cmd, result = parser.consume(arglist) File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/plac_core.py", line 207, in consume return cmd, self.func(*(args + varargs + extraopts), **kwargs) File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/snips_nlu/cli/generate_dataset.py", line 16, in generate_dataset dataset = AssistantDataset.from_files(language, list(files)) File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/snips_nlu/cli/dataset/assistant_dataset.py", line 57, in from_files for f in intent_filepaths] File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/snips_nlu/cli/dataset/assistant_dataset.py", line 57, in &lt;listcomp&gt; for f in intent_filepaths] File "/Users/jbennett8/anaconda3/lib/python3.6/site-packages/snips_nlu/cli/dataset/intent_dataset.py", line 47, in from_file with filepath.open(encoding="utf-8") as f: File "/Users/jbennett8/anaconda3/lib/python3.6/pathlib.py", line 1161, in open opener=self._opener) File "/Users/jbennett8/anaconda3/lib/python3.6/pathlib.py", line 1015, in _opener return self._accessor.open(self, flags, mode) File "/Users/jbennett8/anaconda3/lib/python3.6/pathlib.py", line 387, in wra…
score: -1
has comment: http://stackoverflow.com/comment/89314954

http://stackoverflow.com/q/51147604
has title: Process running on port needs to be killed everytime I re-run a script in PyCharm
linked to: http://stackoverflow.com/q/39632667
type: Question
has answer: http://stackoverflow.com/a/51147887
has comment: http://stackoverflow.com/comment/89279673
accepted answer: http://stackoverflow.com/a/51147887
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89279815
tagged with: pycharm
linked to: http://stackoverflow.com/q/20239232
has body: I'm currently learning CherryPy, usnig Python 2.7 on PyCharm, on Windows 10. While I executed a few programs on it, I noticed something. The first time I run the program it successfully executes, and the required o/p appears on localhost port 8080 in the browser. However, if I change something in the same program and run it again, I get this: C:\Python27\python.exe C:/Users/ymodak/Desktop/Training/x.py [03/Jul/2018:11:15:37] ENGINE Listening for SIGTERM. [03/Jul/2018:11:15:37] ENGINE Bus STARTING CherryPy Checker: The Application mounted at '' has an empty config. [03/Jul/2018:11:15:37] ENGINE Set handler for console events. [03/Jul/2018:11:15:37] ENGINE Started monitor thread 'Autoreloader'. [03/Jul/2018:11:15:39] ENGINE Error in 'start' listener <bound method Server.start of <cherrypy._cpserver.Server object at 0x0000000003B14F98>> Traceback (most recent call last): File "C:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 230, in publish output.append(listener(*args, **kwargs)) File "C:\Python27\lib\site-packages\cherrypy\_cpserver.py", line 191, in start super(Server, self).start() File "C:\Python27\lib\site-packages\cherrypy\process\servers.py", line 177, in start portend.free(*self.bind_addr, timeout=Timeouts.free) File "C:\Python27\lib\site-packages\portend.py", line 119, in free raise Timeout("Port {port} not free on {host}.".format(**locals())) Timeout: Port 8080 not free on 127.0.0.1. [03/Jul/2018:11:15:39] ENGINE Shutting down due to error in start listener: Traceback (most recent call last): File "C:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 268, in start self.publish('start') File "C:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 248, in publish raise exc ChannelFailures: Timeout('Port 8080 not free on 127.0.0.1.',) [03/Jul/2018:11:15:39] ENGINE Bus STOPPING [03/Jul/2018:11:15:39] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('127.0.0.1', 8080)) already shut down [03/Jul/2018:11:15:39] ENGINE Stop…
tagged with: python
has comment: http://stackoverflow.com/comment/89279500
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89279588
upvote count: 2

http://stackoverflow.com/comment/89187639
type: QuestionComment
score: 0
has text: I didnt try it, but looks like it's possible https://stackoverflow.com/questions/7878028/override-default-django-translations
comment on: http://stackoverflow.com/q/51099894
type: Comment

http://stackoverflow.com/comment/89090990
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51044297
has text: Okay where should I add this line of code? `df['col_name'] = df['col_name'].str.strip().map(d)` I was working on exceptions handlers that were supposed to NaN the final product if the column name wasn't in the dictionary. But that line of your will clean all the columns of bad characters.

http://stackoverflow.com/comment/89217170
has text: Then `user_id` is in your models's `user.id` and token - see how DRF creates tokens, you can add any other fields in your child model as per need if they are not in Django's User model.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51115442

http://stackoverflow.com/comment/89238606
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51126737
score: 0
has text: @PM2Ring I'm supporting environments that only support Python 2.7 (3D tools like Autodesk Maya and SideFX Houdini).

http://stackoverflow.com/comment/89304920
type: Comment
comment on: http://stackoverflow.com/q/51129215
has text: @SimonBrahan Yes that's right.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51130306
answers question: http://stackoverflow.com/q/51129946
has body: You can use regex pattern to do this For example suppose l is list of floats: import re from datetime import datetime, timedelta l = [130101.34764204, 130101.34764606, 130101.34765007] DAY = 24*60*60 def to_date(f): year, month, day, decimal = list(map(int, re.match('(\d{2})(\d{2})(\d{2})\.(\d+)', "{:.8f}".format(f)).groups(1))) seconds = decimal*DAY / 10**8 return datetime(2000+year, month, day) + timedelta(seconds=seconds) converted_l = map(to_date, l) Result: for c in converted_l: print(c) 2013-01-01 08:20:36.272256 2013-01-01 08:20:36.619584 2013-01-01 08:20:36.966048
has comment: http://stackoverflow.com/comment/89304567
has comment: http://stackoverflow.com/comment/89290534
type: Answer
has comment: http://stackoverflow.com/comment/89292744
score: 0

http://stackoverflow.com/comment/89263916
type: QuestionComment
has text: If the "image is stored as a file", why is the database involved at all? PHP can read the file, then send it to "others".
score: 1
comment on: http://stackoverflow.com/q/51109303
type: Comment

http://stackoverflow.com/comment/97758409
comment on: http://stackoverflow.com/q/51031137
score: 0
type: Comment
type: QuestionComment
has text: Your example does not work. Can you add the necessary imports?

syntax-highlighting
tags question: http://stackoverflow.com/q/51165378
tag name: syntax-highlighting
type: Tag

http://stackoverflow.com/q/51068159
tagged with: django
has title: Pass a datetime object to url in django
type: Question
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/51068408
has answer: http://stackoverflow.com/a/51068445
downvote count: 0
tagged with: url
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/57137903
tagged with: datetime
tagged with: python
has body: How can I pass a datetime e.g. datetime.date(2017, 12, 31) object to a url in django? My template: {% for key, value in my_dictionary.items %} {{ key.0 }} # it displays Dec. 31, 2017 ... {% endfor %} Passing it to the url as: href="{% url 'my_url:my_date' selected_day=key.0 %}"&gt; My urls.py: url(r'^my-date/(?P&lt;selected_day&gt;\w+)/$', name='my_date') Error: Exception Type: NoReverseMatch Exception Value: Reverse for 'my_date' with keyword arguments '{'selected_day': datetime.date(2017, 12, 31),}'not found. 1 pattern(s) tried: ['my-url/my-date/(?P&lt;selected_day&gt;\\w+)/$']
type: UnansweredQuestion
upvote count: 3

http://stackoverflow.com/q/51157815
score: 2
type: AnsweredQuestion
has body: I wrote a simple scraper sometime ago which opens up chrome browser and scrapes some data from a website. However now everytime I run that script it does not open the url I provide but instead redirects to GDPR consent website. I removed --incognito mode from options but it is still the same. The chrome opens then the script crashes because it is atuomatically redirected to that GDPR consent webpage. How can I go around this issue? Here is the code to reproduce the error. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException option = webdriver.ChromeOptions() #option.add_argument("--incognito") browser = webdriver.Chrome(executable_path='chromedriverpath', chrome_options=option) rval=[] browser.get("https://finance.yahoo.com/quote/AAPL/key-statistics?p=AAPL") timeout = 10 WebDriverWait(browser, timeout) values_element = browser.find_elements_by_xpath("//td[@class='Fz(s) Fw(500) Ta(end)']") print(browser) values = [x.text for x in values_element] rval.append(values[8]) for title, value in zip(stockname, rval): print(title + ': ' + value) evdict=dict(zip(stockname, rval))
tagged with: selenium
has comment: http://stackoverflow.com/comment/89320046
type: Question
has answer: http://stackoverflow.com/a/56853096
answer count: 1
downvote count: 0
has title: Selenium webdriver and GDPR consent
has comment: http://stackoverflow.com/comment/89301452
has comment: http://stackoverflow.com/comment/89301234
favorite count: 0
has comment: http://stackoverflow.com/comment/89319762
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/56853096
has comment: http://stackoverflow.com/comment/89304143
tagged with: selenium-webdriver

http://stackoverflow.com/a/51120263
upvote count: 5
answers question: http://stackoverflow.com/q/51119896
type: Answer
has comment: http://stackoverflow.com/comment/89226565
has comment: http://stackoverflow.com/comment/89232334
score: 5
has body: Replace //div[contains(., 'All')][2] with (//div[contains(., 'All')])[2] to select the second such div overall rather than restricting such div elements to be in the second child position. You might further tighten the predicate to use string equality rather than substring containment (to avoid matching All good men , for example), if your data is truly as shown: (//div[.='All'])[2]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51119896

http://stackoverflow.com/q/51016431
has comment: http://stackoverflow.com/comment/89025308
has comment: http://stackoverflow.com/comment/89025347
favorite count: 0
tagged with: python-3.x
has body: list1 = [] while True: num=input("enter a number or input q to quit or input a for the average\n") if isinstance(num, int): list1.append(num) elif isinstance(num, str): if num == "q": exit() elif num == "a": print(list1) else: print("stop") I'm a python beginner, and I've made this program to find the average of integers in a list, but for some reason it does not add any integers to the list. I don't know why it doesn't work
type: Question
tagged with: python
has title: Python 3 program about finding the average of integers in a list
score: 0
upvote count: 1
linked to: http://stackoverflow.com/q/5424716
downvote count: 1
has comment: http://stackoverflow.com/comment/89025428
duplicate of: http://stackoverflow.com/q/5424716
answer count: 0
has comment: http://stackoverflow.com/comment/89025311
type: UnansweredQuestion

http://stackoverflow.com/a/51031374
type: Answer
has body: lst = ['the offspring','legends','the legends','soraka'] for i in lst: if 'the' in i: print(i) This is how I would check inside of the list, hope this helps!
answers question: http://stackoverflow.com/q/51031209
score: 0

http://stackoverflow.com/comment/89034495
type: QuestionComment
comment on: http://stackoverflow.com/q/51020916
score: 0
type: Comment
has text: Shouldn't there still only be a single argument, even if the username contains spaces? Either it's a single string (without spaces) `'John'`, or it's a single string (with spaces) `'Me Head'`.

http://stackoverflow.com/comment/89521348
comment on: http://stackoverflow.com/a/51156780
type: Comment
score: 0
type: AnswerComment
has text: Because that's not a list comprehension. See https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions: *A list comprehension consists of brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses.*.

http://stackoverflow.com/comment/89305472
type: AnswerComment
has text: In my Jupyter notebook, the values aren't displayed as the table you posted above. On mine, it shows the three headings and then all of the values underneath, rather than as a table. any thoughts? Thanks a bunch for your help again! Pay as you go One year reserved Three year reserved and then all of the values underneath
type: Comment
comment on: http://stackoverflow.com/a/51160874
score: 0

http://stackoverflow.com/a/66614950
score: 0
has body: I had a similar issue. I have two versions of Python on my machine. 3.7.4 and 3.7.4 (conda) linked to Anaconda. For some reasons, when on the conda version and using : $ pip install Flask-SQLAlchemy The installation does not go through, I had to switch to the 3.7.4 regular version.
type: Answer
answers question: http://stackoverflow.com/q/51142996

http://stackoverflow.com/comment/89126605
type: QuestionComment
has text: You don't need to use `== True`. It's not the reason you have an issue, but it's all you need to do. Your decorator is otherwise exactly the same as the [one used by Python's own test suite](https://github.com/python/cpython/blob/master/Lib/test/support/__init__.py#L187-L195).
score: 0
comment on: http://stackoverflow.com/q/51068281
type: Comment

http://stackoverflow.com/comment/89187551
comment on: http://stackoverflow.com/q/51100078
has text: Why you are not satisfied with your approach? It's just one command after all!
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89188988
type: AnswerComment
type: Comment
has text: i wanted for a group of line items not at individual line item like if you see in the required output as given above
score: 0
comment on: http://stackoverflow.com/a/51096570

http://stackoverflow.com/comment/89242922
type: AnswerComment
score: 0
type: Comment
has text: Thanks for your reply.I did the same but it is not working for me.Have you tried to do the same in windows?
comment on: http://stackoverflow.com/a/51125798

http://stackoverflow.com/q/51062934
has body: I need to convert a list of lists like so: [['S', 'NP', 'VP'], ['NP', 'Det', 'N'], ['NP', 'NP', 'PP'], ['VP', 'V', 'NP'], ['VP', 'VP', 'PP'], ['PP', 'P', 'NP'], ['Det', "'the'"], ['N', "'pirate'"], ['N', "'sailor'"], ['N', "'telescope'"], ['V', "'sees'"], ['P', "'with'"]] to a dictionary such that it looks like this: {'S':['NP', 'VP'], 'NP': ['Det', 'N'], ['NP', 'PP'], 'VP': ['V', 'NP'], ['VP', 'PP'], 'PP': ['P', 'NP'], 'Det': ["'the'"], 'N': ["'pirate'"], ["'sailor'"], ["'telescope'"], 'V': ["'sees'"], 'P': ["'with'"]} I have tried using this method using from collections import default dict: g = defaultdict(dict) for i, j, k in new_grammar: g[i][j] = k But this does not work because there are lists in the list of lists with only two elements. I have also tried: grammar = {} for rule in new_grammar: grammar[rule[0]] = rule[1:] However, this only gives each key one value. Is there any way to do this?
favorite count: 0
upvote count: 2
answer count: 5
accepted answer: http://stackoverflow.com/a/51062997
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51063144
has answer: http://stackoverflow.com/a/51063032
tagged with: list
score: 1
possible better answer: http://stackoverflow.com/a/51063104
downvote count: 1
has answer: http://stackoverflow.com/a/51063104
type: Question
has title: How to convert a list of lists with separate lists that have the same first element to a dictionary?
has comment: http://stackoverflow.com/comment/89115713
has answer: http://stackoverflow.com/a/51062997
has answer: http://stackoverflow.com/a/51063391

http://stackoverflow.com/q/51026191
upvote count: 2
has answer: http://stackoverflow.com/a/51026511
has answer: http://stackoverflow.com/a/51026309
score: 2
type: AnsweredQuestion
has body: I am parsing some XML and write data to different files depending on the XML element that is currently being processed. Processing an element is really fast, and writing the data is, too. Therefore, files would need to open and close very often. For example, given a huge file: for _, node in lxml.etree.iterparse(file): with open(f"{node.tag}.txt", 'a') as fout: fout.write(node.attrib['someattr']+'\n']) This would work, but relatively speaking it would take a lot of time opening and closing the files. (Note: this is a toy program. In reality the actual contents that I write to the files as well as the filenames are different. See the last paragraph for data details.) An alternative could be: fhs = {} for _, node in lxml.etree.iterparse(file): if node.tag not in fhs: fhs[node.tag] = open(f"{node.tag}.txt", 'w') fhs[node.tag].write(node.attrib['someattr']+'\n']) for _, fh in fhs.items(): fh.close() This will keep the files open until the parsing of XML is completed. There is a bit of lookup overhead, but that should be minimal compared to iteratively opening and closing the file. My question is, what is the downside of this approach, performance wise? I know that this will make the open files inaccessible by other processes, and that you may run into a limit of open files. However, I am more interested in performance issues. Does keeping all file handles open create some sort of memory issues or processing issues? Perhaps too much file buffering is going on in such scenarios? I am not certain, hence this question. The input XML files can be up to around 70GB. The number of files generated is limited to around 35, which is far from the limits I read about in the aforementioned post.
tagged with: performance
has comment: http://stackoverflow.com/comment/89045139
has title: Downsides of keeping file handles open?
has comment: http://stackoverflow.com/comment/89048188
type: Question
accepted answer: http://stackoverflow.com/a/51026511
downvote count: 0
has comment: http://stackoverflow.com/comment/89053625
has comment: http://stackoverflow.com/comment/89048181
favorite count: 0
has comment: http://stackoverflow.com/comment/89045894
has answer: http://stackoverflow.com/a/51026869
linked to: http://stackoverflow.com/q/6774724
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/89048376
has answer: http://stackoverflow.com/a/51027045
tagged with: file-handling
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51026309

http://stackoverflow.com/comment/89228381
has text: And when we're not sure, we test! So I tried replacing my `g = ''.join(sorted(w))` line with `g = frozenset(Counter(w).items())`. I also changed the print statement to not print the key, since that might be unfair for the frozen sets: `print('%2d' % (len(words)), ' '.join(words))`. Result: 0.361s for sorting, 1.558s for frozen sets.
score: 0
comment on: http://stackoverflow.com/a/51118349
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51040611
tagged with: dataframe
has body: I have one dataframe like below: name,date AAA,201705 AAA,201706 AAA,201707 AAA,201708 AAA,201710 AAA,201711 AAA,201802 AAA,201803 AAA,201804 AAA,201805 AAA,201806 AAA,201807 In this dataframe two columns are available i.e. name and date. In the date column only year and month is available in yyyymm format. In date column values 201709, 201712 and 201801 months are not available. Need to check all the months are present or not. If any month is not available then need the ouput in below format: name,start_date,end_date,count AAA,201709,201709,1 AAA,201712,201801,2 I am trying to use pandas diff function
upvote count: 2
tagged with: pandas
answer count: 1
has title: How to find month gaps count from monthly data?
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51040990
downvote count: 0
type: Question

http://stackoverflow.com/comment/89103434
type: QuestionComment
comment on: http://stackoverflow.com/q/51056256
has text: @vijayMV - not whole source code but the one relevant to your question
score: 0
type: Comment

http://stackoverflow.com/q/51119865
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/89275678
score: 0
tagged with: pygame
favorite count: 0
has answer: http://stackoverflow.com/a/51149197
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has body: I have total of 5 questions and I want them to be called randomly but my problem is that I am unable to display one question at a time on the screen and wait till user select the answer. The code I have right now is just switching the questions and not staying on one questions. Below the code I posted is only the main part where I am having issues I am testing with 2 questions so in the code there is only 2 questions in random choice. The python version I am using is 3.6 any help would be appreciated. Thank you. GAME SCREEN def game_screen(): player_score = 25 actual_score = 0 wrong_answer = 0 timer = pygame.time.get_ticks() seconds = 0 start = True question_list = [question1, question2] while start : for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() seconds = (pygame.time.get_ticks()- timer)/1000 main_font = pygame.font.Font("ArialRounded.TTF", 22) sub_font = pygame.font.Font("ArialRounded.TTF", 22) timer_font = sub_font.render(str(seconds), True, SEABLUE) question_font = main_font.render("Question:", True, SEABLUE) star_img = pygame.image.load("starscore.png") menu_screen_img = pygame.image.load("quizzappbackgroundscreen.png") blureffect_img = pygame.image.load("blureffect.png") onoff_button_img = pygame.image.load("onoffbutton.png") knobone_img = pygame.image.load("knob_a.png") knobtwo_img = pygame.image.load("knob_a.png") knobrect_a = knobone_img.get_rect(center=(97.5,647.5)) knobrect_b = knobtwo_img.get_rect(center=(514.5,647.5)) mpos = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if knobrect_a.collidepoint(mpos): knobone_img = pygame.image.load("knob_b.png") if click[0] == 1: knobone_img = pygame.image.load("rotatedknob_a.png") click_sound.set_volume(0.3) click_sound.play() if knobrect_b.collidepoint(mpos): knobtwo_img = pygame.image.load("knob_b.png") if click[0] == 1: knobtwo_img = pygame.image.load("rotatedknob_a.png") click_sound.set_volume(0.3) click_sound.play() screen.blit(menu_screen_img, [0,0]) screen…
has comment: http://stackoverflow.com/comment/89272851
has title: How can I show one function at a time and take input of return value in python?
type: Question
answer count: 1

http://stackoverflow.com/a/51140076
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51140011
type: Answer
score: 2
upvote count: 2
has body: You can do new_df = df[list] df = df.drop(columns=list)
has comment: http://stackoverflow.com/comment/97162928
answers question: http://stackoverflow.com/q/51140011
type: AcceptedAnswer

http://stackoverflow.com/a/51126862
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89245634
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89266746
score: 1
upvote count: 1
has body: On every draw() iteration, you're doing: background_img = pyglet.resource.image('pizza_clicker.png') This means you're loading in the same picture, from hard-drive, every render sequence. You're also doing a for loop over different pizza images where you also fetch them from hard drive: for i in range (0, len(images)): divideby = 1.4 / (i + 1) pizza.append(pyglet.resource.image(images[i])) I strongly suggest you read up on how resources are loaded in, and use a cProfiler analyzer. A good example of how you could profile your code, is here. Since this is a external source, I'll include two SO's links as well that's about equally good (but not as potent or self explaining): https://stackoverflow.com/a/23164271/929999 Using cProfile results with KCacheGrind Here's a tl-dr version: python -m cProfile -o profile_data.pyprof your_script.py pyprof2calltree -i profile_data.pyprof -k This should render a so called, "call tree", of all the executions your code did, how long they took and how much memory they used up. All the way from start to bottom of your application. However, I strongly suggest you do 1 rendering sequence and add a exit(1) after the first render. Just so you profile 1 run, not 60 per second. Keywords to search for to get a hang of why your code is slow: Python, profiling, kcachegrind, cprofile, cprofiling, callstack. Spoiler alert To solve the majority of your problems, move all I/O intensive operations (loading images, creating shapes etc) into the __init__ call of your main class. The end product would look something like this instead: class Main(object): def __init__(self): self.label = pyglet.text.Label('Pizzas: 0', font_size=100, color=(0, 0, 0, 255), x=win_width//2, y=win_height - 100, anchor_x='left', anchor_y='top') self.points = 0 self.number = 1 self.background_img = pyglet.resource.image('pizza_clicker.png') self.background_img.width = (win_width/5)*4 self.background_img.height = win_height sidebar_pattern = pyglet.image.SolidColorImagePattern(c…
accepted answer of: http://stackoverflow.com/q/51098711
answers question: http://stackoverflow.com/q/51098711
has comment: http://stackoverflow.com/comment/89263727

http://stackoverflow.com/comment/89244346
has text: use the absolute path of the crawl and mycrawler files in the command
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51129668
type: Comment

http://stackoverflow.com/a/51013223
type: Answer
score: 2
has body: You can use a single numpy.where: low, high = 300, 500 df['score'] = np.where(df['Amount'].between(low, high), 100, 100 - np.maximum(low - df['Amount'], df['Amount'] - high)/100) print(df) orderID Amount score 0 0 340.0 100.0 1 1 200.0 99.0 2 2 10.0 97.1 3 3 500.0 100.0 4 4 700.0 98.0 The logic is as follows: If within the range, choose 100. If above the range, df['Amount'] - high &gt; 0 &gt; low - df['Amount']; and vice versa. We take the maximum to ensure only the positive value is used.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51013059

http://stackoverflow.com/comment/89262758
comment on: http://stackoverflow.com/a/51138058
has text: Hmm; curious why `pip` wasn't found in your virtual-env. Did you `source venv/bin/activate`? Is there a `pip` script in the `venv/bin/` directory?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/54342260
score: 0
answers question: http://stackoverflow.com/q/51073126
type: Answer
has body: Any instance of tornado.web.Application has default_router: &gt;&gt;&gt; import tornado.web &gt;&gt;&gt; import tornado.routing &gt;&gt;&gt; r1 = tornado.routing.Rule(r'/', MainHandler, name="/") &gt;&gt;&gt; r2 = tornado.routing.Rule(r'/sub/[\w-]+/', SubHandler, name="/sub/{name of}") &gt;&gt;&gt; app_tornado = tornado.web.Application([r1, r2]) &gt;&gt;&gt; app_tornado.default_router.rules [Rule(&lt;tornado.routing.AnyMatches object at 0x7f603cadd0b8&gt;, &lt;tornado.web._ApplicationRouter object at 0x7f603cadd080&gt;, kwargs={}, name=None)] &gt;&gt;&gt; app_tornado.default_router.rules[0].target.rules [Rule('/', &lt;class '__main__.MainHandler'&gt;, kwargs={}, name='/'), Rule('/sub/[\\w-]+/', &lt;class '__main__.SubHandler'&gt;, kwargs={}, name='/sub/{name of}')] So, you can add rule: &gt;&gt;&gt; app_tornado.default_router.rules[0].target.add_rules([('/new_rule/', MainHandler)]) &gt;&gt;&gt; app_tornado.default_router.rules[0].target.rules [Rule('/', &lt;class '__main__.MainHandler'&gt;, kwargs={}, name='/'), Rule('/sub/[\\w-]+/', &lt;class '__main__.SubHandler'&gt;, kwargs={}, name='/sub/{name of}'), Rule(&lt;tornado.routing.PathMatches object at 0x7f603cadd1d0&gt;, &lt;class '__main__.MainHandler'&gt;, kwargs={}, name=None)] May be it what you want.

http://stackoverflow.com/comment/89161292
has text: I honestly don't get the distinction, perhaps it's time for me to eat humble pie. Please explain what I'm not seeing.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51086305

http://stackoverflow.com/q/51018493
has answer: http://stackoverflow.com/a/51018575
tagged with: sql
favorite count: 0
has body: I am using python sql cursor to dynamically access my database and I am in a situation where I want to use a variable in place of a table name. So far all of my attempts have resulted in syntax errors, although I (think?) I am doing things as expected? Unless a table name as a variable is different from a value as a variable: here is what I currently have: cursor.execute("INSERT INTO %s (word=%s,item_id=%s,word_tag=%s,unstemmed_word=%s, word_position=%s, TF=%s, normalized_term_frequency=%s, sentence=%s,anthology_id=%s) "%(table_name, stemmedWord,fle.split()[0], str(word[1]), uniqeWord, word_pos, TF, normalized_term_frequency, sentence, fle.split()[1].split(".")[0])) and I have also tried this: cursor.execute("INSERT INTO %s (word,item_id,word_tag,unstemmed_word, word_position, TF, normalized_term_frequency, sentence,anthology_id) values(%s, %s,%s, %s, %s, %s, %s, %s, %s)",(table_name, stemmedWord,fle.split()[0], str(word[1]), uniqeWord, word_pos, TF, normalized_term_frequency, sentence, fle.split()[1].split(".")[0]))
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89029794
tagged with: python
has answer: http://stackoverflow.com/a/51018905
score: 2
downvote count: 0
has title: Using a variable for a table name with python sql cursor
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/89152226
score: 0
has text: I'd be very thankful to you if you solved this or guided me on this thank you !
type: Comment
comment on: http://stackoverflow.com/a/51081803
type: AnswerComment

http://stackoverflow.com/a/75735369
has body: Just set debug=False and check your logs
score: 0
answers question: http://stackoverflow.com/q/51149185
type: Answer

http://stackoverflow.com/comment/89042070
comment on: http://stackoverflow.com/a/51024399
score: 0
type: AnswerComment
has text: yup i'm trying it
type: Comment

http://stackoverflow.com/q/51163887
has body: I have a project that I'm working on it, I'm using Mininet to check and work on SDN's performance and now I would like to use PHP to check the performance analysis vs python. I did some searches but I couldn't any helpful things. Could you please let me know if there is a way to do that or even if that is possible? Thank you in advance for your support and help.
answer count: 0
has comment: http://stackoverflow.com/comment/89312630
tagged with: sdn
has title: is there a way to use php with mininet like test use php for performance analysis?
type: Question
tagged with: mininet
has comment: http://stackoverflow.com/comment/89371822
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: php

http://stackoverflow.com/q/51055970
has body: enter image description hereI made registration folder under my templates folder and add these thwo files(login.html & logout.html) in this folder.when i runserver i got no error but my login template in not rendering.only base template is render.please guide me? here is all my code. Login.html {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} Log-in {% if form.errors %} Your username and password didn't match. Please try again. {% else %} Please, use the following form to log-in. If you don't have an account register here {% endif %} {{ form.as_p }} {% csrf_token %} Forgotten your password? {% endblock %} urls.py from django.urls import path from django.contrib.auth.views import LogoutView, LoginView from . import views urlpatterns = [ path('', views.dashboard, name='dashboard'), #login and logout path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), ] views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) setting.py from django.urls import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') base.html {% load staticfiles %} {% block title %}{% endblock %} Bookmarks {% if request.user.is_authenticated %} My dashboard Images People {% endif %} {% if request.user.is_authenticated %} Hello {{ request.user.first_name }}, Logout {% else %} Login {% endif %}
type: UnansweredQuestion
has title: django built-in authentication views not rendering templates
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89102482
type: Question
has comment: http://stackoverflow.com/comment/89103106
has comment: http://stackoverflow.com/comment/89104352
linked to: http://stackoverflow.com/q/15467831
has comment: http://stackoverflow.com/comment/89103210
score: 0
has comment: http://stackoverflow.com/comment/89103557

http://stackoverflow.com/comment/89249409
type: Comment
has text: Thanks a lot for your help! And for a such detailed explanation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51125474

http://stackoverflow.com/q/51083092
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89156312
tagged with: python
has comment: http://stackoverflow.com/comment/89164765
tagged with: many-to-many
answer count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/89156624
upvote count: 1
has comment: http://stackoverflow.com/comment/89156150
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/22355890
type: Question
has comment: http://stackoverflow.com/comment/89156863
has body: I have these class models: class Application(Base): __tablename__ = 'applications' identifier = Column(Integer, primary_key=True) name = Column(String) description = Column(String) level1 = relationship("Teams", secondary='assoc_apps_teams', back_populates='support_1') level2 = relationship("Teams", secondary='assoc_apps_teams', back_populates='support_2') class Teams(Base): __tablename__ = 'teams' identifier = Column(Integer, primary_key=True) name = Column(String) description = Column(String) support_1 = relationship("Application", secondary='assoc_apps_teams', back_populates='level1') support_2 = relationship("Application", secondary='assoc_apps_teams', back_populates='level2') class AssocAppsTeams(Base, DictSerializable): __tablename__ = 'assoc_apps_teams' identifier = Column(Integer, primary_key=True) apps_id = Column(Integer, ForeignKey("applications.identifier"), nullable=False) support1_id = Column(Integer, ForeignKey("teams.identifier"), nullable=False) support2_id = Column(Integer, ForeignKey("teams.identifier"), nullable=False) if __name__ == "__main__": app = model.Application("app", "desc") session.add(app) session.commit() session.close() Consedering that an application has 2 support levels, each level can have one or more than one team ( each support is a team). When I run my script I get this error: sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Applications.support1 - there are multiple foreign key paths linking the tables via secondary table 'assoc_apps_levels'. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables. In this case, I have a relationship many to many: an application is managed by two levels of support that are teams, and each support can manage more than one application. How to map this relationship correctly??
tagged with: foreign-keys
downvote count: 0
has title: Many to many relationship in sqlAlchemy with two foreign keys to the same table
score: 1
has comment: http://stackoverflow.com/comment/89158782
favorite count: 0
has comment: http://stackoverflow.com/comment/89164342
has comment: http://stackoverflow.com/comment/89156562
has comment: http://stackoverflow.com/comment/89156916

http://stackoverflow.com/comment/89024782
type: Comment
score: 0
has text: Silvio Mayolo...obviously, i'm a beginner...but the issue is, Python seems to lack any good resource online...with any other language, those resources would've been easily found
comment on: http://stackoverflow.com/q/51016044
type: QuestionComment

http://stackoverflow.com/q/51144365
has title: async def and call stack
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89273059
tagged with: python
has answer: http://stackoverflow.com/a/51147818
has comment: http://stackoverflow.com/comment/89292229
has body: When using asyncio with Python 3.6, if one function deep in the callstack is async, do I need to make the whole stack async and put await at every call? For example I have: class FileDataSource: def getData(self): return pd.read_csv('/some/file') class SocketDataSource: def __init__(self, host, port): self.reader, self.writer = yield from asyncio.open_connection(host, port) async def getData(self): data = await self.reader.readuntil(b'\n\n') return data def func1(datasource): func2(datasource) def func2(datasource): func3(datasource) def func3(datasource): datasource.getData() def main(host, port): if host is None: func1(FileDataSource()) else: loop = asyncio.get_event_loop() for timeout in range(1, 60): loop.call_later(timeout, func1(SocketDataSource(host, port))) loop.run_forever() In the above example, do I need to make the whole call stack of func1 / 2 / 3 as async and await on all of them? (I am afraid answer is yes) Can I interchangeably pass FileDataSource and SocketDataSource to func1 or do I need to change the whole call hierarchy based on async vs non-async calls? What would be the best way to design something like this which can run as a server or a batch? Thanks a lot in advance for all help!
has comment: http://stackoverflow.com/comment/89448100
type: Question
upvote count: 4
downvote count: 0
score: 4
tagged with: python-asyncio
answer count: 1
favorite count: 0

jupyter
tags question: http://stackoverflow.com/q/51051902
tags question: http://stackoverflow.com/q/51159578
type: Tag
tags question: http://stackoverflow.com/q/51090853
tags question: http://stackoverflow.com/q/51090389
tags question: http://stackoverflow.com/q/51105475
tags question: http://stackoverflow.com/q/51093533
tags question: http://stackoverflow.com/q/51127814
tags question: http://stackoverflow.com/q/51034915
tag name: jupyter
tags question: http://stackoverflow.com/q/51028292
tags question: http://stackoverflow.com/q/51032159
tags question: http://stackoverflow.com/q/51019813
tags question: http://stackoverflow.com/q/51102243

http://stackoverflow.com/q/51153760
has title: Vehicle reloading at depot and continuing
tagged with: python
has answer: http://stackoverflow.com/a/51189814
accepted answer: http://stackoverflow.com/a/51189814
tagged with: or-tools
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89332417
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89359990
upvote count: 1
answer count: 1
downvote count: 0
has body: I try to generate a delivery plan using ORTOOL and Python. My constraints are the following: Each vehicle has a start time and an end time Each vehicle has its own capacity of stored items, taken at the depot Each vehicle has its own speed. For 1 and 3, it works fine using AddDimensionWithVehicleTransits. For the second constraint, if the vehicle is empty, it has to return to the depot to retrieve items and start again. I've seen the refuel example, so setting a node with a capacity &lt; 0 works fine. But in my case, the depot is the refuel point and the solver doesn't make the vehicle return to it. My dimension is set like that: routing.AddDimensionWithVehicleCapacity( capacity_evaluator, 0, [capacity[vehicle].get('capacity', dataconfig.default_capacity) for vehicle in data.vehicles], True, 'Capacity' ) Basically, with a max capacity of 4: Route for Vehicle1 [LOCATION, START, CAPACITY] ['Depot', '4:0', 0] [u'7', '9:0', 1] [u'6', '10:0', 4] ['Depot', '11:00', 4] What I need: Route for Vehicle1 [LOCATION, START, CAPACITY] ['Depot', '4:0', 0] [u'Location1', '9:0', 1] [u'Location2', '10:0', 4] ['Depot', '11:00', 0] [u'Location3', '12:0', 1] [u'Location4', '13:0', 2] [u'Location5', '14:0', 4] ['Depot', '15:00', 0] Any idea about how to put the refuel point to the depot ? Regards
favorite count: 0
has comment: http://stackoverflow.com/comment/89327774

http://stackoverflow.com/comment/89199733
type: Comment
type: QuestionComment
has text: @UCProgrammer your class shares no state between methods, you never use `self`. Anyway, `set_options` takes a `self` parameter, this is why your code is failing when you call it in the `dict` literal: `set_options(options)}`. Why did you think you didn't need to pass it? Anyway, you could pass it anything, since you *never do anything with it*. So `set_options(None, options)` would work, but maybe you should refractor your code not to needlessly use a class.
comment on: http://stackoverflow.com/q/51105907
score: 0

http://stackoverflow.com/comment/89090948
type: Comment
has text: Yeah something is wrong in the user's setup. Your example shows it working as expected.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51049886

http://stackoverflow.com/a/51056990
answers question: http://stackoverflow.com/q/51049664
has body: An exec error indicates you took the wrong OS file for geckodriver. See the below for all release https://github.com/mozilla/geckodriver/releases As of today (27th Jun 2018), you should probably be picking below https://github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-arm7hf.tar.gz Also make sure to do chmod +x /home/pi/Desktop/geckodriver So that it has executable rights
score: 0
type: Answer

http://stackoverflow.com/a/51051759
has body: import json import bs4 import urllib data = '&lt;input id="ctl00_BodyContentPlaceholder_C013_RadListView1_ctrl1_rlb1_ClientState" name="ctl00_BodyContentPlaceholder_C013_RadListView1_ctrl1_rlb1_ClientState" type="hidden" autocomplete="off" value="{&amp;quot;text&amp;quot;:&amp;quot;Documents&amp;quot;,&amp;quot;value&amp;quot;:&amp;quot;&amp;quot;,&amp;quot;target&amp;quot;:&amp;quot;&amp;quot;,&amp;quot;navigateUrl&amp;quot;:&amp;quot;/procurement/procurement-bids/constructionprocurementdetail?Title=Lakeland Adult Daycare Center Roof Replacement 18-785&amp;quot;,&amp;quot;primary&amp;quot;:false}"&gt;' # cook up some soup soup = bs4.BeautifulSoup(data) # extract the relevant attribute vals_as_string = soup.html.body.input.attrs['value'] # it's urlencoded, so decode it unquoted_vals_as_string = urllib.parse.unquote(vals_as_string) # turns out, it's json vals_as_json = json.loads(unquoted_vals_as_string) # well, json converts to dict, so there's our target navigateUrl = vals_as_json['navigateUrl']
answers question: http://stackoverflow.com/q/51051351
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51020482
type: Question
tagged with: numpy
has title: How to add more parameters while predicting using LSTM
tagged with: keras
favorite count: 0
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
tagged with: tensorflow
score: 1
has body: What changes should I make in this code to predict the output based on all the parameters listed on the dataset and predict the next day opening stock price? When I tried to run it showed an out of shape error. This code works fine with only 1 parameter. My code is as follows: dataset_train = pd.read_csv('ongc_train.csv') dataset_train = dataset_train.dropna() training_set = dataset_train.iloc[:, 1:2].value # Creating a dataset with 60 timesteps and 1 output X_train = [] Y_train = [] for i in range(60,2493): X_train.append(training_set_scaled[i-60:i, 0]) Y_train.append(training_set_scaled[i, 0]) X_train, Y_train = np.array(X_train), np.array(Y_train) # Reshaping X_train np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # Fitting the RNN to the training set regressor.fit(X_train, Y_train, epochs=100, batch_size=32) # Getting the predicted stock price of 2017 # Concatenating the original training and test set # Vertical concatenating of open stock prices dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis=0) inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values inputs = inputs.reshape(-1, 1) inputs = sc.transform(inputs) X_test = [] for i in range(60, 61): X_test.append(inputs[i-60:i, 0]) X_test=np.array(X_test) X_test=np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) predicted_stock_price = regressor.predict(X_test) predicted_stock_price = sc.inverse_transform(predicted_stock_price) actual = dataset_test.iloc[:, 1:2].values print("Predicted Stock Price:",predicted_stock_price) Thank you.
tagged with: lstm

http://stackoverflow.com/comment/89185182
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51051692
has text: sorry to come back to you on this and if the protocol is to create a new post, happy to do this. I have a new usercase that needs me to do a loop and I've struggled to integrate this. I've asked it as a new answer.

http://stackoverflow.com/a/51078672
answers question: http://stackoverflow.com/q/51077486
type: Answer
has comment: http://stackoverflow.com/comment/89193748
has body: According to the readme of shuffle.NET, you need to provide a path to the config file as argument, as following: python main.py --config config/test.json. And there should be a config. EDIT: After I looked into it: Apparently, the error is right and add_check_numerics_ops is incompatible with while_loops and stuff. In the code you can also see that this line was just added for debugging to handle nans, which normally should not occur. Therefore I guess you can just comment out this part. Finally I found that there is this issue on the project too, which gives me the feeling that there is really an issue with the code.
has comment: http://stackoverflow.com/comment/89153363
has comment: http://stackoverflow.com/comment/89184098
score: 0

http://stackoverflow.com/comment/121555281
type: Comment
has text: I don't know if it's only me but I had to create a `def create_app():` surrounding all my code with a `return app` at the end, and instead of your `if create_app():` I did `if __name__ == '__main__': app = create_app() app.run()` Maybe I have missed something from your example but anyway it works for me like that. I wanted to share if someone like me didn't understand. With your example I get `SyntaxError: 'return' outside function`
type: AnswerComment
comment on: http://stackoverflow.com/a/54381386
score: 0

http://stackoverflow.com/comment/89286960
comment on: http://stackoverflow.com/q/51101224
type: Comment
type: QuestionComment
score: 0
has text: Is your dev endpoint in a public subnet?

http://stackoverflow.com/comment/110365100
has text: is there any way to getElementByType(image)?
type: AnswerComment
comment on: http://stackoverflow.com/a/51055187
score: 0
type: Comment

http://stackoverflow.com/a/51138749
type: Answer
has body: You need to pass self (i.e. c) to cExample.pri (i.e. self.func). But __missing__ won't allow you to do this: it receives only the key. You can rewrite it using function-based decorator: import functools def memorize2(f): cache = {} @functools.wraps(f) def wrapper(*args): if args not in cache: cache[args] = f(*args) return cache[args] return wrapper class cExample(): @memorize2 def pri(self, text): return self.text(text) def text(self, text): return text c = cExample() print(c.pri('hi')) # hi (I'm using functools.wraps not to lose the original name of decorated method). In this approach self will be passed to wrapper as positional arg and proxied to cExample.pri.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51138226
upvote count: 1

http://stackoverflow.com/comment/89276236
type: Comment
comment on: http://stackoverflow.com/a/51145816
score: 0
type: AnswerComment
has text: Thanks. Sent you an email.

spring
tags question: http://stackoverflow.com/q/51034490
type: Tag
tag name: spring

http://stackoverflow.com/a/51093545
accepted answer of: http://stackoverflow.com/q/51093387
score: 1
has comment: http://stackoverflow.com/comment/89175370
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89209678
type: Answer
has body: I believe you have two issues with your code. Firstly the Meta attribute class on StudentsTable needs to inherit the UserTable.Meta attribute, or else it will not have model defined: class StudentsTable(UsersTable): # Call UsersTable constructor def __init__(self, *args, **kwargs): super(StudentsTable, self).__init__(*args, **kwargs) print(self.edit_link) # Verify edit_link has been generated class Meta(UsersTable.Meta): sequence = ('firstname','lastname','emailaddress','phonenumber','defaultsignaturescanfile','classid') Secondarily, the docs for django-tables2 says that sequence enumerates columns. Columns are either fields on the underlying model or column attributes of the table class: class StudentsTable(UsersTable): edit_link = tables.LinkColumn(viewname='wakemeup:edit_object', text='Editar') Rather than defining editLink on the instance in the __init__ method. To load keyword arguments for the link from the model and table instance, you'll need to pass accessor instances to the Column rather than the literal kwarg values. The docs for LinkColumn indicate that should be done like this: from django_tables2.utils import A class StudentsTable(UsersTable): edit_link = tables.LinkColumn(viewname='wakemeup:edit_object', text='Editar', kwargs={"name": A("name")) This means you'll need to define which kwargs you need explicitly, rather than dynamically, which should not be a problem for you given that these are URL arguments that are defined as a contract somewhere.
upvote count: 1
answers question: http://stackoverflow.com/q/51093387

http://stackoverflow.com/q/51129513
answer count: 2
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium
downvote count: 3
has title: Facing "TypeError: object of type 'WebElement' has no len()" while executing the below script
has body: Iam trying to check whether the product is 12 or not by using assert equal function.Please check the below script i have tried: def test_search(self): driver=self.driver driver.get("http://magento-demo.lexiconn.com/") driver.maximize_window() driver.find_element_by_xpath(".//*[@id='search']").send_keys("Bed &amp; Bath") driver.find_element_by_xpath(".//*[@id='search_mini_form']/div[1]/button").click() lis = driver.find_element_by_xpath("//h2[@class='product-name'] / a") self.assertEqual(12,len(lis))
has comment: http://stackoverflow.com/comment/89243946
has comment: http://stackoverflow.com/comment/89243832
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89244082
upvote count: 4
score: 1
has answer: http://stackoverflow.com/a/51129577
favorite count: 0
has comment: http://stackoverflow.com/comment/89243920
type: Question
has answer: http://stackoverflow.com/a/51129644

http://stackoverflow.com/a/51242403
score: -1
answers question: http://stackoverflow.com/q/51111046
type: Answer
has body: You are importing db from Talks2.py in models.py file and again in routes.py declaring again. You haven't shared the code of Talks2.py file. What I am suspecting is you are declaring app and db object multiple times and replacing it with others. Just do import in the proper way and your model will be detected by the flask. The simplest solution is to declare app &amp; db in Talks2.py, then import both in models.py and then from models.py import app &amp; db in routes.py. This will resolve your problem. Also, it should be flask db migrate instead of flask migrate db. For more information refer to these commands: To create a migration repository: flask db init To Generate Migration Script (Make sure to reviewed and edited, as Alembic currently does not detect every change you make to your models) flask db migrate To apply the migration to the database flask db upgrade To see all the commands that are available run this command: flask db --help For more info refer this official doc. Let me know if this didn't help.
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/51121875
tagged with: python-3.x
answer count: 12
linked to: http://stackoverflow.com/q/54537030
has answer: http://stackoverflow.com/a/51121932
has answer: http://stackoverflow.com/a/54541510
has answer: http://stackoverflow.com/a/74661206
has title: How to run Docker with python and Java?
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/49962999
has answer: http://stackoverflow.com/a/58293896
has answer: http://stackoverflow.com/a/72021175
tagged with: java
has answer: http://stackoverflow.com/a/52688196
score: 33
type: Question
has comment: http://stackoverflow.com/comment/89229238
has answer: http://stackoverflow.com/a/67986398
accepted answer: http://stackoverflow.com/a/51171447
has answer: http://stackoverflow.com/a/62269189
linked to: http://stackoverflow.com/q/29586487
tagged with: docker
has answer: http://stackoverflow.com/a/76269459
has answer: http://stackoverflow.com/a/51171447
possible better answer: http://stackoverflow.com/a/58293896
linked to: http://stackoverflow.com/q/38568476
has answer: http://stackoverflow.com/a/51122958
linked to: http://stackoverflow.com/q/30172605
has answer: http://stackoverflow.com/a/61489619
tagged with: python
has body: I need both java and python in my docker container to run some code. This is my dockerfile: It works perpectly if I don't add the FROM openjdk:slim #get python FROM python:3.6-slim RUN pip install --trusted-host pypi.python.org flask #get openjdk FROM openjdk:slim COPY . /targetdir WORKDIR /targetdir # Make port 81 available to the world outside this container EXPOSE 81 CMD ["python", "test.py"] And the test.py app is in the same directory: from flask import Flask import os app = Flask(__name__) @app.route("/") def hello(): html = " Test:{test} " test = os.environ['JAVA_HOME'] return html.format(test = test) if __name__ == '__main__': app.run(debug=True,host='0.0.0.0',port=81) I'm getting this error: D:\MyApps\Docker Toolbox\Docker Toolbox\docker.exe: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"python\": executable file not found in $PATH": unknown. What exactly am I doing wrong here? I'm new to docker, perhaps I'm missing a step. Additional details My goal I have to run a python program that runs a Java file. The python library I'm using requires the path to JAVA_HOME. My issues: I do not know Java, so I cannot run the file properly. My entire code is in Python, except this Java bit The Python wrapper runs the file in a way I need it to run.
linked to: http://stackoverflow.com/q/44732303
upvote count: 33
favorite count: 0

http://stackoverflow.com/q/51030122
has title: Flask: Why is my view not rendering the template I want it to?
duplicate of: http://stackoverflow.com/q/10722968
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51030369
tagged with: flask
score: 0
tagged with: http://stackoverflow.com/tag/html
has body: Here is the class I created, model of the flask mega tutorial's RegistrationForm class eyeReaderInput(FlaskForm): article = StringField('Article') submit = SubmitField('Enter') And I've implemented that class in this view: @app.route('/eyereader', methods=['GET', 'POST']) def eyereader(): form = eyeReaderInput() sTuple = () if form.validate_on_submit(): string = wikipedia.page(form.article.data) for chunk in textwrap.wrap(string, 15): sTuple += (chunk,) return render_template('eyereader.html', string = sTuple, form = form) else: return render_template('eyereader.html', form = form) with this being my template of eyereader.html Title {% if string %} {% for s in string %} [{{s}}] {% endfor %} {% else %} Please input an article name {{ form.article.label}} {{ form.article() }} {{ form.submit() }} {% endif %} What I'm hoping to do is for the user to initially access the eyereader site using a 'GET' request (which is what happens when I look at my console), and once the user inserts the wikipedia article he wishes to read, it sends a 'POST' request with a new string parameter which will make {% is string %} true and instead show the wikipedia text. However when I'm testing this, both 'GET' and 'POST' requests end up going to the input page. Does anyone know what I may be able to change to get this to work? Thanks.
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89052807
linked to: http://stackoverflow.com/q/10722968

http://stackoverflow.com/a/51100863
has body: If your just writing each string on a seperate line, you can just keep it simple and just write each item with a \n: lst= ['name1@domain.com', 'name2@domain.com', 'name3@domain.com'] def write_to_csv(list_of_emails): with open('emails.csv', 'w') as csvfile: for domain in list_of_emails: csvfile.write(domain + '\n') write_to_csv(lst) Which Outputs: name1@domain.com name2@domain.com name3@domain.com You also shouldn't use list as a variable name, since it shadows the builtin function list.
score: 4
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51100680

http://stackoverflow.com/comment/89057802
comment on: http://stackoverflow.com/q/51032737
type: Comment
type: QuestionComment
has text: If you want to handle messages rather than bytes with TCP, you have to come up a message-framing protocol. The simplest one is that each message is a bunch of bytes ending in a `b'\n'`, or a bunch of UTF-8-encoded characters ending in UTF-8-encoded `'\n'`. This doesn't work if your messages can include embedded newlines, but if they can't, it's dead easy, especially because the `makefile` method on `socket` objects does the whole protocol implementation for you.
score: 0

http://stackoverflow.com/q/51140994
tagged with: pyqtgraph
score: 3
has answer: http://stackoverflow.com/a/55401579
has body: I have a time series waveform plot made with pyqtgraph. The user should be able to zoom in and out to various points in time (x-axis), and the y-axis should automatically scale to whatever data is visible within the current range of x values. I believe that enableAutoRange and setAutoVisible should allow this, but it doesn't seem to work. I have unlocked the aspect ratio but this doesn't seem to help. A minimal example is below, please could anyone suggest how to get this working? Ideally when you zoom in to the low-amplitude data on the right hand side, the y-axis should scale up so that the sine wave is visble. import numpy import pyqtgraph x_data = numpy.linspace(0, 100, num=10000) y_data = 1000*numpy.sin(x_data) y_data[5000:] = numpy.sin(x_data[5000:]) plt = pyqtgraph.plot(x_data, y_data) plt.setMouseEnabled(x=True,y=False) vb = plt.getViewBox() vb.setAspectLocked(lock=False) vb.setAutoVisible(y=1.0) vb.enableAutoRange(axis='y', enable=True) One interesting thing is that if you zoom to the right hand side, and then right click and select Y-Axis>Auto, it works as expected.
upvote count: 3
type: Question
has title: Autoscaling y axis to visible data in pyqtgraph
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51092267
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89172857
score: 0
has title: Merging Series to Single Output - pandas
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89172967
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51092551
type: UnansweredQuestion
tagged with: python
has body: I want a single series as the output and not multiple series like below: Current Output: 0 5.98% to 35.89% 1 1% to 6% dtype: object 0 1% to 6% dtype: object 0 6.99% to 24.99% 1 6.99% to 24.99% 2 6.99% to 24.99% 3 6.99% to 24.99% dtype: object 0 6.99% to 24.99% dtype: object Desired Output: 0 5.98% to 35.89% 1 1% to 6% 0 1% to 6% 0 6.99% to 24.99% 1 6.99% to 24.99% 2 6.99% to 24.99% 3 6.99% to 24.99% 0 6.99% to 24.99% dtype: object However with my current code I can't get the series to consolidate. I have attempted to make it into a dataframe with all the information I want appended to it; however, when trying to combine all the dataframes in the output I haven't been able to get it to combine either. I know I am running a loop before the creation of the dataframe for the regex operator I am doing to some text before creating the strings/dataframe which is most likely causing the multiple outputs. Is there a way I can combine it post loop? Code below: paragraph = soup.find_all(text=re.compile('[0-9]%')) for n in paragraph: matches = [] matches.extend(re.findall('(?i)\d+(?:\.\d+)?%\s*(?:to|-)\s*\d+(?:\.\d+)?%', n.string)) sint = pd.Series(matches) if sint.empty: continue print(sint) With Edits: paragraph = soup.find_all(text=re.compile('[0-9]%')) vals = [] for n in paragraph: matches = re.findall('(?i)\d+(?:\.\d+)?%\s*(?:to|-)\s*\d+(?:\.\d+)?%', n.string) vals.append(pd.Series(matches)) sint = pd.concat(vals) print(sint) New Output: 0 6.99% to 24.99% dtype: object

http://stackoverflow.com/q/51148382
type: Question
has body: Is it possible to make a windows form application in visual studio using c# for the GUI and then use python in order to make api requests and database calls? And if so how would one go about doing this?
tagged with: c#
answer count: 1
tagged with: user-interface
downvote count: 0
has answer: http://stackoverflow.com/a/51148433
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: visual-studio
score: 2
tagged with: web-applications
has title: combining both c# and python in order to make a windows form application in vs

http://stackoverflow.com/a/51076443
has body: A vectorized solution: Remember that you can compare all elements in b with all elements in a using broadcasting: b[:, None] &gt; a # array([[ True, False, False, False], # b[0] &gt; a[:] # [ True, True, False, False]]) # b[1] &gt; a[:] And now find the index of the last True value in each row, which equals to the first False value in each row, minus 1 np.argmin((b[:, None] &gt; a), axis=1) - 1 # array([0, 1]) Note that there might be an ambiguity as to what a returned value of -1 means. It could mean b[x] was larger than all elements in a, or b[x] was not larger than any element in a In our data, this means a = np.asarray([10, 20, 30, 40]) b = np.asarray([9, 12, 25, 39, 40, 41, 50]) mask = b[:, None] &gt; a # array([[False, False, False, False], # 9 is smaller than a[:], case 2 # [ True, False, False, False], # [ True, False, False, False], # [ True, True, True, False], # [ True, True, True, False], # [ True, True, True, True], # 41 is larger than a[:], case 1 # [ True, True, True, True]]) # 50 is larger than a[:], case 1 So for case 1 we need to find rows with all True values: is_max = np.all(mask, axis=1) And for case 2 we need to find rows with all False values: none_found = np.all(~mask, axis=1) This means we can use the is_max to find and replace all case 1 -1 values with a positive index mask = b[:, None] &gt; a is_max = np.all(mask, axis=1) # array([False, False, False, False, False, True, True]) idx = np.argmin(mask, axis=1) - 1 # array([-1, 0, 0, 2, 2, -1, -1]) idx[is_max] = len(a) - 1 # array([-1, 0, 0, 2, 2, 3, 3]) However be aware that the index -1 has a meaning: Just like 3 it already means "the last element". So if you want to use idx for indexing, keeping -1 as an invalid value marker may cause trouble down the line.
has comment: http://stackoverflow.com/comment/89142133
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51075744
answers question: http://stackoverflow.com/q/51075744
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89142526
has comment: http://stackoverflow.com/comment/89142164
has comment: http://stackoverflow.com/comment/89143664
has comment: http://stackoverflow.com/comment/89141945
has comment: http://stackoverflow.com/comment/89142837
type: Answer

http://stackoverflow.com/comment/89300367
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51144253
score: 1
has text: The fastest LP solvers are probably the commercial codes Cplex, Gurobi and Xpress. CBC is a good open source solver. Note that if your problem is very dense, all LP solvers will have a difficult time: they are designed to handle large, sparse problems. Note that you can try out many solvers at [NEOS](https://neos-server.org/neos/) (the easiest is to generate an MPS file for that).

http://stackoverflow.com/comment/89281316
has text: What have you tried so far? Edit your question and post the relevant code parts.
score: 0
comment on: http://stackoverflow.com/q/51148685
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/138842728
comment on: http://stackoverflow.com/a/51040587
has text: Gave `date: illegal option -- d` in macOS 14.2.1
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89064139
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51035794
has text: @Anthony Considering that they seem to be advertising that they're PHP-5.5-clean, which was a big dealhalf a decade ago (maybe a bit later for pure Windows shops), I guess I wouldn't be surprised if they only support Python 2.7…

http://stackoverflow.com/comment/89106546
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51058078
type: QuestionComment
has text: Did you rather mean `[0, 3, 1, 2, 4]`?

http://stackoverflow.com/comment/89249944
comment on: http://stackoverflow.com/a/51132371
score: 0
has text: Are you looking to use a dedicated service account to make API calls? Or are you looking to use your own account to make the call?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51045491
tagged with: python-asyncio
tagged with: python
has comment: http://stackoverflow.com/comment/89083217
downvote count: 0
accepted answer: http://stackoverflow.com/a/51047731
has title: Start processing async tasks while adding them to the event loop
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51047731
has comment: http://stackoverflow.com/comment/89099484
type: Question
answer count: 1
favorite count: 0
has body: A common pattern with asyncio, like the one shown here, is to add a collection of coroutines to a list, and then asyncio.gather them. For instance: async def some_task(i): # Do something asynchronously with i tasks = [some_task(i) for i in range(100)] loop.run_until_complete(asyncio.gather(**tasks)) Here, the execution order of this code is such that none of the tasks are running while we build up the list. We add task 1 to the list, then task 2, etc. and then we add the tasks 1-100 to the event loop. However, I want task creation itself to be part of the event loop. I want task 1 to be scheduled immediately as it's created, and then when task is waiting for something on another thread, return to task creation and create task 2 and add it to the event loop. I believe this would give me better concurrency from my async code. Is this possible? For example, my first thought would be to put task creation into a coroutine and schedule tasks as they are created: async def some_task(i): # Do something asynchronously with i async def generate_tasks(loop): tasks = [] for i in range(100): task = loop.create_task(some_task(i)) tasks.append(loop) await asyncio.gather(**tasks) loop.run_until_complete(generate_tasks()) However, because my generate_tasks never uses await, execution is never passed back to the event loop, so the entirety of generate_tasks will run before some_task() is run at all. But then, if I await each task as they are created, it will wait for each task to complete before moving on to the next task, giving me no concurrency at all! async def generate_tasks(loop): tasks = [] for i in range(100): await some_task(i) loop.run_until_complete(generate_tasks())
upvote count: 3

http://stackoverflow.com/comment/89164488
has text: Found something about reaching the [Sent Items folder](https://stackoverflow.com/a/39911751/9094687), might be of some use.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51087601

http://stackoverflow.com/comment/127136547
comment on: http://stackoverflow.com/q/51069236
score: 0
type: Comment
type: QuestionComment
has text: the equivalent is {future}

http://stackoverflow.com/a/51138451
type: Answer
accepted answer of: http://stackoverflow.com/q/51137050
answers question: http://stackoverflow.com/q/51137050
score: 0
type: AcceptedAnswer
has body: change for row in range(1,rows + 1): for column in range(1,column +1): to for row in range(rows): # rows + 1 will result in 'out of range' for column in range(columns): # note 'columns' not 'column' and remove (or narrow) the try block as noted by Mel.

http://stackoverflow.com/comment/89064150
type: QuestionComment
has text: can you please add a class definition to the post?
score: 0
comment on: http://stackoverflow.com/q/51036121
type: Comment

http://stackoverflow.com/comment/89311934
comment on: http://stackoverflow.com/a/51164287
has text: try: `x**i` not `n**i`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51064113
score: 2
has body: The method you're looking for is str.find - even the documentation for str.index says it does the same except raising an error...
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89118286
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51064038
type: Answer
answers question: http://stackoverflow.com/q/51064038
has comment: http://stackoverflow.com/comment/89118213
has comment: http://stackoverflow.com/comment/89118555

http://stackoverflow.com/comment/89312189
type: Comment
score: 1
has text: Man, this just reminds me why every Python module I write that needs Py2 compatibility begins with `from __future__ import print_function`. None of this special purpose statement nonsense with weird side-effects. Learned something new today, and it mostly reminded me why I avoided learning that particular dusty corner of the old language. :-)
comment on: http://stackoverflow.com/a/51164438
type: AnswerComment

http://stackoverflow.com/comment/99113117
score: 0
type: Comment
has text: You can absolutely use pip to install dependencies in AWS using the Serverless Framework. I am doing that in an application I am developing.
type: AnswerComment
comment on: http://stackoverflow.com/a/54635818

http://stackoverflow.com/q/51083286
has comment: http://stackoverflow.com/comment/89155242
possible better answer: http://stackoverflow.com/a/51083332
accepted answer: http://stackoverflow.com/a/51083642
has comment: http://stackoverflow.com/comment/89154836
has title: Drop percentage of a dataframe [pandas]
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89155103
has comment: http://stackoverflow.com/comment/89154859
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51083642
upvote count: 2
has answer: http://stackoverflow.com/a/51083332
type: Question
has body: I have a dataset with a very long tail and wish to sample only 90% of the data. city score bangkok 60 kl 20 sydney 10 melbourne 5 dhaka 5 should be: city score bangkok 60 kl 20 sydney 10

http://stackoverflow.com/a/51134579
has body: request_data = request.POST; request_data['abc_pqr'] = request_data.get("abc-pqr")
has comment: http://stackoverflow.com/comment/89253437
type: Answer
has comment: http://stackoverflow.com/comment/89254540
has comment: http://stackoverflow.com/comment/89254515
score: 0
answers question: http://stackoverflow.com/q/51134530

http://stackoverflow.com/comment/89272286
type: Comment
type: QuestionComment
score: 7
comment on: http://stackoverflow.com/q/51144050
has text: Does it have to be regex? Why not split the string on space and count how many words start with a hashtag?

http://stackoverflow.com/comment/89111064
has text: But I have such two root folders that I maintain cache(for each) and compare the cache, based on the key. I evaluate value 1 in cache1 with value2 in cache2, if key1 is equal to key2. This is the goal. For this, nested dictionary would not work.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51033936

http://stackoverflow.com/q/51107814
tagged with: encode
tagged with: python
has answer: http://stackoverflow.com/a/51107922
favorite count: 0
tagged with: selenium
accepted answer: http://stackoverflow.com/a/51107922
upvote count: 1
tagged with: web-scraping
type: AnsweredQuestion
score: 1
has title: NoneType error during multi-page scrape
type: Question
tagged with: nonetype
answer count: 1
downvote count: 0
has body: I'm working on a web scraper and am close to getting what I need, but I can't figure out why I'm getting a NoneType error all of a sudden after it finishes scraping the fourth page (of 204). Here's my code: script_path = os.path.dirname(os.path.realpath(__file__)) driver = webdriver.PhantomJS(executable_path="/usr/local/bin/bin/phantomjs", service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) case_list = [] #this function launches the headless browser and gets us to the first page of results, which we'll scrape using main def search(): driver.get('https://www.courts.mo.gov/casenet/cases/nameSearch.do') if 'Service Unavailable' in driver.page_source: log('Casenet website seems to be down. Receiving "service unavailable"') driver.quit() gc.collect() return False time.sleep(2) court = Select(driver.find_element_by_id('courtId')) court.select_by_visible_text('All Participating Courts') case_enter = driver.find_element_by_id('inputVO.lastName') case_enter.send_keys('Wakefield &amp; Associates') year_enter = driver.find_element_by_id('inputVO.yearFiled') year_enter.send_keys('2018') driver.find_element_by_id('findButton').click() time.sleep(3) #scrapes table and stores what we need in a list of lists def main(): parties = [] dates = [] case_nums = [] html = driver.page_source soup = BeautifulSoup(html, 'html.parser') table = soup.findAll('table', {'class':'outerTable'}) for row in table: col = row.find_all('td', attrs={'class':'td1'}) col2 = row.find_all('td', attrs={'class':'td2'}) all_links = soup.findAll('a') for cols in col: if 'V' in cols.text: cols = cols.string cols.encode('utf-8').strip() cols = re.sub("\xa0'\'", '', cols).strip() parties.append(cols) for cols in col2: if 'V' in cols.text: cols = cols.string cols.encode('utf-8').strip() cols = re.sub("\xa0'\'", '', cols).strip() parties.append(cols) for link in all_links: raw_html = str(link) if 'goToThisCase' in raw_html: start = raw_html.find("('") + 2 end = raw_html.find("',") case = raw_html[start:e…

timer
tag name: timer
tags question: http://stackoverflow.com/q/51145690
type: Tag
tags question: http://stackoverflow.com/q/51102631

http://stackoverflow.com/comment/89307427
has text: From my experience, it looks like `move` sometimes bounds the position to the screen, sometimes not, and I don't understand which conditions triggers which behaviour.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51144336
type: Comment

http://stackoverflow.com/q/51025894
accepted answer: http://stackoverflow.com/a/51026251
has title: Python For-Loop over specific dates
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/51026321
has comment: http://stackoverflow.com/comment/89044324
score: 0
has answer: http://stackoverflow.com/a/51026251
tagged with: python
possible better answer: http://stackoverflow.com/a/51026321
has body: my question is about a simple For loop. I have a CSV file with an hourly performance over 4 years. The problem is that I need an average output per month. Therefore I use the sum of all outputs per month divided by the amount of outputs. My input file has the following format: power_output timestamp 2012-01-01 00:00:00 2335.215265 2012-01-01 01:00:00 3097.521354 2012-01-01 02:00:00 3412.639293 2012-01-01 03:00:00 3366.400549 2012-01-01 04:00:00 3431.050170 The form of the timestamp is yyyy-mm-dd and than the hour. My problem is now, that I'm not able to iterate with the for -loop over the timestamp for one month. Can someone help me?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89044458
tagged with: timestamp
type: Question

http://stackoverflow.com/comment/89044183
score: 0
comment on: http://stackoverflow.com/q/51025661
type: Comment
type: QuestionComment
has text: What is `collection1`?

timestamp
tags question: http://stackoverflow.com/q/51036659
tags question: http://stackoverflow.com/q/51040350
tag name: timestamp
tags question: http://stackoverflow.com/q/51080695
tags question: http://stackoverflow.com/q/51025894
tags question: http://stackoverflow.com/q/51110672
tags question: http://stackoverflow.com/q/51080432
type: Tag
tags question: http://stackoverflow.com/q/51078117

http://stackoverflow.com/q/51057611
tagged with: ssh
tagged with: python
has title: How to use sshkey with subprocess
has body: I'm trying to connect to a router over ssh and write a command to the shell. I think the connection works, because I get an empty output and not an error message. I know that I have to use a keyfile to connect really on the device. Maybe that's the reason why the output is empty. This is my code: mykey = os.path.expanduser('C:\\Users\\taaiaal1\\PycharmProjects\\hal_dmms_application\\dev_ssh') command = 'pcb_cli -u cwmpd pcb://ipc:[/var/run/IGD] -i \'?\'' ssh = subprocess.Popen(["ssh", username + '@' + host + ':' + port, command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = ssh.stdout.readlines() print(result) Where should I integrate the keyfile? I feel like checked every page google let me find and even in the subprocess python doc I couldn't find anything. Is this even possible? I'm using Python 3.
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/51058019
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/51057831
has answer: http://stackoverflow.com/a/51057831
has answer: http://stackoverflow.com/a/51058019
has comment: http://stackoverflow.com/comment/89105651
has answer: http://stackoverflow.com/a/51057950
score: 0
answer count: 3
tagged with: public-key

http://stackoverflow.com/a/53125632
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51046942
answers question: http://stackoverflow.com/q/51046942
upvote count: 2
has body: I answered a similar question yesterday with a demo. I based that almost entirely off of the example in the docs.. In the docs, assigning dynamic dependencies by yeilding tasks seems like the way they prefer. luigi.Config and dynamic dependencies can probably give you a pipeline of almost infinite flexibility. They also describe a dummy Task that calls multiple dependency chains here, which could give you even more control.
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/89173147
type: QuestionComment
comment on: http://stackoverflow.com/q/51092258
has text: I think you need to explain your goal more clearly. Do you mean you want to find sets of 3 words, with the 1st word in each set having 2 letters, the 2nd 4 letters, the 3rd 5 letters, with each letter from your base string e.g. `LNDJOBEAWRL` being used exactly once in those 3 words?
score: 0
type: Comment

http://stackoverflow.com/a/51028796
type: AcceptedAnswer
downvote count: 0
has body: I was creating the y array manually and it seems that was my mistake. I used now MultiLabelBinarizer to create it, as the following example and now it works: train_foo = [['sci-fi', 'thriller'],['comedy'],['sci-fi', 'thriller'],['comedy']] mlb = MultiLabelBinarizer() mlb_label_train = mlb.fit_transform(train_foo) X = np.loadtxt("docvecs.txt", delimiter=",") cv_scores = [] mlknn = MLkNN(k=3) scores = cross_val_score(mlknn, X, mlb_label_train, cv=5, scoring='f1_macro') cv_scores.append(scores) you can find the documentation for MultiLabelBinarizer here.
type: Answer
accepted answer of: http://stackoverflow.com/q/51011865
upvote count: 5
answers question: http://stackoverflow.com/q/51011865
score: 5

http://stackoverflow.com/a/51144853
has comment: http://stackoverflow.com/comment/89274062
has comment: http://stackoverflow.com/comment/89274222
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89274092
has body: The problem is here: accounts = ([self.obj.first_name(), self.obj.last_name()]) At first glance, this looks like a tuple of lists, and the only list in the tuple has two values. So, for first, last in accounts: ought to work, right? But it's not actually a tuple. Commas create tuples in Python; parentheses are just for disambiguation. The value (2+3) is not a tuple of the single element 5, it's just the number 5. You need 2+3, (or (2+3,)) if you want a tuple with that one element. And that's exactly what's happening in your code. Without the comma, you're just creating the list [self.obj.first_name(), self.obj.last_name()]. When you iterate over that, you don't get a 2-element list, you get a name (presumably a string), so you're effectively doing first, last = first_name, which is nonsense.1 To fix it, just add the comma: accounts = ([self.obj.first_name(), self.obj.last_name()],) Or you could just use a list. You're not really looking for immutability here (otherwise you'd have a tuple of tuples, not a tuple of lists), or for a fixed-size collection where position is meaningful, or for a micro-optimization (a tuple should shave ~6% of the &lt;100 bytes…), and those are the main reasons to use tuples in place of lists: accounts = self.obj.first_name(), self.obj.last_name() 1. Actually, it's a perfectly legal statement, because strings are iterable—they iterate their individual characters. But a first name like, say, 'Balla' has 5 characters, and you're trying to unpack those 5 elements into 2 variables. Hence the error ValueError: too many values to unpack (expected 2).
has comment: http://stackoverflow.com/comment/89274280
accepted answer of: http://stackoverflow.com/q/51144789
has comment: http://stackoverflow.com/comment/89274288
answers question: http://stackoverflow.com/q/51144789
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89274426

http://stackoverflow.com/comment/89027253
score: 2
has text: Make sure you are checking in the proper location for the file. Also make sure that the line datafile.write is executed by printing something above and below that line.
comment on: http://stackoverflow.com/q/51017384
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89164055
has text: @JayCalamari `stack`is pretty straightfoward. You have two rows/two columns. After stack, you'll have 4 rows, 1 column (i.e. values are pilled up)
comment on: http://stackoverflow.com/q/51087653
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51639404
type: Answer
accepted answer of: http://stackoverflow.com/q/51108247
score: 0
has body: So, I solved this using Case which maps to SQL cases using When condition. Here user_interested_in_tag_list is the list of tags that are user interested in, and the logic was to rank each venue on the no. of tags that matched this list. from django.db.models import ( Case, ExpressionWrapper, IntegerField, Q, Value, When ) from functools import reduce def calculate_user_interest_rank(venue_queryset, user_interested_in_tag_list): if user_interested_in_tag_list: # Add rank of 10 for each matched tag in the venue user_interest_match_query = map( lambda x: Case( When(Q(tags__contains=[x, ]), then=Value(10)), default=Value(0) ), user_interested_in_tag_list ) user_interested_tags_matches = reduce( lambda x, y: x + y, user_interest_match_query ) venue_queryset = venue_queryset.annotate( user_interest_score=ExpressionWrapper( user_interested_tags_matches, output_field=IntegerField() ) ) else: venue_queryset = venue_queryset.annotate( user_interest_score=ExpressionWrapper( Value(0), output_field=IntegerField() ) ) The user_interest_match_query will be a list of When clauses, including Value of 10 for each matched tag from user_interest_match_query, and Value of 0 otherwise. The user_interested_tags_matches is then the summation of all the resultants of When clauses which gives the actual score of each venue as annotated in user_interest_score. I hope this helps someone :) Let me know if you need any more details.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51108247

http://stackoverflow.com/q/51020783
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/89071923
tagged with: scrapy
type: Question
type: AnsweredQuestion
has title: items scrapy in sqlite3 : Error binding parameter 0 - probably unsupported type
has body: I'm trying to store the items in a sqlite3 database. I have generated all the items.. Here is my storage code in my pipelines: con = None # db connection class StoreInDBPipeline(object): # constructeur def __init__(self): self.createBD() self.dropFactureTable() self.createFactureTable() # implémenter dans la classe Pipeline et renvoyer une exception dict, Item ou DropItem def process_item(self, item, spider): self.storeInDb(item) return item # insertion def storeInDb(self, item): self.cur.execute("INSERT INTO Facture(numDocument, dateFacture, datePaiement, typeFacture, montantTTC, lienFacture ) VALUES( ?,?,?,?,?,?)", (item['numDocument'], item['dateFacture'], item['datePaiement'], item['typeFacture'], item['montantTTC'], item['lienFacture'])) log.msg("Item stored in db", level=log.DEBUG) self.con.commit() # creer la BD / cursor def createBD(self): self.con = lite.connect('BD_Facture.db') self.cur = self.con.cursor() # contrepartie du constructeur (destructeur) fermer la connexion à la BD def __del__(self): self.closeDB() # creer la table def createFactureTable(self): self.cur.execute('CREATE TABLE IF NOT EXISTS Facture(numDocument INTEGER PRIMARY KEY NOT NULL, dateFacture TEXT, datePaiement TEXT,typeFacture TEXT, montantTTC TEXT , lienFacture TEXT)') # supprime la table dans la BD def dropFactureTable(self): self.cur.execute("DROP TABLE IF EXISTS Facture") # fermer la connexion à la BD def closeDB(self): self.con.close() But during storage, I get this error : sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
answer count: 1
has answer: http://stackoverflow.com/a/51560371
score: 0
has comment: http://stackoverflow.com/comment/89071986
accepted answer: http://stackoverflow.com/a/51560371

http://stackoverflow.com/comment/89266579
has text: `"Hello {}".format(some_variable)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51141174

http://stackoverflow.com/q/51069952
has body: I'm building a GUI app using Tkinter, then I convert into one exe file using pyinstaller --onefile It's required from me that the Entry text box remembers the previous history of input. So that when the user clicks on the Entry box, is shows previous entered values and then the user can choose one of them. Please note that this should take place in the one exe file and it remembers history even after closing. I've already thought about creating a text file when starting the app, where it can store input history. And keep the text file even after closing the app, then checking the file when reopening the app. That's doable. But how to display the input history when clicking the Entry box and then choosing one of the history inputs?
score: 0
has answer: http://stackoverflow.com/a/51071813
answer count: 1
accepted answer: http://stackoverflow.com/a/51071813
tagged with: python-3.x
tagged with: tkinter
tagged with: pyinstaller
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89131471
type: Question
has title: How to remember input history in Tkinter Entry after converting with Pyinstaller?

http://stackoverflow.com/q/51084043
accepted answer: http://stackoverflow.com/a/51084556
tagged with: arrays
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
has body: b =np.ndarray(shape=(5,5), dtype=int, order='F') Out[142]: array([[ 1, 65536, 0, 0, 0], [ 0, 0, 1, 65536, 0], [16777216, 0, 0, 0, 1], [ 0, 256, 16777216, 0, 0], [ 0, 0, 0, 256, 16777216]]) and I have a list, such as : a = [1,23,4,5,20,0...] I would like to check for each index if the value in a is in the corresponding row in b , as np.isin(a[0], b[0]) and to receive Boolean vector for all the rows (if a[i] is in b[i]). The length of a is equal the length of b (amount of rows).
tagged with: python
has title: Check if value in a list is in the corresponding row in numpy array
type: AnsweredQuestion
score: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51084556

http://stackoverflow.com/comment/89204141
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51105703
score: 0
has text: I have figured out the answer sorry to have bothered anyone. I will be posting my solution as soon as it has been 24 hours.

http://stackoverflow.com/comment/89026801
has text: i export this lines: export PATH=/usr/local/cuda-9.0/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:$LD_LIBRARY_PATH export CUDA_HOME=/usr/local/cuda
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51016504
score: 0

http://stackoverflow.com/a/51132939
has body: Yes you are right, itertools is gonna be really useful here. What you want is find all subsets of desired length of the possibles list WITH duplicates, and the function that does that is itertools.product from itertools import product possibles = [20, 30, 40, 50, 60, 70, 80, 100] desired = [20, 30, 40] def fake_hamming(cur, desired, possibles): assert len(cur) == len(desired) hamm = 0 for i in range(len(cur)): assert cur[i] in possibles assert desired[i] in possibles hamm += abs(possibles.index(cur[i]) - possibles.index(desired[i])) return hamm def generate_close_by(desired, possibles, dist): all_possible_lists = product(possibles, repeat=len(desired)) return [l for l in all_possible_lists if fake_hamming(l, desired, possibles) == dist] print(generate_close_by(desired, possibles,1)) &gt;&gt;&gt; [(20, 20, 40), (20, 30, 30), (20, 30, 50), (20, 40, 40), (30, 30, 40)] Edit There you go, changed combinations for product (see @tobias_k comment below), and also here is the fake_hamming function xD Also it is true that it will be slow for big lists, but this is the most generic way to do it
has comment: http://stackoverflow.com/comment/89250892
has comment: http://stackoverflow.com/comment/89250959
has comment: http://stackoverflow.com/comment/89250934
has comment: http://stackoverflow.com/comment/89250960
has comment: http://stackoverflow.com/comment/89251037
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89250992
has comment: http://stackoverflow.com/comment/89250914
has comment: http://stackoverflow.com/comment/89250412
answers question: http://stackoverflow.com/q/51132454
has comment: http://stackoverflow.com/comment/89251174
has comment: http://stackoverflow.com/comment/89251001
downvote count: 0
has comment: http://stackoverflow.com/comment/89251933
type: Answer
has comment: http://stackoverflow.com/comment/89251335

http://stackoverflow.com/q/51104505
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: frequency
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51109647
upvote count: 2
tagged with: plot
has body: I am trying to draw a frequency line plot using matplotlib with the x-axis being the amount (loan_amount) and the y-axis the number of occurrences of that amount (loan_count) but I am not sure how to use the number of occurrences as y-values. I'd think the general code has to start similar to this but am not sure what y should be and how to complete it: con = sqlite3.connect('databaseTest.db') cur = con.cursor() cur.execute("SELECT LOAN_AMOUNT FROM funded") loan_amount = cur.fetchall() loan_amount_list = [i[0] for i in loan_amount] fig = plt.figure() ax = fig.add_subplot(1,1,1) x = loan_amount_list I want the final plot to look like this: Any help is much appreciated! Thanks! -- Edit: Implementing the counter function from collections as suggested below leads to the following plot which is not what I am aiming for:
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51105748
accepted answer: http://stackoverflow.com/a/51109647
has answer: http://stackoverflow.com/a/51105748
has title: Frequency line plot using matplotlib in python

http://stackoverflow.com/comment/89262718
type: QuestionComment
score: 1
has text: Have you tried looking for the element you're trying to scrape with either the `find` or `find_all` methods of the BeautifulSoup object you created (aka `weatherTest`)? You don't need to save the page to a file to do this. Also you're correct that `weatherTest` is simply a variable name that you can modify without altering the functionality.
comment on: http://stackoverflow.com/q/51138836
type: Comment

http://stackoverflow.com/a/51058538
has body: Use QApplication::desktop(): ... if __name__ == '__main__': app = QtGui.QApplication(sys.argv) ws = [] for i in range(QtGui.QApplication.desktop().screenCount()): topLeft = QtGui.QApplication.desktop().screenGeometry(i).topLeft() window = Fillscreen() window.move(topLeft) window.full() ws.append(window) sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/89107744
accepted answer of: http://stackoverflow.com/q/51058236
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89107500
answers question: http://stackoverflow.com/q/51058236
score: 1
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51071324
tagged with: google-cloud-datastore
tagged with: wagtail
has title: Does wagtail early versions support GCP Datastore?
score: 0
has answer: http://stackoverflow.com/a/51072158
answer count: 1
tagged with: google-app-engine
has body: Now we have our project up and running on google-app-engine using cloud SQL as the back-end database system but the client somehow wants to convert to Datastore so what are the opportunities to use Datastore with Wagtail 1.13 or greater without having any troubles. Thanks for your help
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51072158
type: Question

http://stackoverflow.com/comment/89312575
type: Comment
type: QuestionComment
has text: … and you also probably want a `datetime.time` object, not a `datetime.datetime` (you can call the `temp_time.time()` method to get one).
score: 1
comment on: http://stackoverflow.com/q/51164619

http://stackoverflow.com/q/51120179
tagged with: macos
has comment: http://stackoverflow.com/comment/89225885
favorite count: 0
tagged with: python-3.x
has title: Link pip installed libraries to python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89233448
has body: I have 3 python versions installed: default mac python 2.7, brew python2.7 and brew python3, but my pip libraries are not being linked to anyone. user$ which python /usr/bin/python user$ which python2.7 /usr/bin/python2.7 user$ which python3 /usr/local/bin/python3 user$ which pip /usr/local/bin/pip user$ which pip2 /usr/local/bin/pip2 How can I link the pip installed libraries to python and python2.7 commands?
tagged with: pip
tagged with: python
answer count: 0
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89226106
linked to: http://stackoverflow.com/q/34803040
has comment: http://stackoverflow.com/comment/89225924
tagged with: python-2.7
downvote count: 0
score: 1

http://stackoverflow.com/comment/89162335
comment on: http://stackoverflow.com/q/51085622
score: 1
has text: For problems this complex, it is perfectly fine to write your own solution. As the answer below illustrates, you can break the problem into smaller pieces and write a function for each piece. Once you have those working functions, you can then refactor them into more "elegant" structures, like replacing loops with list comprehensions.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51092258
has comment: http://stackoverflow.com/comment/89173147
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1756096
answer count: 2
has comment: http://stackoverflow.com/comment/89173421
upvote count: 1
has comment: http://stackoverflow.com/comment/89173264
has title: Generate words of varying length give n number of characters
has comment: http://stackoverflow.com/comment/89225409
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89173081
has body: I need to generate all possible words of Ki lengths given n characters for example: given LNDJOBEAWRL do bear I cant come up with the word of len 5 but this is the idea n = 11 k1 = 2 k2 = 4 k3 = 5 So basically all words of length 2 4 and 5 but without reusing characters. What would be the best way to do it? My dictionary structure looks likes this: { 3: [{u'eit': u' "eit":0'}], 5: [{u'doosw': u' "woods": 4601, '}, {u'acenr': u' "caner": 0, '}, {u'acens': u' "canes": 0, '}, {u'acden': u' "caned": 0, '}, {u'aceln': u' "canel": 0,'}], 6: [{u'abeill': u' "alible": 0, '}, {u'cdeeit': u' "deciet":0,'}, {u'demoor': u' "mooder": 0, '}], 7: [{u'deiprss': u' "spiders": 0, '}, {u'deiprsy': u' "spidery": 0, '}, {u'cersttu': u' "scutter": 0, '}], 8: [{u'chiiilst': u' "chilitis": 0, '}, {u'agilnrtw': u' "trawling": 0, '}, {u'abdeemns': u' "beadsmen": 0, '}], 9: [{u'abeiilnns': u' "biennials": 0, '}, {u'bclooortu': u' "oblocutor": 0, '}, {u'aabfiinst': u' "fabianist": 0, '}, {u'acdeiituz': u' "diazeutic": 0, '}, {u'aabfiimns': u' "fabianism": 0, '}, {u'ehnoooppt': u' "optophone": 0, '}], 10: [{u'aiilnoprtt': u' "tripolitan": 0, '}, {u'eeilprrsty': u' "sperrylite": 0, '}, {u'gghhiilttt': u' "lighttight": 0, '}, {u'aeegilrruz': u' "regularize": 0, '}, {u'ellnprtuuy': u' "purulently": 0, '}], 11: [{u'cdgilnoostu': u' "outscolding": 0, '}], 12: [{u'ceeeilnostuy': u' "leucosyenite": 0, '}, {u'aacciloprsst': u' "sarcoplastic": 0, '}], 13: [{u'acdeimmoprrsu': u' "cardiospermum": 0, '}, {u'celnnooostuvy': u' "noncovetously": 0, '}], 14: [{u'adeejmnnoprrtu': u' "preadjournment": 0, '}] } And my modified code looks like this: wlen = self.table[pos] if pos == 0: # See if the letters remaining in the bag are a valid word key = ''.join(sorted(bag.elements())) for d in wlen: if key in d.keys(): yield solution + [key] else: pos -= 1 for dic in wlen: print(len(dic)) for key in dic.keys():
has comment: http://stackoverflow.com/comment/89172939
has answer: http://stackoverflow.com/a/51103183
has comment: http://stackoverflow.com/comment/89173200
has comment: http://stackoverflow.com/comment/89225461
downvote count: 4
has answer: http://stackoverflow.com/a/51093324
tagged with: string
tagged with: data-structures
score: -3
possible better answer: http://stackoverflow.com/a/51093324
accepted answer: http://stackoverflow.com/a/51103183
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89173028
tagged with: words
tagged with: python
has comment: http://stackoverflow.com/comment/89173071

http://stackoverflow.com/comment/89407178
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51160183
type: Comment
has text: Python version needs to be specified in the question. And see edit with a Python 3.6 transcript. If you're getting a contrary result, you need to share instructions that others can follow to see it as well.

http://stackoverflow.com/comment/89206623
has text: I think he has only copied the executable file (may be elf or cx_freeze). I have tried it with some other random name, It is still executing. My Bad. Anyways,Thanks a lot guys for the help. Appreciated.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51109420

http://stackoverflow.com/comment/89084327
comment on: http://stackoverflow.com/a/51046511
has text: what happen if the task takes longer than the max_runtime in the first loop?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89065683
type: Comment
has text: I have fixed my problem. I go on resolving. I delete the line "for student in record.student_ids:" in my code. Thank you
comment on: http://stackoverflow.com/a/51027198
type: AnswerComment
score: 0

http://stackoverflow.com/q/51115476
favorite count: 0
score: 4
accepted answer: http://stackoverflow.com/a/51116966
type: Question
tagged with: pytorch
has title: Applying convolution operation to image - PyTorch
answer count: 2
upvote count: 4
has body: To render an image if shape 27x35 I use : random_image = [] for x in range(1 , 946): random_image.append(random.randint(0 , 255)) random_image_arr = np.array(random_image) matplotlib.pyplot.imshow(random_image_arr.reshape(27 , 35)) This generates : I then try to apply a convolution to the image using the torch.nn.Conv2d : conv2 = torch.nn.Conv2d(3, 18, kernel_size=3, stride=1, padding=1) image_d = np.asarray(random_image_arr.reshape(27 , 35)) conv2(torch.from_numpy(image_d)) But this displays error : ~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input) 299 def forward(self, input): 300 return F.conv2d(input, self.weight, self.bias, self.stride, --&gt; 301 self.padding, self.dilation, self.groups) 302 303 RuntimeError: input has less dimensions than expected The shape of the input image_d is (27, 35) Should I change the parameters of Conv2d in order to apply the convolution to the image ? Update. From @McLawrence answer I have : random_image = [] for x in range(1 , 946): random_image.append(random.randint(0 , 255)) random_image_arr = np.array(random_image) matplotlib.pyplot.imshow(random_image_arr.reshape(27 , 35)) This renders image : Applying the convolution operation : conv2 = torch.nn.Conv2d(1, 18, kernel_size=3, stride=1, padding=1) image_d = torch.FloatTensor(np.asarray(random_image_arr.reshape(1, 1, 27 , 35))).numpy() fc = conv2(torch.from_numpy(image_d)) matplotlib.pyplot.imshow(fc[0][0].data.numpy()) renders image :
has answer: http://stackoverflow.com/a/51116966
downvote count: 0
has answer: http://stackoverflow.com/a/78970238
possible better answer: http://stackoverflow.com/a/78970238
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89291713
tagged with: python

http://stackoverflow.com/comment/112351312
has text: I did it and it resolved in vs code but it is still showing up in Jupyter notebook
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/53998039

http://stackoverflow.com/comment/89171290
comment on: http://stackoverflow.com/a/51091411
score: 0
type: AnswerComment
has text: BTW, you can (& should) use the `print` function in Python 2.6+, you just need `from __future__ import print_function` at the top of your script, before other `import` statements. That makes it easier to migrate to Python 3. However, the Python 2.6 version doesn't support all the latest `print` function features.
type: Comment

http://stackoverflow.com/comment/89324577
has text: @john And you lost attached img
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51164645

http://stackoverflow.com/comment/89112453
has text: Please provide the sample of the data file you used. Couldn't reproduce this issue.
comment on: http://stackoverflow.com/q/51040542
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51164291
favorite count: 0
linked to: http://stackoverflow.com/q/4622057
linked to: http://stackoverflow.com/q/49061906
has comment: http://stackoverflow.com/comment/89312038
has answer: http://stackoverflow.com/a/51164477
has comment: http://stackoverflow.com/comment/89312064
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Matplotlib "patch" like function for 3D triangular meshes
has comment: http://stackoverflow.com/comment/89312218
type: Question
accepted answer: http://stackoverflow.com/a/51164477
tagged with: matplotlib
answer count: 1
has body: I would like to plot a 3D finite element mesh using MATPLOTLIB. I have some problems using MAYAVI, so this kind of solution does not apply. I need something like Matlab "patch" function, as shown below: x = [0.0, 1.0, 0.0]; y = [0.0, 0.0, 1.0]; z = [0.0, 1.0, 1.0]; v = 100.0; view(3) patch(x, y, z, v) hold on; x = [1.0, 1.0, 0.0]; y = [0.0, 1.0, 1.0]; z = [1.0, 0.0, 1.0]; v = 50.0; patch(x, y, z, v) in this code, "v" is the scalar field evaluated at the center of each triangle. It produces the image below.
downvote count: 0

http://stackoverflow.com/a/52188445
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51156581
downvote count: 0
has comment: http://stackoverflow.com/comment/91389258
answers question: http://stackoverflow.com/q/51156581
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/91389918
upvote count: 5
has body: I believe there was just a typo (though I couldn't exactly find where) in your definition sgt. Here is an implementation that works. %matplotlib inline import matplotlib.pyplot as plt from scipy.special import beta import numpy as np from math import sqrt from typing import Union from scipy import integrate # Generalised Student T probability Distribution def generalized_student_t(x:Union[float, np.ndarray], mu:float, sigma:float, lam:float, p:float, q:float) \ -&gt; Union[float, np.ndarray]: v = q**(-1/p) * ((3*lam**2 + 1)*(beta(3/p, q - 2/p)/beta(1/p,q)) - 4*lam**2*(beta(2/p, q - 1/p)/beta(1/p,q))**2)**(-1/2) m = 2*v*sigma*lam*q**(1/p)*beta(2/p,q - 1/p)/beta(1/p,q) fx = p / (2*v*sigma*q**(1/p)*beta(1/p,q)*(abs(x-mu+m)**p/(q*(v*sigma)**p)*(lam*np.sign(x-mu+m)+1)**p + 1)**(1/p + q)) return fx def plot_cdf_pdf(x_axis:np.ndarray, pmf:np.ndarray) -&gt; None: """ Plot the PDF and CDF of the array returned from the function. """ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) ax1.plot(x_axis, pmf) ax1.set_title('PDF') ax2.plot(x_axis, integrate.cumtrapz(x=x_axis, y=pmf, initial = 0)) ax2.set_title('CDF') pass dx = 0.0001 x_axis = np.arange(-10, 10, dx) # Create the Two distribution1 = generalized_student_t(x=x_axis, mu=0, sigma=1, lam=0, p=2, q=100) distribution2 = generalized_student_t(x=x_axis, mu=0, sigma=2, lam=0, p=1.05, q=2.1) plot_cdf_pdf(x_axis=x_axis, pmf=distribution1) plot_cdf_pdf(x_axis=x_axis, pmf=distribution2) We can also check that the integral of the PDFs are 1 integrate.simps(x=x_axis, y = distribution1) integrate.simps(x=x_axis, y = distribution2) We can see the results of the integral are 0.99999999999999978 and 0.99752026308335162. The reason they are not exactly 1 is due the CDF being defined as integral from -infinity to infinity of the PDF.
has comment: http://stackoverflow.com/comment/137466530

http://stackoverflow.com/q/51029274
answer count: 4
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51029308
type: UnansweredQuestion
tagged with: count
tagged with: python
has title: how to count the number of user inputs
downvote count: 1
has answer: http://stackoverflow.com/a/62774163
has answer: http://stackoverflow.com/a/51029317
score: 1
type: Question
has answer: http://stackoverflow.com/a/51038616
has body: Im having loads of trouble trying to count the number of guesses in this after you find the number. def play_game(): print("Enter the upper limit for the range of numbers: ") limit = int(input()) number = random.randint(1, limit) print("I'm thinking of a number from 1 to " + str(limit) + "\n") while True: guess = int(input("Your guess: ")) if guess &lt; number: print("Too low.") elif guess &gt; number: print("Too high.") elif guess == number: print("You guessed it in " + str(count) + " tries.\n") return

http://stackoverflow.com/comment/89055026
comment on: http://stackoverflow.com/a/51031306
has text: Works great. Thank you!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51013597
has body: Because first [i + [num] for i in result] is resolved, and then once that is computed, the result += part happens, which is different from yours where you append 1 by 1. The other solution appends all at once so there is no issue
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51013561
answers question: http://stackoverflow.com/q/51013561
score: 3

http://stackoverflow.com/q/51032311
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89057079
upvote count: 1
type: Question
score: 1
has title: PyQt label positioning on widget
tagged with: pyqt
answer count: 1
tagged with: pyqt4
downvote count: 0
has body: I create an simple arduino project. The main purpose of my project is to display text on a LCD screen based on PIN status (1 or 0). To reach this, i create a simple form and added a label on it. On startup it shows a default text, but when I press a menu button (simulate PIN =1) the text is changed to "WARNING_TEXT" Here is my Python code (this is Entry point for my app): import sys from forms import MainForm2 import os from PyQt4.QtGui import * def main(): app, window = MainForm2.init() p = app.desktop().availableGeometry().center() window.move(p.x()-window.width()*0.5,p.y()-window.height()*0.5) window.setWindowTitle('Monitor') #&lt;=Nazvanie app window.showMaximized() sys.exit(app.exec_()) if __name__ =="__main__": main() The code of MainForm2(all application logic is here): # -*- coding: utf-8 -*- from PyQt4 import QtGui,QtCore from PyQt4.QtGui import QSizePolicy,QColor import sys import time try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class QMainWindow(QtGui.QMainWindow): defaultStyle ='color:green;font-size:240px' warningStyle ='color:red;text-align: justify;font-size:{0}px' def __init__(self,parent=None): super(QtGui.QMainWindow,self).__init__(parent) self.cnfVacant = "Default text" self.cnfBusy = "Warning text" self.setupUi() def setupUi(self): self.thread=QMyThread() #timer self.timer = QtCore.QTimer() self.timer.setInterval(1000) self.timer.timeout.connect(self.displayTime) self.main = QtGui.QWidget(self) self.main.setAutoFillBackground(True) p = self.main.palette() p.setColor(self.main.backgroundRole(),QColor.fromRgb(0,0,0,255)) self.main.setPalette(p) self.setCentralWidget(self.main) self.menubar = QtGui.QMenuBar(self) self.menu…
has answer: http://stackoverflow.com/a/51032867
favorite count: 0
accepted answer: http://stackoverflow.com/a/51032867

http://stackoverflow.com/q/51157742
has comment: http://stackoverflow.com/comment/89300000
has comment: http://stackoverflow.com/comment/89299032
tagged with: python-2.7
score: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89299350
has title: How to print 3rd from bottom line in file?
has answer: http://stackoverflow.com/a/51158397
has comment: http://stackoverflow.com/comment/89299399
accepted answer: http://stackoverflow.com/a/51158397
type: Question
has body: I want to read and print the 3rd from last line in date.log. This is specified in the line_from_bottom_line variable. The log can have any number of lines at any time. Here is an example of what the log looks like: 192.168.80.231 May 8 2018 18:45:00 192.168.80.231 July 30 2018 09:46:48 192.168.80.231 July 2 2018 14:37:14 If there are only 3 lines in the log, the else line will be printed: line_number[x1] = [(index,log_time)] The output will be: (1, '18:45:00') Which is not what I want. If there are 4 or more lines, the line printed will be in the format of: 2018:8:18:45:00 This is what I want. I think my code below is moving to the bottom line and subtracting 3. So if 4 lines don't exist, it doesn't know what to print. How can I change it so that the 3rd from bottom line is printed even if there are not 4 or more lines in the log? old_time = (line_number[x1][-(line_from_bottom_line)].__str__()) from datetime import datetime, date, time # this would be the third from last line line_from_bottom_line = 3 date_order = 2 time_order = 4 year_order = 3 present = datetime.now() def main(): logfile = open('krinkov.log', 'r+') line_number = dict() for index,line in enumerate(logfile,1): # scan lines if line in ['\n', '\r\n']: # Error Checking: if not enough lines in var .log print("Not enough lines.") return if line: x1 = line.split()[0] # if line, get IP address log_day = line.split()[date_order] log_time = line.split()[time_order] # This will already be in the format of hh:mm:ss log_year = line.split()[year_order] if x1 in line_number : # if ip address on line line_number[x1].append((log_year + ":" + log_day + ":" + log_time)) else: line_number[x1] = [(index,log_time)] if x1 in line_number and len(line_number.get(x1,None)) &gt; 1: # Below is where I am having issues. # If there are not 4 or more lines in the log, an error occurs. old_time = (line_number[x1][-line_from_bottom_line]) print(old_time) # ** get last line number. Print that line number. then subtract 2 from it # …
answer count: 1

http://stackoverflow.com/comment/99897670
has text: This is now a year old question, but the scipy documentation page on this is still unchanged.
comment on: http://stackoverflow.com/q/51042870
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51111869
upvote count: 1
answers question: http://stackoverflow.com/q/51111861
has comment: http://stackoverflow.com/comment/89210593
has body: Functions return None by default; by calling print(function), you are printing the returned value, in your case, it is None. Because the printing happens in your function, you could call steps without printing: Edit: if the print is mandatory... Maybe you could return the empty string then: def steps(i): t = 0 for i in range(1, i + 1): print(("\t" * t) + (str(i) * 3) + "\n") t += 1 return '' print(steps(6)) output: 111 222 333 444 555 666 ''
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/51125786
score: 0
answers question: http://stackoverflow.com/q/51125769
has body: Apparently this notation below works: proccessing_data['RSI'] = proccessing_data.groupby('Symbol')[('{}ClosePrice'.format(a_list[0]))].transform(lambda x: talib.RSI(x, timeperiod=14))
type: Answer

http://stackoverflow.com/a/51087670
type: Answer
score: 0
has body: The global state of the storage tanks was the problem. I had tests at the beginning that changed the level of one of the tanks but never returned it to its normal state. By adding some function calls prior to starting the rest of the tests and ensuring that the tank levels were "full", it fixed all the problems: fff.change_tank_level(ffc.tank1, 36) fff.change_tank_level(ffc.tank2, 36) where 36 is a full tank. So, when I get to the TestGate3TankLevels class, I changing the tank levels works correctly. The teardown method then returns the tank levels back to normal.
answers question: http://stackoverflow.com/q/51050076

http://stackoverflow.com/comment/89165239
type: AnswerComment
comment on: http://stackoverflow.com/a/51088188
score: 0
type: Comment
has text: Oh! So I have to use **count_vectorizer** with a fit method or only transform method?

http://stackoverflow.com/q/51057369
has comment: http://stackoverflow.com/comment/89417372
has comment: http://stackoverflow.com/comment/89151274
has comment: http://stackoverflow.com/comment/89114919
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89107864
has comment: http://stackoverflow.com/comment/89105240
has comment: http://stackoverflow.com/comment/89105271
has title: Normalizing FFT spectrum magnitude to 0dB
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/89111403
tagged with: spectrum
has comment: http://stackoverflow.com/comment/89148744
tagged with: frequency
has comment: http://stackoverflow.com/comment/89105226
tagged with: python
has answer: http://stackoverflow.com/a/51240462
has comment: http://stackoverflow.com/comment/89108340
has body: I'm using FFT to extract the amplitude of each frequency components from an audio file. Actually, there is already a function called Plot Spectrum in Audacity that can help to solve the problem. Taking this example audio file which is composed of 3kHz sine and 6kHz sine, the spectrum result is like the following picture. You can see peaks are at 3KHz and 6kHz, no extra frequency. Now I need to implement the same function and plot the similar result in Python. I'm close to the Audacity result with the help of rfft but I still have problems to solve after getting this result. What's physical meaning of the amplitude in the second picture? How to normalize the amplitude to 0dB like the one in Audacity? Why do the frequency over 6kHz have such high amplitude (≥90)? Can I scale those frequency to relative low level? Related code: import numpy as np from pylab import plot, show from scipy.io import wavfile sample_rate, x = wavfile.read('sine3k6k.wav') fs = 44100.0 rfft = np.abs(np.fft.rfft(x)) p = 20*np.log10(rfft) f = np.linspace(0, fs/2, len(p)) plot(f, p) show() Update I multiplied Hanning window with the whole length signal (is that correct?) and get this. Most of the amplitude of skirts are below 40. And scale the y-axis to decibel as @Mateen Ulhaq said. The result is more close to the Audacity one. Can I treat the amplitude below -90dB so low that it can be ignored? Updated code: fs, x = wavfile.read('input/sine3k6k.wav') x = x * np.hanning(len(x)) rfft = np.abs(np.fft.rfft(x)) rfft_max = max(rfft) p = 20*np.log10(rfft/rfft_max) f = np.linspace(0, fs/2, len(p)) About the bounty With the code in the update above, I can measure the frequency components in decibel. The highest possible value will be 0dB. But the method only works for a specific audio file because it uses rfft_max of this audio. I want to measure the frequency components of multiple audio files in one standard rule just like Audacity does. I also started a discussion in Audacity forum, but I was still n…
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89146179
score: 11
tagged with: audacity
has comment: http://stackoverflow.com/comment/89111400
type: Question
accepted answer: http://stackoverflow.com/a/51240462
has comment: http://stackoverflow.com/comment/89105447
has comment: http://stackoverflow.com/comment/89114797
has comment: http://stackoverflow.com/comment/89146490

http://stackoverflow.com/a/51168681
accepted answer of: http://stackoverflow.com/q/51165549
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
score: 2
has body: It appears that the Python extension is implementing the VSCode API directly for features such as rename, rather than using the LSP abstraction layer. See for instance its renameProvider.ts, which implements vscode.RenameProvider: https://github.com/Microsoft/vscode-python/blob/c976b6c98e34e041b7ee826ec22f9820ba90f8ac/src/client/providers/renameProvider.ts I don't think how it's implemented really matters to you as a caller though - It seems like you're in luck, the ability to programatically trigger a rename was added just recently and will be released soon as part of VSCode 1.25.0 / the June release: API to programmatically begin rename (#50856) It's also part of the release notes for the upcoming version, which give the following usage example: vscode.commands.executeCommand( 'editor.action.rename', [vscode.Uri.file('/my/file.abc'), new vscode.Position(14, 7)] )
answers question: http://stackoverflow.com/q/51165549

http://stackoverflow.com/q/51055694
score: 1
has answer: http://stackoverflow.com/a/51061107
tagged with: scrapy
type: Question
has body: I stuck with one problem. I want to extract text from following HTML using XPath in scrapy. &lt;div class="block fix-text job-description"&gt; &lt;p&gt;We’re looking for an experienced &lt;strong&gt;Events Manager&lt;/strong&gt; to develop and deliver our events and exhibitions programme, available to start as soon as possible. You’ll be leading a team of two to create and implement an events strategy that supports our corporate objectives. You’ll be working closely with our campaigns, marketing and projects teams to make sure we connect with our audiences and achieve event objectives.&lt;/p&gt; &lt;p&gt;In this role, you’ll be working within a dynamic team in a fast-paced environment, with the potential opportunity to be part of the recruitment process to build your own team. Your experience as an events manager will have a strong marketing or digital marketing focus, ideally within a regulatory or third sector context.&lt;/p&gt; &lt;p&gt;You’ll be managing high profile events across our diverse organisation, from workshops and online webinars to our national flagship conference. It’s an exciting role with the opportunity to help shape our current digital transformation and strengthen our brand, so we’re looking for creativity and innovation. You’ll also be working with senior colleagues and stakeholders, for whom you’ll prepare detailed briefings. In addition, you:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Can demonstrate your extensive experience of creating and managing high profile events and conferences&lt;/li&gt; &lt;li&gt;Have experience in delivering complex events programmes integrated into campaigns and marketing communications&lt;/li&gt; &lt;li&gt;Have experience of audience research and insight&lt;/li&gt; &lt;li&gt;Have excellent budget management and negotiation skills&lt;/li&gt; &lt;li&gt;Are an outstanding communicator, both verbal and written&lt;/li&gt; &lt;li&gt;Have strong people management skills with the ability to motivate and develop a team remotely&lt;/…
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51055839
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
has title: How to extract text data from multiple tags using response.XPath in Scrapy?
downvote count: 0

http://stackoverflow.com/comment/89234600
type: Comment
type: QuestionComment
has text: That's because you go into package to run the module. From the root dir, run `python slots_tracker/server.py` or even better, run directly `python -m slots_tracker.server`.
score: 1
comment on: http://stackoverflow.com/q/51098026

http://stackoverflow.com/q/51126493
type: UnansweredQuestion
score: 0
type: Question
tagged with: plotly-dash
has body: I have my app (final_test.py) and my demo dataset (final_test.csv) and all I want is to able to plot scatter or barchart from my dataset (number of cases per day). Here goes my code on final_test.py: #### Importing DASH COMPONENTS ############################################################################## #coding: utf-8 import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html from plotly import graph_objs as go # or #import plotly.graph_objs as go import ipywidgets as widgets from scipy import special import datetime #To allow displaying today's Date in upper right corner import json import pandas as pd import os from flask import Flask import numpy as np #### Preparing FLASK App #################################################################################### server = Flask('my app') #### SCATTER PLOT ########################################################################################## dfb=pd.read_csv('final_test.csv', encoding="latin-1", infer_datetime_format=True, parse_dates=['date'], sep=",") trace1=go.Bar( #Trace Enrollment x=pd.to_datetime(dfb['date']), # IT WORKS ALMOST DONE! #x=dfb['date'], # IT WORKS ALMOST DONE #x=pd.to_datetime(dfb.date, format='%m-%d-%y'), #IT WORKS NO EFFECT y=dfb.set_index('date').resample('D')["enrolled"].sum(), #IT WORKS ALMOST DONE! #mode='lines + markers', name='Enrollment', ) trace2=go.Bar( #Trace empty enrollment x=pd.to_datetime(dfb['date']), y=dfb[dfb['enrolled'].isnull()].sum(), # IT WORKS ALMOST DONE! name='Not Answered', #xaxis='Performance' ) trace3=go.Bar( #Trace Rejection to Enrollment x=pd.to_datetime(dfb['date']), y=dfb[dfb['enrolled'] == 2].sum(), name='Rejected Participation', #xaxis='Performance' ) ############################################################################################################# app = dash.Dash() # Describe the layout, or the UI, of the app app.layout = html.Div([ html.Div([ # page 1 html.A(['Print PDF'], cla…
has answer: http://stackoverflow.com/a/51126501
answer count: 1
tagged with: python
has title: Python/ Dash: How to do Scatter Plot on Dash grouping Cases by Date?

http://stackoverflow.com/q/51012621
has comment: http://stackoverflow.com/comment/89018023
answer count: 2
has body: I need to run netstat -nb via python code but everything I tried gives me the same output, "The requested operation requires elevation." How do I evaluate netstat -nb in python?
has answer: http://stackoverflow.com/a/51012822
score: 0
tagged with: python
tagged with: python-3.x
tagged with: subprocess
has answer: http://stackoverflow.com/a/51021593
type: UnansweredQuestion
has title: How to run netstat -nb in python
type: Question
linked to: http://stackoverflow.com/q/19672352

http://stackoverflow.com/a/51072452
accepted answer of: http://stackoverflow.com/q/51070559
has comment: http://stackoverflow.com/comment/89202070
has comment: http://stackoverflow.com/comment/89200427
has comment: http://stackoverflow.com/comment/89201287
answers question: http://stackoverflow.com/q/51070559
has comment: http://stackoverflow.com/comment/89200918
type: Answer
has comment: http://stackoverflow.com/comment/89201067
has comment: http://stackoverflow.com/comment/89200091
has comment: http://stackoverflow.com/comment/89201711
upvote count: 1
has body: Here in your case you are just extending Django User model, so you should not override AUTH_USER_MODEL. Delete this line of code from settings.py file: AUTH_USER_MODEL = "pedidos.Usuario" , and in your code if you want to use your User model, this is the one you should use: from django.contrib.auth.models import User (as we said you are just extending Django User model) or you can use the convenient function get_user_model() get_user_model(): Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise. If you want to get the attribute es_tecnico of a User you can use: &gt;&gt;&gt; from django.contrib.auth.models import User &gt;&gt;&gt; u = User.objects.get(username='Juan') &gt;&gt;&gt; juan_es_tecnico = u.usuario.es_tecnico or using get_user_model(): &gt;&gt;&gt; from django.contrib.auth import get_user_model &gt;&gt;&gt; my_user = get_user_model() &gt;&gt;&gt; u = my_user.objects.get(username='Juan') &gt;&gt;&gt; juan_es_tecnico = u.usuario.es_tecnico Edit: class Registrar(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = UsuarioSerializer def create(self, request, *args, **kwargs): # Creando un nuevo usuario username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') user = User.objects.create_user(username, email, password) user.save() token = Token.objects.create(user=user) return Response({'detail': 'El usuario fue creado con el token: ' + token.key}) In Registrar class use User model instead of Usuario. I hope this will help.
has comment: http://stackoverflow.com/comment/89201151
has comment: http://stackoverflow.com/comment/89201598
has comment: http://stackoverflow.com/comment/89200811
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89202034
score: 1

http://stackoverflow.com/comment/89017248
score: 0
type: Comment
type: QuestionComment
has text: The program works by itself, and in cmd when i directly type the sbdart >> output.csv, it works perfectly would you like a copy of the program? It has no configuration options or even an interface, hence the confusion. Please help me out, im at my wits end
comment on: http://stackoverflow.com/q/51011742

http://stackoverflow.com/q/51118428
tagged with: attributeerror
has body: I am trying out the code from the book: Beginning Robotics with Raspberry Pi and Arduino: Using Python and OpenCV. In the first chapter, the author has us type in a code to simulate controlling a robot. In python, a file is created called robot_sample_class.py and the code is: class Robot(): """ A simple robot class This multi-line comment is a good place to provide a description of what the class is. """ # define the initiating function. # speed = value between 0 and 255 # duration = value in milliseconds def __init__(self, name, desc, color, owner, speed = 125, duration = 100): # initiates our robot self.name = name self.desc = desc self.color = color self.owner = owner self.speed = speed self.duration = duration def drive_forward(self): # simulates driving forward print(self.name.title() + " is driving" + " forward " + str(self.duration) + " milliseconds") def drive_backward(self): # simulates driving backward print(self.name.title() + " is driving" + " backward " + str(self.duration) + " milliseconds") def turn_left(self): # simulates turning left print(self.name.title() + " is turning " + " right " + str(self.duration) + " milliseconds") def turn_right(self): # simulates turning right print(self.name.title() + " is turning " + " left " + str(self.duration) + " milliseconds") def set_speed(self, speed): # sets the speed of the motors self.speed = speed print("the motor speed is now " + str(self.speed)) def set_duration(self, duration): # sets duration of travel self. duration = duration print("the duration is now " + str(self.duration))' Then, I create a file called robot_sample.py and here is the code: import robot_sample_class def my_robot(): Robot("Nomad", "Autonomous rover","black", "Cecil") print("My robot is a " + my_robot.desc + " called " + my_robot.name) my_robot.drive_forward() my_robot.drive_backward() my_robot.turn_left() my_robot.turn_right() my_robot.set_speed(255) my_robot.set_duration(1000) When I run the robot_sample.py, I get an error message: …
downvote count: 1
type: Question
tagged with: object
tagged with: function
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/89222930
accepted answer: http://stackoverflow.com/a/51118501
answer count: 1
favorite count: 0
has title: Attribute Error: function has no attribute 'desc'
has comment: http://stackoverflow.com/comment/89222984
tagged with: python
has answer: http://stackoverflow.com/a/51118501
type: AnsweredQuestion

http://stackoverflow.com/a/51146271
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51146094
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51146094
has body: One idiom that may feel slightly less awkward is: np.nanmin(xyzlist[-w:(-w+14) or None], axis = 0)
has comment: http://stackoverflow.com/comment/89277793
type: AcceptedAnswer

http://stackoverflow.com/a/51118822
downvote count: 0
answers question: http://stackoverflow.com/q/51118779
type: Answer
has body: Start by defining your lists of keys, arguments, and boolean variables: keys = ["do_a", "do_b", ...] args = ["args for a", "args for b", ...] mask = [a, b, ...] Now, construct obj using the mask list to determine what keys are inserted: obj = {k : a for k, a, m in zip(keys, args, mask) if m} Alternatively, obj = {} for k, a, m in zip(keys, args, mask): if m: obj[k] = a
score: 5
upvote count: 5

http://stackoverflow.com/a/51126407
score: 1
answers question: http://stackoverflow.com/q/51126376
downvote count: 0
type: Answer
has body: Subscripting a string will return a string not an int, like you're comparing them to. You should use string literals in your conditions: s=input('Enter the IP address :') if s[0]=='1' and s[1]=='0' and s[2]=='.': print('It is a special IP address') elif s[0]=='1' and s[1]=='9' and s[2]=='2' and s[3]=='.' and s[4]=='1' and s[5]=='6' and s[6]=='8': print('It is a special IP address') else: print('It is an ordinary IP address')
upvote count: 1

http://stackoverflow.com/q/51083128
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89154955
score: 1
has body: I'm trying to use pycodestyle within a python program: from pycodestyle import StyleGuide, StandardReport CONFIG_FILE = 'setup.cfg' def check_pycodestyle(): style_guide = StyleGuide(config_file=CONFIG_FILE, quiet=True) # style_guide = StyleGuide(config_file=CONFIG_FILE, reporter=StandardReport, quiet=True) report = style_guide.check_files(paths='./') Unfortunately I haven't found a way to get the results as a simple return value. When using the quiet=True flag, nothing is printed automatically but the returned report is a BaseReport and doesn't seem to contain the actual results but just a count on how many total_errors. When omitting the quiet flag, then the results are automatically printed. Is there a function to retrieve the results and not print them? EDIT: When using report.get_file_results() I receive the following results: With quiet=True: 0 Without quiet: &lt;prints the results&gt; 0
upvote count: 1
has title: pycodestyle retrieve results without printing them
type: Question
has answer: http://stackoverflow.com/a/58223842
has comment: http://stackoverflow.com/comment/89154665
tagged with: pycodestyle
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51050202
has body: I've written a script in python to get the item and it's value in a dictionary. When I run my script, it does fetch that in the wrong way, I meant not in that way I wish to have. The result I'm having now is like: {'4194813.75690': 'foo', '4194813.75691': 'foo'} But, I wish to have: {'4194813.75690': 'foo', '4194813.75691': 'bar'} In the name attribute this portion 4194813 is always stable but this .75691 portion changes dynamically so I could not use any suitable flag in .startswith() other than what i've tried below. This is the script: import requests from bs4 import BeautifulSoup url = "https://www.electricityregistry.co.nz/bin_public/jadehttp.dll?MariaWebR" res = requests.get(url) soup = BeautifulSoup(res.text,"lxml") formdata = {} for items in soup.select("[name='JadeForm'] input"): if items.get("name").startswith('4194813'): item = items.get("name") val = "foo" #how to change it to "bar" in the second iteration formdata[item] = val print(formdata)
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/89091731
score: 0
has comment: http://stackoverflow.com/comment/89091670
has comment: http://stackoverflow.com/comment/89091429
answer count: 1
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89091793
has comment: http://stackoverflow.com/comment/89091705
has answer: http://stackoverflow.com/a/51050412
has title: Unable to get values in accordance with items in a dictionary
tagged with: python
accepted answer: http://stackoverflow.com/a/51050412
type: AnsweredQuestion

http://stackoverflow.com/comment/89174490
has text: the latest version
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51073519
type: Comment

http://stackoverflow.com/comment/89268646
has text: @syntonym I deployed it
type: QuestionComment
comment on: http://stackoverflow.com/q/51116689
score: 0
type: Comment

http://stackoverflow.com/comment/89298038
type: AnswerComment
has text: That is exactly what I was looking for! @jezrael
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51157150

http://stackoverflow.com/comment/89085560
comment on: http://stackoverflow.com/q/51046870
type: Comment
has text: I would have default manager at objects. like objects = models.Manager() # The default manager. and then special_products = ProductManager()
score: 0
type: QuestionComment

http://stackoverflow.com/comment/115288087
score: 2
type: Comment
type: AnswerComment
has text: In case you use upload_object, you could also use: `s3_client.upload_fileobj(obj, bucket, filename, ExtraArgs={'ACL': 'bucket-owner-full-control'})`
comment on: http://stackoverflow.com/a/51154862

http://stackoverflow.com/a/51069487
upvote count: 3
has body: purge doesn't actually receive a list of messages to delete (though the documentation is phrased as if it does). Instead, it takes a number of keyword arguments that it uses to determine whether or not messages should be deleted. Try @bot.command() async def clear(ctx, amount: int): await ctx.channel.purge(limit=amount)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51069337
accepted answer of: http://stackoverflow.com/q/51069337
type: Answer
score: 3

http://stackoverflow.com/q/51069406
type: Question
has answer: http://stackoverflow.com/a/65688517
downvote count: 0
linked to: http://stackoverflow.com/q/3975376
tagged with: deep-copy
has answer: http://stackoverflow.com/a/51069598
has comment: http://stackoverflow.com/comment/89128705
has title: Does python3 dict.copy still only create shallow copies?
favorite count: 0
has comment: http://stackoverflow.com/comment/89128947
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: After reading on a few places including here: Understanding dict.copy() - shallow or deep? It claims that dict.copy will create a shallow copy otherwise known as a reference to the same values. However, when playing with it myself in python3 repl, I only get a copy by value? a = {'one': 1, 'two': 2, 'three': 3} b = a.copy() print(a is b) # False print(a == b) # True a['one'] = 5 print(a) # {'one': 5, 'two': 2, 'three': 3} print(b) # {'one': 1, 'two': 2, 'three': 3} Does this mean that shallow and deep copies do not necessarily affect immutable values?
has comment: http://stackoverflow.com/comment/89128757
answer count: 4
has comment: http://stackoverflow.com/comment/89128893
has comment: http://stackoverflow.com/comment/89128726
has answer: http://stackoverflow.com/a/51070172
score: 2
has comment: http://stackoverflow.com/comment/89128694
has comment: http://stackoverflow.com/comment/89128878
has comment: http://stackoverflow.com/comment/89128812
has answer: http://stackoverflow.com/a/51069443

http://stackoverflow.com/q/51116331
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89349317
has comment: http://stackoverflow.com/comment/89219542
score: -3
has comment: http://stackoverflow.com/comment/89218990
tagged with: python
has body: Consider this code: from tkinter import * import pymysql def newc(): def inr1(): var1 = var.get() connection = pymysql.connect(host='localhost', user='root', password='', db='class') cursor = connection.cursor() q = ("create table " + str(var1) + "(Name text,regno int,attendence text)") cursor.execute(q) connection.commit() connection.close() r2.withdraw() r3.deiconify() cfr=Frame(r3,width=800,height=600).grid(row=0,column=0) l3=Label(cfr,text="Enter the name of the class").grid(row=0,column=0) var=StringVar() ec=Entry(cfr,textvariable=var).grid(row=0,column=1) eb=Button(cfr,text="Create",command=inr1).grid(row=1,column=1) eb1=Button(cfr,text="quit",command=quit).grid(row=1,column=2) def insstud(): def inr(): classname =sec.get() stu=name.get() re1=regno.get() at=att.get() connection = pymysql.connect(host='localhost', user='root', password='', db='class') cursor = connection.cursor() q = ("insert into "+str(classname)+" values(%s,%s,%s)") values=[stu,re1,at] cursor.execute(q,values) connection.commit() connection.close() r2.withdraw() s1.deiconify() sf = Frame(s1, width=800, height=600).grid(row=0, column=0) Label(sf,text="Class").grid(row=0,column=0) Entry(sf,textvariable=sec).grid(row=0,column=1) Label(sf,text="Name").grid(row=1,column=0) Entry(sf, textvariable=name).grid(row=1, column=1) Label(sf, text="Regno").grid(row=2, column=0) Entry(sf, textvariable=regno).grid(row=2, column=1) Label(sf, text="Attendance ").grid(row=3, column=0) Entry(sf, textvariable=att).grid(row=3, column=1) Button(sf,text="Submit",command=inr).grid(row=4,column=3) def postlogin(): root.destroy() r2.deiconify() nf2=Frame(r2,width=800,height=600).grid(row=0,column=0) # /*----For Displaying class---------s-*/ b1=Button(r2,text="Show the details of a class",command=show).grid(row=0,column=0,rowspan=3,columnspan=3) # /*----For creating New class----------*/ b2=Button(r2,text="Create a new class",command=newc).grid(row=0,column=2,rowspan=3,columnspan=3) b3=Button(r2,text="Insert a student in…
upvote count: 0
type: Question
has title: pymysql.err.ProgrammingError when running tkinter+pymysql script
tagged with: pymysql
has comment: http://stackoverflow.com/comment/89218848
has comment: http://stackoverflow.com/comment/89219127
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/51116553
tagged with: mariadb

http://stackoverflow.com/q/51117367
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I try to read an excel sheet with more than 999999 rows with python xlrd module. It gives the following error when reading the row after 999999th row: File "C:\Python27\lib\site-packages\xlrd\xlsx.py", line 549, in do_row self.rowx = int(row_number) - 1 ValueError: invalid literal for int() with base 10: '1e6' Do you know a workaround for this?
tagged with: valueerror
tagged with: excel
has comment: http://stackoverflow.com/comment/89221993
score: 1
has title: python xlrd package gives ValueError when reading a sheet with more than 999999 rows
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89222503
tagged with: xlrd
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/111923623
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51026809
type: Comment
has text: Good answer. Using critical thinking and context clues (concepts taught in grade school), I understood your answer and your analogy completely. Thank you. Sorry someone down-voted you.

http://stackoverflow.com/q/51017373
tagged with: keras
favorite count: 0
has title: Keras error: "BatchNormalization Shape must be rank 1 but is rank 4 for batch_normalization"
tagged with: python
has body: I have a Keras functional model (Neural network with convolutional layers) which works fine with tensorflow. I can run it and I can fit it. However, the model cannot be built when tensorflow gpu is used. This is the line of the code when building the model which throws the error. x = BatchNormalization(axis=1)(x) And the error message is "BatchNormalization Shape must be rank 1 but is rank 4 for batch_normalization". It seems to me that it is a bug in Keras. If so, if there is a fix, how can I install this particular fix into Windows/Anaconda environment? Keras version is 2.2.0 and tensorflow gpu 1.8.0 Any idea? Thanks in advance to everyone.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51018603
upvote count: 3
tagged with: tensorflow
type: Question
score: 3
tagged with: batch-normalization
has answer: http://stackoverflow.com/a/51018603
tagged with: version
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51075091
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89158892
downvote count: 0
has comment: http://stackoverflow.com/comment/124360294
has comment: http://stackoverflow.com/comment/89142548
score: 1
answers question: http://stackoverflow.com/q/51070935
has body: You could consider training the model without round like model = Sequential() model.add(Dense(32, input_shape=(5,))) model.add(Dense(1, activation="sigmoid")) #model.add(Lambda(lambda x: K.round(x))) model.compile("adam", "mae") # or cross entropy model.fit(X_train, y_train) model.save_weights("/path/to/model.h5") Add round now. output = Lambda(lambda x: K.round(x)) (model.output) m1 = Model(model.input, output) m1.load_weights("/path/to/model.h5")

http://stackoverflow.com/comment/89334864
type: Comment
type: QuestionComment
has text: Thank you for your help! So I just tried it with that (edit above) but its still not working.
comment on: http://stackoverflow.com/q/51155745
score: 0

http://stackoverflow.com/comment/89204654
has text: I've seen, with about the same frequency, either passing a `**buffer` (and returning `size`) or passing `*size` to the function (and returning `*buffer`).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51108716
type: Comment

http://stackoverflow.com/a/51096727
has body: To match two lines before and after the keyword use a regex like this: (?:.*(?:\r?\n)+){2}age(?:.*(?:\r?\n|$)+){3} Demo Explanation: (?:.*(?:\r?\n|$)+){3} actually, you need to match 3 of those blocks since the first newline is found directly after the keyword (age) and the next is found the end of line 4 (25). Therefore, a third repetition is needed. However, since this could be the end of the string, I've added $ as an alternative. I've also added an optional \r before \n which comes handy if your strings may contain Windows line endings, otherwise remove them. Sample code: import re regex = r"(?:.*(?:\r?\n)+){2}age(?:.*(?:\r?\n|$)+){3}" test_str = (" Pratap\n" "pandey\n" "age\n" "25\n" "student") matches = re.finditer(regex, test_str, re.MULTILINE) for match in matches: matchNum = matchNum + 1 print (match.group())
score: 0
answers question: http://stackoverflow.com/q/51079333
type: Answer

http://stackoverflow.com/q/51127363
has answer: http://stackoverflow.com/a/51127431
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51127431
has comment: http://stackoverflow.com/comment/89239730
has title: Python matplotlib manipulating to use it in the plot title
type: Question
answer count: 2
has body: assume I've the following variable roundi = theta_result_lasso.round(2) [ 0. -2.36] where theta_result_lasso.round are just two values. The line for my plot title is ax.set_title(r'Globales Minimum $\hat \beta$ = {}'.format(roundi), fontsize=20) producing this: is there a way to replace the "." after the zero by a "," and descreasing the disance between the two values as it should look like a "vector" ? It should look like this: [0, -2.36] If you Need further informations, I'll provide an example
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89239742
has answer: http://stackoverflow.com/a/51127430
accepted answer: http://stackoverflow.com/a/51127430
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/89083874
score: 0
type: Comment
type: QuestionComment
has text: What does `python --version` show you?
comment on: http://stackoverflow.com/q/51046290

http://stackoverflow.com/comment/89206048
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51109420
has text: you answered the question yourself. you create it running code in your terminal

http://stackoverflow.com/comment/89048670
type: Comment
has text: Maybe you can try it [code](https://paste.ubuntu.com/p/7NVwvgjFqM/), move driver.quit( ) to outside. @Ruman_Hossain
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51017967

http://stackoverflow.com/comment/89270264
has text: I've resolved the issue, the findall() function I was using to gather the time data was posting a length 1 list to my DataFrame. I select the first value [0] from it removing the brackets and am able to .agg the min and max values, thanks for the help!
comment on: http://stackoverflow.com/q/51140916
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51039925
tagged with: pandas
has comment: http://stackoverflow.com/comment/89071145
tagged with: python
score: 1
has body: I have two DateFrame with values and number of rows different. All Index values in second DateFrame is in the first, so, I need a DateFrame with the same number of rows that the second DateFrame and all data of both DateFrames. Example df1 = pd.DataFrame(columns=["A", "B", "C"], data=[['a1' , 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']], index=[1,2,3]) df2 = pd.DataFrame(columns=["D", "E"], data=[['d2' , 'e2'], ['d3' , 'e3']], index=[2,3]) print (df1) print (df2) Out: A B C 1 a1 b1 c1 2 a2 b2 c2 3 a3 b3 c3 D E 2 d2 e2 3 d3 e3 I want: A B C D E 2 a2 b2 c2 d2 e2 3 a3 b3 c3 d3 e3 I try this: merge = df1.merge(df2, how='inner', left_on=df1.index, right_on=df2.index) But I receive an error: IndexError: indices are out-of-bounds Note: Not all index in df1 are in df2 but all index in df2 are in df1.
has comment: http://stackoverflow.com/comment/89071201
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89071092
type: Question
downvote count: 0
favorite count: 0
has title: Merge two Dataframe with columns name differents

http://stackoverflow.com/q/51078671
favorite count: 0
has comment: http://stackoverflow.com/comment/89146978
has comment: http://stackoverflow.com/comment/89146570
has title: Python BFS not giving the shortest path
tagged with: breadth-first-search
downvote count: 0
has comment: http://stackoverflow.com/comment/89146392
has comment: http://stackoverflow.com/comment/89146910
has body: I have implemented breadth-first search according to the pseudo-code in CLRS. However, it's not always giving me the shortest path between two nodes, as you can clearly see on the image below. Here it went 10 -> 5 -> 1 -> 6 -> 0 but it should clearly have gone through 10 -> 1 -> 0. Nodes and edges: [[6, 7], [5, 0, 4], [6, 0, 4], [9, 4], [8, 2], [4, 9, 10], [1], [0], [9, 0], [7, 7], [8, 3, 1]] Distances: [0, 2, 4, 5, 3, 3, 1, 1, 4, 4, 4] Colors ( 2 stands for black ): [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] Predecessors: [None, 6, 4, 10, 1, 1, 0, 0, 4, 5, 5] I can't figure out what's happening here as it seems that I'm doing exactly what's described in CLRS. Most of the times it gets the right path but sometimes it goes wrong for unknown reasons. There's also a possibility that I'm just drawing the graph wrong with networkx, I don't know. The overall idea is that the code below generates random graphs until it finds one where it's possible to draw the shortest path between nodes a and b (i.e. a and b are not disjoint ). Graph() is my own class and nx.Graph() is a different function from the networkx library. from collections import deque import networkx as nx import matplotlib.pyplot as plt import random class Graph(object): def __init__(self,graph): self.nodes = graph self.colors = [0] * len(graph) self.distances = [len(graph) + 1000] * len(graph) self.predecessor = [None] * len(graph) self.queue = deque() self.nodelist = ['red'] * len(graph) def BFS(self,start): self.__init__(self.nodes) self.colors[start] = 1 #GRAY self.distances[start] = 0 self.queue.append(start) while self.queue: current = self.queue.popleft() for node in self.nodes[current]: if self.colors[node] == 0: #WHITE self.colors[node] = 1 #GRAY self.distances[node] = self.distances[current] + 1 self.predecessor[node] = current self.queue.append(node) self.colors[current] = 2 #BLACK def draw_path(self,start,end): self.nodelist[start] = 'green' previous = end while previous != start: self.nodelist[previous] = …
tagged with: python
accepted answer: http://stackoverflow.com/a/51079385
has comment: http://stackoverflow.com/comment/89146618
has comment: http://stackoverflow.com/comment/89147212
tagged with: networkx
has comment: http://stackoverflow.com/comment/89147051
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89147252
has comment: http://stackoverflow.com/comment/89146849
tagged with: algorithm
score: 1
has answer: http://stackoverflow.com/a/51079385
has comment: http://stackoverflow.com/comment/89146911
has comment: http://stackoverflow.com/comment/89147082
type: Question
has comment: http://stackoverflow.com/comment/89147277
has comment: http://stackoverflow.com/comment/89146722
upvote count: 1
has comment: http://stackoverflow.com/comment/89146994
answer count: 1

http://stackoverflow.com/comment/89257868
comment on: http://stackoverflow.com/q/51136890
has text: `cap.append(random.choice(values))` do you mean `cap.extend(random.choice(values))` ? what is your expected output and what's your current input?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51077280
type: Question
has comment: http://stackoverflow.com/comment/89143822
has comment: http://stackoverflow.com/comment/89143702
has body: I have an api endpoint that passes a variable which is used to make a call in the database. For some reason it cannot run the query yet the syntax is correct. My code is below. @app.route('/api/update/&lt;lastqnid&gt;') def check_new_entries(lastqnid): result = Trades.query.filter_by(id=lastqnid).first() new_entries = Trades.query.filter(Trades.time_recorded &gt; result.time_recorded).all() The id field is: id = db.Column(db.String,default=lambda: str(uuid4().hex), primary_key=True) I have tried filter instead of filter_by and it does not work. When I remove the filter_by(id=lastqnid) it works. What could be the reason it is not running the query? The trades table am querying from is class Trades(db.Model): id = db.Column(db.String,default=lambda: str(uuid4().hex), primary_key=True) amount = db.Column(db.Integer, unique=False) time_recorded = db.Column(db.DateTime, unique=False)
score: 2
has title: AttributeError: 'NoneType' object has no attribute 'time_recorded' in Flask, SQLAlchemy
has comment: http://stackoverflow.com/comment/89143784
answer count: 1
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/89143791
has comment: http://stackoverflow.com/comment/89143884
tagged with: python
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51077649
has comment: http://stackoverflow.com/comment/89143999
tagged with: sqlalchemy

http://stackoverflow.com/a/51158081
score: 0
type: Answer
has body: Ok so the function was working fine on its own, the problem turned out to be in my 'run' function and I was actually able to fix it. Here's the code from my updated write_values_to_spreadsheet and 'run' function. def write_values_to_spreadsheet(wb, total_protein_dictionary): """Takes the keys and values of the total protein dictionary and puts them in the spreasheet""" sheet = wb.active print(len(total_protein_dictionary)) for next_row in range(1, len(total_protein_dictionary)+1): food, protein_grams = total_protein_dictionary.popitem() sheet.cell(column=1 , row=next_row, value=food) sheet.cell(column=2 , row=next_row, value=protein_grams) def run(file): """Runs the whole program""" wb = openpyxl.load_workbook(file) #opens the workbook at the beginning checks_sheet_title(wb) #food_protein(x) function start eaten_today = str(input("Did you eat any food today?\n")).lower() total_protein_dictionary = {} #creates dictionary that can be updated, taken as a paramter in food_protein if eaten_today == "yes": foods_documented = False #answers the question: has all food eaten today been accounted for? total_protein_dictionary.update(food_protein(total_protein_dictionary)) #updates with new food print(total_protein_dictionary) while foods_documented == False: more_food = str(input("Did you have any more food?\n")) if more_food == "yes": total_protein_dictionary.update(food_protein(total_protein_dictionary)) print(total_protein_dictionary) elif more_food == "no": foods_documented = True #escapes print("Today you've had " + str(sum(total_protein_dictionary.values())) + " grams of protein so far today.") write_values_to_spreadsheet(wb, total_protein_dictionary) wb.save(file) The first bit of 'run' prompts the user to make the dictionary, then on line 35 calls write_values_to_spreadsheet. What fixed the issue for me is that I changed write_values_to_spreadsheet to take wb as a parameter instead of file, in the process I deleted wb = openpyxl.load_workbook(file) and wb.save(file) b…
answers question: http://stackoverflow.com/q/51145253

http://stackoverflow.com/a/51124451
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89234017
has comment: http://stackoverflow.com/comment/89242301
has body: Use an infinite loop and break only when all criteria are satisfied instead. while True: varD = input("Enter Day:") if varD.isdigit() and not varD.isspace() and varD.isdecimal() \ and int(varD) &lt; 32 and int(varD) != 26 and int(varD) &gt; 0: break print("Error: Enter Valid Number!") print("You have entered: %s" % varD) Also, your understanding of the term triple nesting is incorrect. Triple nesting means something like this: while expression1: while expression2: while expression3: do_something()
has comment: http://stackoverflow.com/comment/89242356
has comment: http://stackoverflow.com/comment/89233982
type: Answer
has comment: http://stackoverflow.com/comment/89234038
score: 2
has comment: http://stackoverflow.com/comment/89253114
has comment: http://stackoverflow.com/comment/89242120
downvote count: 0
has comment: http://stackoverflow.com/comment/89242442
has comment: http://stackoverflow.com/comment/89242995
has comment: http://stackoverflow.com/comment/89271736
has comment: http://stackoverflow.com/comment/89233997
accepted answer of: http://stackoverflow.com/q/51124413
has comment: http://stackoverflow.com/comment/89242392
has comment: http://stackoverflow.com/comment/89241154
answers question: http://stackoverflow.com/q/51124413
has comment: http://stackoverflow.com/comment/89257650
has comment: http://stackoverflow.com/comment/89241539
upvote count: 2
has comment: http://stackoverflow.com/comment/89242845

hierarchical-clustering
tags question: http://stackoverflow.com/q/51089814
tags question: http://stackoverflow.com/q/51129498
tag name: hierarchical-clustering
type: Tag

http://stackoverflow.com/q/51092351
type: UnansweredQuestion
tagged with: python
has body: I am new to opencv and I'm trying to do circle detection using HoughCircles, but it's giving me circles where there are none, and it's not detecting the huge obvious circle that I want it to. I tried changing the parameters but can't get it to work well. What am I doing wrong? Original Image: Image After Thresholding: Canny Filtered with Circles: path=r"minimap.png" screen = cv2.imread(path,cv2.IMREAD_GRAYSCALE) cv2.imshow('Original', screen) ret,screen = cv2.threshold(screen,200,255,cv2.THRESH_BINARY) cv2.imshow('Thresholded', screen) P=50 can = cv2.Canny(screen,P/2,P) cv2.imshow('Canny', can) if 1: circles = cv2.HoughCircles(screen, cv2.HOUGH_GRADIENT, dp=1, minDist=50, param1=P, param2=53, minRadius=0, maxRadius=0) print(circles) circles = np.uint16(np.around(circles)) can=cv2.cvtColor(can,cv2.COLOR_GRAY2RGB) for i in circles[0,:]: # draw the outer circle cv2.circle(can, (i[0], i[1]), i[2], (0, 255, 0), 3) # draw the center of the circle cv2.circle(can, (i[0], i[1]), 2, (0, 0, 255), 5) cv2.imshow('Circles', can) cv2.waitKey()
tagged with: opencv
tagged with: detection
tagged with: hough-transform
has answer: http://stackoverflow.com/a/51100375
type: Question
score: 0
answer count: 1
has title: OpenCV cv2.HoughCircles detection giving bad results on easy picture
tagged with: geometry

http://stackoverflow.com/a/51072812
has comment: http://stackoverflow.com/comment/89135291
score: 0
answers question: http://stackoverflow.com/q/51072793
has body: Use zip to combine items from each list with the same index: for x, y, z in zip(list1, list2, list3): print(x, y, z) subject1 subject2 subject3 subject4 subject5 subject6 subject7 subject8 subject9 subject10 subject11 subject12
type: Answer

http://stackoverflow.com/q/51095704
has comment: http://stackoverflow.com/comment/89210893
type: AnsweredQuestion
tagged with: flask-wtforms
has body: My purpose is to construct a form with dynamicly provided labels and use it in Jinja Form. This made me reveal multiple fundemental questions. As in the exemple here from flask_wtf import FlaskForm from wtforms import SubmitField from wtforms.validators import DataRequired class LoginForm(FlaskForm): # submit = SubmitField('Go On') def __init__(self, BtnLble): self.submit = SubmitField(BtnLble,form=self, name="MySbmt", _meta=self.Meta) # self.submit.bind(form=self, name="MySbmt", _meta=self.Meta) super(LoginForm,self).__init__() self.submit() # .__call__() does not exist def UseForm( ) : Login = LoginForm(“Hit here”) if form.validate_on_submit(): flash('Wellcom... ' ) return redirect(url_for(‘GoOn’)) return render_template('Login.html', **locals()) I try to construct my form ‘dynamically’ in the __init __ part of the form class. It seems that the construction of elements (put in comment in the example) differs from that one done in the declaration part In the above example, the call “submit()” will result with ‘Non callable object’. While it will be possible if only it is declared in declaration part ! So the following questions become to mind : 1) What is the difference between declaration in the declaration part and the one done inside __init __'. We are not using a ‘static’ variable her! 2) How to make a ‘field of a Form’ callable ? 3) It seems that the callability becomes to exist only after the call of the FlaskForm’s initiator. How does it add ‘a method’ to this object ? I noticed that similar questions have been revealed by other experienced developers, but they did not provided them in such simple way, like this one WTForms keeps giving "Not Callable" error during server run, but not on the python prompt
tagged with: jinja2
type: Question
tagged with: wtforms
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/47480354
has title: Dynamic Flask-Form construction intended for use under Jinja
has answer: http://stackoverflow.com/a/51112483
accepted answer: http://stackoverflow.com/a/51112483
tagged with: python

http://stackoverflow.com/q/51067991
favorite count: 0
tagged with: terminal
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89126089
tagged with: python
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has body: My code has been running for 3 days now and my computer suddenly restarted, and my code won't continue where it left off. I get the following: [Restored Jun 27, 2018 at 6:22:51 PM] Last login: Wed Jun 27 18:22:43 on console Restored session: Wed Jun 27 18:09:53 CEST 2018 -bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory I've changed nothing in terms of location of files etc. How can I make it continue where it left off without having to start it all over again? I stupidly only made it write the results into a csv file once all the results are collected, so now I basically have nothing.
has comment: http://stackoverflow.com/comment/89125837
score: 0
has comment: http://stackoverflow.com/comment/89965743
has title: Computer restarted while python still running but now won't recover

http://stackoverflow.com/q/51054454
tagged with: isinstance
has comment: http://stackoverflow.com/comment/89099665
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51054477
has answer: http://stackoverflow.com/a/51054477
has title: Error in using operators in function arguments (isinstance) in Python
has body: I can't seem to wrap my head around the output of this function: def is_integer(num1, num2): if isinstance(num1 and num2, int): return 'Yes' else: return 'No' print(is_integer(1.4, 2)) This will output 'Yes', but it shouldn't as 1.4 and 2 are not both integers. Any help?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51054483
upvote count: 0
score: -2
tagged with: arguments
favorite count: 0
linked to: http://stackoverflow.com/q/47007680
downvote count: 2
has answer: http://stackoverflow.com/a/51054483
tagged with: python

http://stackoverflow.com/comment/89258720
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51126675
has text: Nevermind, found it. Pass on the arguments as a dictionary and use ** instead of * while passing arguments.

arrays
tags question: http://stackoverflow.com/q/51090205
tags question: http://stackoverflow.com/q/51151945
type: Tag
tags question: http://stackoverflow.com/q/51044957
tags question: http://stackoverflow.com/q/51026162
tags question: http://stackoverflow.com/q/51159491
tags question: http://stackoverflow.com/q/51072573
tags question: http://stackoverflow.com/q/51103867
tags question: http://stackoverflow.com/q/51092737
tags question: http://stackoverflow.com/q/51142082
tags question: http://stackoverflow.com/q/51036850
tags question: http://stackoverflow.com/q/51015003
tags question: http://stackoverflow.com/q/51022380
tags question: http://stackoverflow.com/q/51012084
tags question: http://stackoverflow.com/q/51156042
tags question: http://stackoverflow.com/q/51017095
tags question: http://stackoverflow.com/q/51164356
tags question: http://stackoverflow.com/q/51152043
tags question: http://stackoverflow.com/q/51052142
tags question: http://stackoverflow.com/q/51164294
tags question: http://stackoverflow.com/q/51079660
tags question: http://stackoverflow.com/q/51119246
tags question: http://stackoverflow.com/q/51058614
tags question: http://stackoverflow.com/q/51022577
tags question: http://stackoverflow.com/q/51030608
tags question: http://stackoverflow.com/q/51138775
tags question: http://stackoverflow.com/q/51122073
tags question: http://stackoverflow.com/q/51113280
tags question: http://stackoverflow.com/q/51139460
tags question: http://stackoverflow.com/q/51030316
tags question: http://stackoverflow.com/q/51110764
tags question: http://stackoverflow.com/q/51134734
tags question: http://stackoverflow.com/q/51116707
tags question: http://stackoverflow.com/q/51084043
tag name: arrays
tags question: http://stackoverflow.com/q/51021544
tags question: http://stackoverflow.com/q/51106131
tags question: http://stackoverflow.com/q/51125847
tags question: http://stackoverflow.com/q/51031140
tags question: http://stackoverflow.com/q/51056081
tags question: http://stackoverflow.com/q/51146933
tags question: http://stackoverflow.com/q/51149911
tags question: http://stackoverflow.com/q/51117943
tags question: http://stackoverflow.com/q/51046762
tags question: http://stackoverflow.com/q/51124540
tags question: http://stackoverflow.com/q/51011970
tags question: http://stackoverflow.com/q/51030163
tags question: http://stackoverflow.com/q/51158629
tags question: http://stackoverflow.com/q/51164408
tags question: http://stackoverflow.com/q/51023113
tags question: http://stackoverflow.com/q/51046537
tags question: http://stackoverflow.com/q/51144127
tags question: http://stackoverflow.com/q/51042742
tags question: http://stackoverflow.com/q/51072399
tags question: http://stackoverflow.com/q/51157655
tags question: http://stackoverflow.com/q/51127792
tags question: http://stackoverflow.com/q/51128035
tags question: http://stackoverflow.com/q/51143682
tags question: http://stackoverflow.com/q/51019139
tags question: http://stackoverflow.com/q/51040326
tags question: http://stackoverflow.com/q/51122730
tags question: http://stackoverflow.com/q/51142026
tags question: http://stackoverflow.com/q/51085780
tags question: http://stackoverflow.com/q/51107057
tags question: http://stackoverflow.com/q/51144944
tags question: http://stackoverflow.com/q/51021292
tags question: http://stackoverflow.com/q/51149865
tags question: http://stackoverflow.com/q/51101791
tags question: http://stackoverflow.com/q/51058577
tags question: http://stackoverflow.com/q/51090121
tags question: http://stackoverflow.com/q/51149809

http://stackoverflow.com/q/51030140
score: 0
has comment: http://stackoverflow.com/comment/89052608
has body: I am trying to compare the similarity between 1 number and a list of numbers, and not sure how to generate this problem? I know how to compare the similarity of 2 inputs: from difflib import SequenceMatcher def similar(a,b): return SequenceMatcher(None, a, b).ratio() a = '123abc' b = '321321' similar(a,b) And now I want to compare the similarity/relevance between 1 number and a list of number, I tried: A=[1,2,3,4,5,6,7] B=2 from difflib import SequenceMatcher def similar(a,b): return SequenceMatcher(None, a, b).ratio() similar (A,B) And it does not give me what I want - it shows "'int' object is not iterable". I am trying to get the accuracy/confident of how the number (2) is matching with the list of A. Ideally in this case - if the number is 2, and the list if from 1-7 then similarity is 1, and if the number is 8 or 9 then similarity is 0. Anyone has ideas of how to do it? I am a new python learner - Thank you in advance!
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51030198
tagged with: relevance
tagged with: similarity
answer count: 2
has title: Python - Compare the similarity of one number and a list of numbers
possible better answer: http://stackoverflow.com/a/51030238
tagged with: python
has answer: http://stackoverflow.com/a/51030238
accepted answer: http://stackoverflow.com/a/51030198

http://stackoverflow.com/q/51054293
tagged with: python
type: AnsweredQuestion
has title: Example in np.argsort document
score: 1
type: Question
tagged with: numpy
downvote count: 0
tagged with: sorting
has answer: http://stackoverflow.com/a/51054371
answer count: 1
favorite count: 0
has body: For some reason I cannot resolve this. According to the example here for 1-dim array, https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html x = np.array([3, 1, 2]) np.argsort(x) array([1, 2, 0]) And I have tried this myself. But by default, the return result should be ascending..meaning x([result]) returns array([1, 2, 3]) Thus shouldnt the result be [2,0,1] What am I missing here?
accepted answer: http://stackoverflow.com/a/51054371
upvote count: 1

http://stackoverflow.com/q/51035522
downvote count: 1
has comment: http://stackoverflow.com/comment/89063320
has comment: http://stackoverflow.com/comment/89063287
has body: so I'm making a script that tries to find the best way to guess a number without guessing over. When I run it I ge this: line 25, in rt[0]=rt[0]+1 TypeError: Can't convert 'int' object to str implicitly And here is my code: import random guess=10 res=[1,2,3,4,5,6,7,8,9] n1=[0,0,0] n2=[0,0,0] n3=[0,0,0] n4=[0,0,0] n5=[0,0,0] n6=[0,0,0] n7=[0,0,0] n8=[0,0,0] n9=[0,0,0] gn=0 num=input('num: ') while guess!=num: guess=res[gn] print('guess: ' + str(guess)) guess=str(guess) rt=str('n'+(guess)) guess=int(guess) num=int(num) if guess&gt;num: rt[1]=rt[1]+1 if guess&lt;num: rt[0]=rt[0]+1 rt[2]=rt[0]-rt[1]
has title: TypeError: Can't convert 'int' object to str simplicity implicitly
type: Question
tagged with: int
score: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89062901
tagged with: typeerror
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89063004
upvote count: 1

http://stackoverflow.com/comment/89140057
type: QuestionComment
has text: Ohhhh okay sorry about that. Just uploaded another screenshot. Is that more helpful? I appreciate it thanks!
comment on: http://stackoverflow.com/q/51068397
score: 0
type: Comment

http://stackoverflow.com/q/51136784
type: Question
has comment: http://stackoverflow.com/comment/89257615
has body: I want to get the response code from a web server, but sometime I get code 200 even if the page doesn't exist and I don't know how to deal with it. I'm using this code: def checking_url(link): try: link = urllib.request.urlopen(link) response = link.code except urllib.error.HTTPError as e: response = e.code return response When I'm checking a website like this one: https://www.wykop.pl/notexistlinkkk/ It still returns code 200 even if the page doesn't exist. Is there any solution to deal with it? I found solution, now gonna test it with more websites I had to use http.client.
tagged with: response
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51136919
tagged with: python
has answer: http://stackoverflow.com/a/51136976
has title: Python Http, getting response code from server
type: UnansweredQuestion
tagged with: http
has comment: http://stackoverflow.com/comment/89265613

http://stackoverflow.com/a/51063092
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51061685
type: Answer
has body: Pnet is a network which performs many convolutions. You can pass an image to the input layer and it performs many convolutions on it. Name of input layer is 'data'. Input layer is a tensor which accepts an image. data = tf.placeholder(tf.float32, (None,None,None,3), 'input') pnet = PNet({'data':data}) Consider out = pnet(img_y) img_y is placed on 'data' layer of Pnet, which is fed to a convolution layer. .conv(3, 3, 10, 1, 1, padding='VALID', relu=False, name='conv1') k_h (kernel height) = 3 k_w (kernel width) = 3 c_o (number of filters) = 10 s_h (stride height) = 1 s_w (stride width) = 1 inp is output of previous layer i.e data layer which is our image. prelu and max pool are applied, then the output is fed as input of next convolution layer. .conv(3, 3, 16, 1, 1, padding='VALID', relu=False, name='conv2') and so on. To understand convolutional neural networks better, refer CNN

http://stackoverflow.com/a/51019749
score: 1
has comment: http://stackoverflow.com/comment/89032197
downvote count: 0
type: AcceptedAnswer
has body: In the Scala DataFrame API, the select method takes a variable number of arguments. In the method signature, this is denoted by a * as in the following example: // Greet many people def greet(who: String*): String = ??? // all valid calls greet() greet("world") greet("alice", "bob") The : token is used to give a hint to the compiler regarding the type of the argument and the _* in this case is used to specify that we are passing a collection as a list of arguments: def people: Seq[String] = getPeopleToGreet() greet(people) // won't compile greet(people: _*) // passes the collection of people as a list of arguments -- works Not sure of how the Python API works, but from my experience I imagine you can either pass a single value or an array, so I believe the problem just doesn't exist in Python.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51019490
accepted answer of: http://stackoverflow.com/q/51019490

http://stackoverflow.com/a/51174322
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51124725
upvote count: 2
type: Answer
has body: @Ilja Everilä answer was mostly helpful I'll leave edited code here, maybe it'll help someone New code that works like I expected is following: making connection to DB:: from sqlalchemy.pool import NullPool # will work even without NullPool in code def connect(user, password, db, host='localhost', port=5432): """Returns a connection and a metadata object""" url = 'postgresql://{}:{}@{}:{}/{}'.format(user, password, host, port, db) temp_con = sqlalchemy.create_engine(url, client_encoding='utf8', poolclass=NullPool) temp_meta = sqlalchemy.MetaData(bind=temp_con, reflect=True) return temp_con, temp_meta one instance of connection and sessionmaker per app, for example where your main function: from sqlalchemy.orm import sessionmaker # create one connection and Sessionmaker to each instance of app (to avoid creating it repeatedly) con, meta = connect(db_user, db_pass, db_instance, db_host) session_maker = sessionmaker(bind=con) enter code here function to get session with with statement: from contextlib import contextmanager from some_place import session_maker @contextmanager def session_scope() -&gt; Session: """Provide a transactional scope around a series of operations.""" session = session_maker() # create session from SQLAlchemy sessionmaker try: yield session session.commit() except: session.rollback() raise wrap transaction and use session: with session_scope() as session: entity = session.query(SomeEntity).first()

http://stackoverflow.com/q/51106254
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92028000
has answer: http://stackoverflow.com/a/62415693
has comment: http://stackoverflow.com/comment/89218048
upvote count: 5
has body: I tried to answer this question from TestDome and got 250877.19298245612 instead of 250000 as suggested. Please let me what went wrong. Thanks import numpy as np from sklearn import linear_model class MarketingCosts: # param marketing_expenditure list. Expenditure for each previous campaign. # param units_sold list. The number of units sold for each previous campaign. # param desired_units_sold int. Target number of units to sell in the new campaign. # returns float. Required amount of money to be invested. @staticmethod def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold): X = [[i] for i in units_sold] reg = linear_model.LinearRegression() reg.fit(X, marketing_expenditure) return float(reg.predict(desired_units_sold)) #For example, with the parameters below the function should return 250000.0. print(MarketingCosts.desired_marketing_expenditure( [300000, 200000, 400000, 300000, 100000], [60000, 50000, 90000, 80000, 30000], 60000))
has answer: http://stackoverflow.com/a/60620520
type: Question
score: 5
has answer: http://stackoverflow.com/a/57237075
downvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/55669463
favorite count: 0
tagged with: python-3.x
has title: TestDome Data Science: Not getting correct answer
has answer: http://stackoverflow.com/a/55699235
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/89218060

http://stackoverflow.com/comment/89179107
score: 0
has text: What do you mean by "somehow not able to" - what problem are you having specifically? What does it not do?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51095528

http://stackoverflow.com/q/51160368
has title: How does python know if daylight savings time is in effect?
score: 0
tagged with: python
has body: Since the start and end times of DST in a timezone can change every year, so how does python tell if dst is in effect or not?
tagged with: timezone
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89304121
has comment: http://stackoverflow.com/comment/89304164
has answer: http://stackoverflow.com/a/51160472
type: Question
has comment: http://stackoverflow.com/comment/89304238
has answer: http://stackoverflow.com/a/51160561
answer count: 2
linked to: http://stackoverflow.com/q/2881025

http://stackoverflow.com/comment/89287376
type: QuestionComment
has text: Deactivate your Virtualenv, and run "pip freeze" to check django installed.
type: Comment
comment on: http://stackoverflow.com/q/51151289
score: 0

http://stackoverflow.com/q/51088265
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51088581
has body: My local python application calls a REST api using httplib2. It has worked fine for over a year. This morning I started to receive the following error: 2018-06-28 12:43:07.001 Python[1722:25727] IMKInputSession [0x7f99e21ac2f0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7f99dfd48440 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4097 "connection from pid 0" UserInfo={NSDebugDescription=connection from pid 0}, com.apple.inputmethod.EmojiFunctionRowItem Initially, I thought this was caused by my openSSL certificate being out of date. I have updated to openSSL 1.1. I have also updated from python 3.6 to 3.7. I am still getting the same error. The code that makes the call is below. connection = httplib2.HTTPSConnectionWithTimeout(URL, 443, timeout = 300) print('Connection made') self.headers = {"Accept":"application/json", "Authorization":Token} print(connection) connection.request('GET', request_command, body=None headers=self.headers) print('request made') The error is caused by connection.request().
tagged with: rest
has title: OSError: [Errno 0] Error in httplib2 request
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: https
type: Question
tagged with: httplib2
accepted answer: http://stackoverflow.com/a/51088581

http://stackoverflow.com/q/51076827
type: Question
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/47137592
possible better answer: http://stackoverflow.com/a/51078278
has answer: http://stackoverflow.com/a/51078278
score: 3
has answer: http://stackoverflow.com/a/51097747
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I need to sort some tasks in Celery that some of them should as a single task and some should work parallel and when the tasks in the group completed, it should pass the next one: chain( task1.s(), task2.s(), group(task3.s(), task4.s()), group(task5.s(), task6.s(), task7.s()), task7.s() ).delay() But I think what did I do is wrong. Any body have idea how to do it? Also, I don't care about sending the result of each task to the others.
accepted answer: http://stackoverflow.com/a/51097747
upvote count: 3
has title: Celery groups and chains
tagged with: celery

http://stackoverflow.com/q/51084664
has comment: http://stackoverflow.com/comment/89158033
type: UnansweredQuestion
score: -3
tagged with: python
has body: I'd like to perform a "mixed" unsupervised clustering which uses first a KMeans algorithm to generate a certain number of first small and homogeneous clusters and THEN apply a hierarchical clustering on these clusters I get from Kmeans. I used cluster.Kmeans from scikit-learn for the first part, and I have my clusters but then I don't know how to use the AgglomerativeClustering function from sklearn so that it can go from those clusters. Any ideas? Thank you !
downvote count: 3
has title: How to implement a sklearn -AgglomerativeClustering from clusters?
has answer: http://stackoverflow.com/a/51112772
type: Question
upvote count: 0
tagged with: k-means
tagged with: cluster-analysis
tagged with: scikit-learn
favorite count: 0
answer count: 1

http://stackoverflow.com/q/51163667
tagged with: mxnet
type: Question
has body: I am try to write prediction part of script for the tutorial: https://mxnet.incubator.apache.org/tutorials/nlp/cnn.html import mxnet as mx from collections import Counter import os import re import threading import sys import itertools import numpy as np from collections import namedtuple SENTENCES_DIR = 'C:/code/mxnet/sentences' CURRENT_DIR = 'C:/code/mxnet' def clean_str(string): string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) string = re.sub(r"\'ll", " \'ll", string) string = re.sub(r",", " , ", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\(", " \( ", string) string = re.sub(r"\)", " \) ", string) string = re.sub(r"\?", " \? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower() def load_data_sentences(filename): sentences_file = open( filename, "r") # Tokenize x_text = [line.decode('Latin1').strip() for line in sentences_file.readlines()] x_text = [clean_str(sent).split(" ") for sent in x_text] return x_text def pad_sentences(sentences, padding_word=""):" sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i in range(len(sentences)): sentence = sentences[i] num_padding = sequence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding padded_sentences.append(new_sentence) return padded_sentences def build_vocab(sentences): word_counts = Counter(itertools.chain(*sentences)) vocabulary_inv = [x[0] for x in word_counts.most_common()] vocabulary = {x: i for i, x in enumerate(vocabulary_inv)} return vocabulary, vocabulary_inv def build_input_data(sentences, vocabulary): x = np.array([ [vocabulary[word] for word in sentence] for sentence in sentences]) return x def predict(mod, sen): mod.forward(Batch(data=[mx.nd.array(sen)])) prob = mod.get_outputs()[0].asnumpy() prob =…
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51388891
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Error in prediction script using CNN model for text classification

http://stackoverflow.com/comment/89257481
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51126393
has text: I am sorry, but when I am trying to handle callback data `m1_1` it for some reason triggers the handler for `m1` callback data until I use more strong pattern with `^` and `$` regex syntax

http://stackoverflow.com/q/51162092
has comment: http://stackoverflow.com/comment/89313121
upvote count: 2
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89311606
has body: So I am trying to encode two strings to utf-8 so I can use them with pandas.read_sql: selectedTable = "ACC__AccountCodes" baseSql = "SELECT * FROM FileMaker_Fields WHERE TableName=" Now when I encode these two things: baseSql.encode('utf-8') selectedTable.encode('utf-8') sqlString = "{}{}".format(baseSql, selectedTable) My output looks like this: b'SELECT * FROM FileMaker_Fields WHERE TableName='b'A\x00C\x00C\x00_\x00_\x00A\x00c\x00c\x00o\x00u\x00n\x00t\x00C\x00o\x00d\x00e\x00s\x00'' So when I run it with encoding set to 'latin1' I get the error: pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT * FROM FileMaker_Fields WHERE TableName=ACC__AccountCodes': ('HY000', '[HY000] [\x00F\x00i\x00l\x00e\x00M\x00a\x00k\x00e\x00r\x00]\x00[\x00F\x00i\x00l\x00e\x00M\x00a\x00k\x00e\x00r\x00]\x00 \x00F\x00Q\x00L\x000\x000\x000\x007\x00/\x00(\x001\x00:\x004\x007\x00)\x00:\x00 \x00T\x00h\x00e\x00 \x00c\x00o\x00l\x00u\x00m\x00n\x00 \x00n\x00a\x00m\x00e\x00d\x00 \x00"\x00A\x00"\x00 \x00d\x00o\x00e\x00s\x00 \x00n\x00o\x00t\x00 \x00e\x00x\x00i\x00s\x00t\x00..... I can't seem to find anything addressing this. Everything I have tried leads me back to this which causes a sql error for invalid syntax. I am using pyodbc which expects utf-8 encoding as the input. Thoughts?
tagged with: python-3.x
has title: Python encoding issue with pandas read_sql
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/51162111
accepted answer: http://stackoverflow.com/a/51162111
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/51071163
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/89160240
score: 8
has comment: http://stackoverflow.com/comment/89136680
has comment: http://stackoverflow.com/comment/98675578
has comment: http://stackoverflow.com/comment/89132239
has comment: http://stackoverflow.com/comment/89132298
has comment: http://stackoverflow.com/comment/89132202
answers question: http://stackoverflow.com/q/51070251
has body: As suggested by @pault, the data field is a string field. since the keys are the same (i.e. 'key1', 'key2') in the JSON string over rows, you might also use json_tuple() (this function is New in version 1.6 based on the documentation) from pyspark.sql import functions as F df.select('id', 'point', F.json_tuple('data', 'key1', 'key2').alias('key1', 'key2')).show() Below is My original post: which is most likely WRONG if the original table is from df.show(truncate=False) and thus the data field is NOT a python data structure. Since you have exploded the data into rows, I supposed the column data is a Python data structure instead of a string: from pyspark.sql import functions as F df.select('id', 'point', F.col('data').getItem('key1').alias('key1'), F.col('data')['key2'].alias('key2')).show()
downvote count: 0

http://stackoverflow.com/comment/89061944
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51032986
has text: Now start your programming
type: QuestionComment

http://stackoverflow.com/a/51141645
answers question: http://stackoverflow.com/q/51140048
type: Answer
has comment: http://stackoverflow.com/comment/89267443
has comment: http://stackoverflow.com/comment/89267980
score: 0
has comment: http://stackoverflow.com/comment/89268062
has comment: http://stackoverflow.com/comment/89268199
has comment: http://stackoverflow.com/comment/89269798
has body: You could get the answer to a specific question with the reverse relation question_instance.answer_set.all() in views, {{ question_instance.answer_set.all }} in templates. To select one answer, you can use slice, or first(): {{question_instance.answer_set.all.0 }} # templates question_instance.answer_set.first() # views If you want to add a new field votes to the Question and you want the answer which has highest votes? A property method inside your question model will do it like: @property def higher_answer(self): return self.answer_set.all().order_by('vote').last()
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51140048

http://stackoverflow.com/q/51082855
has title: Efficiently extracting rows from pandas dataframe in which I have to search for elements in a list
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51082897
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51082897
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: My dataframe is like this: id author 1 ['abc','def','alp'] 2 ['akx','xyz','shdj','dhhs'] 3 ['abc', 'alp','pqw'] For eg, I want to extract all the rows with authors ['abc','alp'].It should extract rows 1 and 3. Is there any efficient way to do this using python pandas?
upvote count: 2
score: 1

mousewheel
tags question: http://stackoverflow.com/q/51073113
type: Tag
tag name: mousewheel

http://stackoverflow.com/comment/89038052
type: Comment
type: QuestionComment
has text: Yeah, I know, since pass does not do anything. However I may add something in the future so I just leave it like that for now. It's like a format.
score: 0
comment on: http://stackoverflow.com/q/51022752

http://stackoverflow.com/comment/89053212
comment on: http://stackoverflow.com/q/51027796
score: 1
has text: @DavidCharles your comment led me in the correct direction. If you want to post an answer that the brackets in this line of code will fix it, I will mark it as the answer.... file_list.append([value])
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51145190
tagged with: types
answer count: 1
accepted answer: http://stackoverflow.com/a/51146055
tagged with: python
tagged with: tostring
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51146055
tagged with: hana
has body: I have a list of IDs (IDList) that are a subset of a list of tupels, containing these IDs and related IDs in String-Format. There can be tupels with one related ID, e.g. (1694, '1743'), two related IDs seperated by comma e.g. (3252, '3253,3254') or no related ID ('none'). I would like to write all IDs from the tupels that are related to the IDs in IDList into one common list (final_list). Therefore the elements containing two IDs should be split by comma and those containing "none" should be dropped. This is how my code looks right now: IDList = [1694, 3252, 2779] related = [(1694, '1743'), (3252, '3253,3254'), (3253, '3252,3254'), (3254, '3252,3253'), (1743, '1694'), (2779, 'none'), (3251, 'none'), (1677, 'none'), (1676, 'none'), (1678, '1679'), (1679, '1678')] final_list = [] related_frame = pd.DataFrame(related) print(related_frame) for n in l: dset = related_frame.loc[related_frame[0] == n] print (dset) rel_set = dset[1] rel_set = str(rel_set) if "," in rel_set: rel_set = rel_set.split(',') print(rel_set) if "none" in rel_set: rel_set = [] final_list.append(rel_set) print(final_list) In dataframe-format it still looks as expected: print(related_frame) out: 0 1 0 1694 1743 1 3252 3253,3254 2 3253 3252,3254 3 3254 3252,3253 4 1743 1694 5 2779 none 6 3251 none 7 1677 none 8 1676 none 9 1678 1679 10 1679 1678 However, once I start working with the related values only, Python for some reason adds information about the type to the values. So the final_list looks like this: print(final_list) [['0 1743\nName: 1', ' dtype: object'], ['1 3253', '3254\nName: 1', ' dtype: object']] I would like to have it this way: print(final_list) [1743, 3253, 3254] Does anyone know how to access the values from the objects in the tupels without the \nName and dtype-information etc.? So I just would like to read the plain value. The data in the related-list is obtained from a varchar-column in SAP HANA-Database, so these are not very exceptional objects by any means. I know I could remove…
type: Question
tagged with: type-conversion
has title: Accessing the value of an object from a tuple without context information
score: 0

http://stackoverflow.com/comment/89245548
type: AnswerComment
score: 0
type: Comment
has text: `settext` or `setText`?
comment on: http://stackoverflow.com/a/51130393

http://stackoverflow.com/q/51025224
type: Question
has comment: http://stackoverflow.com/comment/89042892
has comment: http://stackoverflow.com/comment/89042941
has comment: http://stackoverflow.com/comment/89043460
downvote count: 0
has comment: http://stackoverflow.com/comment/89045477
favorite count: 0
tagged with: python-3.x
has body: New to Python, and I find this bit rather confusing. I have a config file that is read into a kwarg. with values like: students||student a|student b|student c I see this populating properly into the kwarg when I debug, however, when I attempt to read the values, it will always only pull the first letter. for student in kwargs.get('students'): --student will come thru as 's' this seems to be something specific to my machine, as this code is running in prod. I set my libraries the same as the server, but still having the issue. Anyone know why this might be occurring? I am running on Python 3.6.5 Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89043506
tagged with: python
has comment: http://stackoverflow.com/comment/89042907
answer count: 0
score: 1
upvote count: 1
has title: kwargs.get only pulls first letter
has comment: http://stackoverflow.com/comment/89042945

http://stackoverflow.com/a/51146244
type: Answer
has comment: http://stackoverflow.com/comment/134051774
has body: Well, I could fix it by setting the host at server side to 0.0.0.0 inside docker and removing-rebuilding the image. All works fine.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51146082

http://stackoverflow.com/comment/89255674
score: 0
type: Comment
type: QuestionComment
has text: `c = fsolve(cubic, cGuess, full_output=True)` returns an output with solution `[3.776248 , 2.61501774]` and the message is `'The solution converged.'`. SciPy 1.1.0, Python 3.6.
comment on: http://stackoverflow.com/q/51040853

http://stackoverflow.com/comment/89084474
comment on: http://stackoverflow.com/q/51046480
has text: @JozefCechovsky it *is* installed, or he won't get the `import email` statement to work.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51067409
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
tagged with: api
has answer: http://stackoverflow.com/a/51067553
has title: How to find out the parameters in an API using Python
has answer: http://stackoverflow.com/a/51068116
upvote count: 1
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
tagged with: parameters
has body: Below is the code I have: response = requests.get('https://website.com', headers= {'Authorization': 'key'}) The response I get is 200. So obviously that is good. I am trying to pull data and format them into data frames afterwards. How do I move forward after this line of code? I don't know what parameters (I think that is the term) to put after because the vendor is very unresponsive and just gave me this link and key. Is there a way to call for a list of the parameters?

http://stackoverflow.com/q/51132108
tagged with: pandas
has comment: http://stackoverflow.com/comment/89249105
linked to: http://stackoverflow.com/q/13509207
has answer: http://stackoverflow.com/a/51132399
favorite count: 0
has comment: http://stackoverflow.com/comment/89248973
tagged with: python
tagged with: excel
type: AnsweredQuestion
has title: Creating an excel table in python
upvote count: 5
accepted answer: http://stackoverflow.com/a/51132399
has comment: http://stackoverflow.com/comment/89248909
type: Question
score: 5
has comment: http://stackoverflow.com/comment/89248848
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89249068
has comment: http://stackoverflow.com/comment/89248967
has comment: http://stackoverflow.com/comment/89248959
has body: I have exported data to excel using pandas dataframes and my next plan is to use the data I've exported with PowerApps. However, in order to do this the data needs to be formatted as an excel table and I was wondering if there's a way to automate this? I've had a good look around and am struggling to find anything - please bear in mind I am in no way a python pro and am very new to pandas! Here's a condensed version of what I've got so far: import pandas as pd list = [['big', 'nested', 'list'],['big', 'nested', 'list'], ['big', 'nested', 'list'],['big', 'nested', 'list'],['big', 'nested', 'list']] df = pd.DataFrame(data = list, columns = ['X','Y','Z']) writer = pd.ExcelWriter('file.xlsx', engine='xlsxwriter') df.to_excel(writer, index = False) writer.save() Ideally I'd like to do this in python rather than try and merge what I've done with VBA (which would seem like the more obvious choice I'm guessing) as I've no experience whatsoever in VBA nor would know how to link the code to signal the other.. However I'm happy to hear all suggestions! Thank you very much in advance EDIT: What i'm wondering is if there's a way to turn this: Current output into this Ideal Output

http://stackoverflow.com/comment/89145371
comment on: http://stackoverflow.com/q/51066894
has text: Here's some test data: `df = pd.DataFrame( [['A', 'START', 3], ['A', 'STOP', 6], ['B', 'STOP', 2], ['C', 'STOP', 1], ['C', 'START', 9], ['C', 'STOP', 7]], columns=['column_A', 'column_B', 'time'] )`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89117920
has text: I think I have worked out some of the bugs. Tell me is the polygons being created meant to always link to the last polygon?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51063462
type: QuestionComment

http://stackoverflow.com/a/51101534
type: Answer
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: You can use np.where to make your rich and poor categories, then groupby that category and get the sum: df['country_cat'] = np.where(df.GDP &lt; 9, 'poor', 'rich') df.groupby('country_cat')['score'].sum() country_cat poor 5 rich 13 You can also do the same in one step, by not creating the extra column for the category (but IMO the code becomes less readable): df.groupby(np.where(df.GDP &lt; 9, 'poor', 'rich'))['score'].sum()
accepted answer of: http://stackoverflow.com/q/51101470
answers question: http://stackoverflow.com/q/51101470

http://stackoverflow.com/q/51036086
has comment: http://stackoverflow.com/comment/89064399
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89065725
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89064147
favorite count: 0
has answer: http://stackoverflow.com/a/51036220
has title: Python text parser for C++ program?
tagged with: windows
tagged with: python
accepted answer: http://stackoverflow.com/a/51036220
has body: Anyone that has tried text parsing in C++ compared to Python will notice a considerable difference in effort and difficulty with Python being the easier of the two quite normally. For this reason I would much rather write a text parsing function in Python that my program written in C++ can use. I thought of compiling a .py file into a .dll but this doesn't seem possible according to the Googling I've done. I can compile a .py file into an .exe file then pass the text to be parsed as a command line argument. However, I would rather not spawn multiple processes each time I need to parse text. I was wondering if there were anyway possible to use a Python function in a C++ program or some other means someone can think of. I just want to avoid using C++ to parse text. Thanks for your time.
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89064297
upvote count: 3

http://stackoverflow.com/comment/89260676
score: 1
has text: hmmm, for me your code and similar working `df1.insert(0, 'per', df['per'].values.reshape(-1,8)[:, [0]])`
comment on: http://stackoverflow.com/a/51130504
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51089334
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51089448
upvote count: 13
score: 12
answer count: 3
downvote count: 1
tagged with: keras
favorite count: 0
has body: What is the difference between tf.keras.layers versus tf.layers? E.g. both of them have Conv2d, do they provide different outputs? Is there any benefits if you mix them (something like a tf.keras.layers.Conv2d in one hidden layer and in the next, tf.layers.max_pooling2d)?
has title: What is the difference between tf.keras.layers versus tf.layers?
possible better answer: http://stackoverflow.com/a/51089448
has answer: http://stackoverflow.com/a/54718798
accepted answer: http://stackoverflow.com/a/54718798
tagged with: python
has comment: http://stackoverflow.com/comment/96223209
has answer: http://stackoverflow.com/a/51089993
type: AnsweredQuestion

http://stackoverflow.com/comment/89243327
comment on: http://stackoverflow.com/a/51126907
type: Comment
has text: I had tried both `setAutoDefault` and `setDefault` before but it was inside the page classes!! `setDefault` works perfectly in the `Wizard` class.!
score: 0
type: AnswerComment

database
tags question: http://stackoverflow.com/q/51030253
tags question: http://stackoverflow.com/q/51133829
tags question: http://stackoverflow.com/q/51130636
tags question: http://stackoverflow.com/q/51159566
tags question: http://stackoverflow.com/q/51087573
type: Tag
tags question: http://stackoverflow.com/q/51164239
tags question: http://stackoverflow.com/q/51055956
tags question: http://stackoverflow.com/q/51048071
tags question: http://stackoverflow.com/q/51048477
tags question: http://stackoverflow.com/q/51044013
tag name: database
tags question: http://stackoverflow.com/q/51136916
tags question: http://stackoverflow.com/q/51126769
tags question: http://stackoverflow.com/q/51096704
tags question: http://stackoverflow.com/q/51148396
tags question: http://stackoverflow.com/q/51074933
tags question: http://stackoverflow.com/q/51075047
tags question: http://stackoverflow.com/q/51089141
tags question: http://stackoverflow.com/q/51061907
tags question: http://stackoverflow.com/q/51143498
tags question: http://stackoverflow.com/q/51157380
tags question: http://stackoverflow.com/q/51031839
tags question: http://stackoverflow.com/q/51085754
tags question: http://stackoverflow.com/q/51142906
tags question: http://stackoverflow.com/q/51085037
tags question: http://stackoverflow.com/q/51107699
tags question: http://stackoverflow.com/q/51128396
tags question: http://stackoverflow.com/q/51080695
tags question: http://stackoverflow.com/q/51145801

http://stackoverflow.com/comment/89101741
has text: In a Python session, this code works for a list such as `nums=list(range(1,10))`. If there are problems using `np.prod`, use one of the answers in: [Product function of elements in a list](https://stackoverflow.com/questions/40385336/product-function-of-elements-in-a-list)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51055277
type: QuestionComment

http://stackoverflow.com/q/51080005
type: Question
has body: I'm following the example I found on the main page of GitHub relative to googlemaps and I'm writing my own code in order to retrieve all cinemas from a specific area. The code is this: import googlemaps gmaps = googlemaps.Client(key='MyGoogleKey') search_loction = gmaps.location('40.714224, -73.961452').type('movie_theater') print (search_loction) It returns me the error: Traceback (most recent call last): File "GoogleMap.py", line 5, in &lt;module&gt; search_loction = gmaps.location('40.714224, -73.961452') AttributeError: 'Client' object has no attribute 'location' If I follow the guide, yes, the attribute [location] is allowed So what am I doing wrong?
has comment: http://stackoverflow.com/comment/89170400
has title: Google Places API: how to search by type and location in Python
accepted answer: http://stackoverflow.com/a/51134165
score: 5
tagged with: google-maps
answer count: 1
has comment: http://stackoverflow.com/comment/89153814
favorite count: 0
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89251077
tagged with: google-places-api
has answer: http://stackoverflow.com/a/51134165
downvote count: 1

http://stackoverflow.com/comment/89369898
type: Comment
has text: thanks for the help but its just returning me one peak... is there any way of returning all the peaks?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51031581

http://stackoverflow.com/comment/89315538
type: QuestionComment
has text: `return replace` => `return replace(word)` or you're returning the function itself. In that case inner function isn't really useful.
score: 0
comment on: http://stackoverflow.com/q/51166020
type: Comment

http://stackoverflow.com/a/51097186
has body: melt + merge You can melt your "pivoted" dataframe, then left merge with your master dataframe. Assumes the year columns in your first dataframe are integers. melted = pd.melt(df1.reset_index(), id_vars='index') res = df2.merge(melted, left_on=['city', 'year'], right_on=['index', 'variable'], how='left') print(res'city', 'year', 'other', 'value') city year other value 0 cityA 2016 aa 23 1 cityB 2017 bb 28 2 cityA 2016 cc 23 3 cityB 2017 dd 28
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51096736

http://stackoverflow.com/a/51091027
answers question: http://stackoverflow.com/q/51090288
score: 1
downvote count: 0
type: Answer
has body: Alright, I solved it myself, so here is what I did. It's pretty simple and I feel stupid for not figuring it out earlier. Let me know if anyone else has a better solution. I created a row that counts the total stops: df['stop_count'] = df.groupby('id')['id'].transform('count') - 1 Then I checked to see if the sequence number matches the stop_count: last_mask = df['sequence'] == df['stop_count']
upvote count: 1

http://stackoverflow.com/a/51146589
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51146054
has comment: http://stackoverflow.com/comment/89278392
type: AcceptedAnswer
downvote count: 0
has body: An array and its attributes: In [28]: arr = np.arange(1,8) In [29]: arr.__array_interface__ Out[29]: {'data': (41034176, False), 'strides': None, 'descr': [('', '&lt;i8')], 'typestr': '&lt;i8', 'shape': (7,), 'version': 3} The data buffer location for a slice: In [30]: arr[4:].__array_interface__['data'][0] Out[30]: 41034208 In [31]: arr[4:].__array_interface__['data'][0]-arr.__array_interface__['data'][0] Out[31]: 32 The slice shares the data buffer, but with an offset of 4 elements (4*8). Using this information I can fetch a slice using the ndarray constructor (not usually needed): In [35]: np.ndarray((3,), dtype=int, buffer=arr.data, offset=32) Out[35]: array([5, 6, 7]) In [36]: arr[4:7] Out[36]: array([5, 6, 7]) arr.data is a memoryview object that somehow references the data buffer of this array. The id/address of arr.data is not the same as the data pointer I used above. In [38]: arr.data Out[38]: &lt;memory at 0x7f996d950e88&gt; In [39]: type(arr.data) Out[39]: memoryview Note that data location for arr[4] is totally different. It is 'unboxed', not a slice: In [37]: arr[4].__array_interface__ Out[37]: {'data': (38269024, False), 'strides': None, 'descr': [('', '&lt;i8')], 'typestr': '&lt;i8', 'shape': (), 'version': 3, '__ref': array(5)}
answers question: http://stackoverflow.com/q/51146054

http://stackoverflow.com/q/51129938
type: Question
has comment: http://stackoverflow.com/comment/89244653
has comment: http://stackoverflow.com/comment/89245041
upvote count: 1
answer count: 1
has title: Python program,assign_add, the result might be a little confusing
has comment: http://stackoverflow.com/comment/89244916
has body: b= tf.ones([3,3],dtype=tf.float32) c= tf.Variable(tf.random_normal([3,3],mean=1,stddev=2,dtype=tf.float32),name="c") d=tf.assign_add(c,b) init_op= tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) x,y,z= sess.run([c,b,d]) print(x,"\n!!\n",y,"\n!!\n",z,"\n!!") print(sess.run(d)) the third array output result should be added 'b' and 'c', but the result did not print as expected. Can you help me? Many thanks. I expect the third Array output result should be the same as the fourth Array. I am confused at the third Array result.
favorite count: 0
has answer: http://stackoverflow.com/a/51130379
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89245402
downvote count: 0
tagged with: tensor
score: 1
tagged with: tensorflow

http://stackoverflow.com/comment/89213781
type: Comment
comment on: http://stackoverflow.com/a/51087238
has text: Yes, so the problem is, usually, that not all DOM elements have been loaded. It's the same issue that you have in your original answer and why you are sometimes seeing the tweets and sometimes you do not. In that case you cannot use `requests.get()`, instead you need to use `Selenium` package and `wait` for the page to load, check this out: http://allselenium.info/wait-for-elements-python-selenium-webdriver/ @aviss
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89181877
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51079470
has text: Have you tried to get to the url yet and make some test?
score: 0

http://stackoverflow.com/q/51150427
score: -2
downvote count: 2
answer count: 1
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51151076
has title: Python, position initialisation (using list) full explanation
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51151076
type: Question
has body: I am trying to make a snake game and I want to start the starting position of the snake head. I bumped into this code (class constructor): self.poslist = [(headposx,y) for y in reversed(range(headposy-self.length+1,headposy+1))] I want help on what this code means and what it does for me to change it to suit my already existing code.
tagged with: python

http://stackoverflow.com/q/51127860
accepted answer: http://stackoverflow.com/a/51127990
tagged with: discord.py
has title: Why is message not defined in my Command?
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/51127990
type: Question
tagged with: python
tagged with: discord
tagged with: bots
score: 0
upvote count: 1
has body: So, I have made a help command with my discord bot and it looks much more neat when I send it as an embed message. However, it does take up a lot of space, so I was wondering if I could send it as a DM to the message.author. Here's what I have so far: import discord from discord.ext.commands import Bot from discord.ext import commands Client = discord.Client() bot_prefix = "." bot = commands.Bot(command_prefix=bot_prefix) @bot.event async def on_ready(): print("Bot Online!") print("Name: {}".format(bot.user.name)) print("ID: {}".format(bot.user.id)) bot.remove_command("help") # .help @bot.command(pass_context=True) async def help(ctx): embed=discord.Embed(title="Commands", description="Here are the commands:", color=0xFFFF00) embed.add_field(name="Command1", value="What it does", inline= True) embed.add_field(name="Command2", value="What it does", inline= True) await bot.send_message(message.author, embed=embed) bot.run("TOKEN") However after running the command you get the error "NameError: name 'message' not defined." This error message still shows up even if I replace the message.author part with message.channel. The only way I can get the message to send at all is when I replace the bot.send_message with await bot.say(embed=embed). Is there a way around this?
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/89046943
type: QuestionComment
comment on: http://stackoverflow.com/q/51027150
type: Comment
has text: how about concatenating the string before you pass it to the `input`? like `input("You now have"+str(strength)+"strength and"+str(health)+"health")`
score: 0

http://stackoverflow.com/comment/89162859
comment on: http://stackoverflow.com/q/51087150
score: 0
type: Comment
type: QuestionComment
has text: @sgerodes "I want my program start at startup without manually copying its shortcut to startup folder"

http://stackoverflow.com/comment/89227279
comment on: http://stackoverflow.com/q/51115249
has text: I'm not sure why that isn't working, but my advice would be to use the public `Meta` API rather than mucking around with `_meta`. Specifically, set `Meta.db_table` (from `attrs`) before calling `ModelBase.__new__()`. That will make you far less dependent on the internal details of Django's metaclass and migrations implementations.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51030312
has body: To further expand, the source code will tell you the truth. assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset First it checks queryset is defined Second it checks if the queryset specified is an instance of Django's Queryset class Third it re-evaluates (makes a database query) the queryset and sets the results Fourth it returns the results The warning about using self.queryset directly is that results are cached when evaluated so further references to this value will not be up to date as opposed of using self.get_queryset().
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51029653
answers question: http://stackoverflow.com/q/51029653
type: Answer

http://stackoverflow.com/q/51044013
type: UnansweredQuestion
tagged with: azure
tagged with: python
has answer: http://stackoverflow.com/a/51044134
has body: I'm new to Azure Databricks so I am having a hard time importing JSON data and converting it to CSV using Azure Databricks even after reading the documentation. After converting JSON to CSV, I need to combine it with another CSV data that has a mutual column. Any help would be really appreciated. Thank you
tagged with: databricks
type: Question
has title: Convert JSON to CSV using Azure Databricks
tagged with: database
score: -1
downvote count: 2
tagged with: apache-spark
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51061080
has comment: http://stackoverflow.com/comment/124593287
has body: I think like that: /usr/bin/python3 %path%
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51053609

http://stackoverflow.com/comment/89110792
has text: You were right, the closing tag was missing. I adjusted the Problem.
comment on: http://stackoverflow.com/q/51060126
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51136890
has comment: http://stackoverflow.com/comment/89258105
has title: Choose Items from a List in multithreaded python
has comment: http://stackoverflow.com/comment/89258099
has comment: http://stackoverflow.com/comment/89259446
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89258144
has comment: http://stackoverflow.com/comment/89258068
has body: I am a beginner in python and cant figure out how to do this: I am running a python script that puts a new value every 5-10 seconds into a list. I want to choose these elements from the list in another multithreaded python script however per thread one value, so one value shouldnt be reused, if theres no next value, then wait until next value is present. I have some code where I tried to do it but with no success: Script that creates values: values = ['a','b','c','d','e','f'] cap = [] while True: cap.append(random.choice(values)) print cap time.sleep(5) Script that needs these values: def adding(self): p = cap.pop() print (p) However in a multithreaded environment, each thread gives me the same value, even thought I want value for each thread to be different (e.g remove value already used by thread) What are my options here?
has comment: http://stackoverflow.com/comment/89258319
has comment: http://stackoverflow.com/comment/89257966
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89262182
has comment: http://stackoverflow.com/comment/89257868
favorite count: 0
accepted answer: http://stackoverflow.com/a/51250768
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/51250768
type: AnsweredQuestion

http://stackoverflow.com/a/51016703
type: Answer
accepted answer of: http://stackoverflow.com/q/51016600
answers question: http://stackoverflow.com/q/51016600
has comment: http://stackoverflow.com/comment/89025920
score: 5
upvote count: 5
has body: To install from GitHub with pip you can: pip3 install git+url example: pip3 install git+https://github.com/ing-bank/sparse_dot_topn.git
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51052346
has comment: http://stackoverflow.com/comment/89097299
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39379556
tagged with: list-comprehension
tagged with: numpy
has comment: http://stackoverflow.com/comment/89097261
accepted answer: http://stackoverflow.com/a/51052347
has title: Numba giving error for NumPy
answer count: 1
score: 0
has body: After watching a SciPy talk on Numba, my understanding is that if it is done with NumPy tools, it can be done with Numba (with a good chance of speeding it up). However, as I experiment with Numba-fying some code, it looks like the simple JIT (1) has no trouble with list comprehension, but (2) can't make head or tail of numpy.asarray(). When I run import numba @numba.jit def squareTest(xlist): y = [x**2 for x in xlist] return y it runs fine. But when I run import numba import numpy as np @numba.jit def squareTest(xlist): y = [x**2 for x in xlist] y1 = np.asarray(y) return y1 the IPython console gives me a long traceback, says there was a Lowering Error, and ends with def squareTest(xlist): y = [x**2 for x in xlist]` ^ I don't know the structure of the Numba module, but the very last part tells me that when it's going to turn the produced list into a NumPy array afterward, it then has trouble doing list comprehensions. I checked @numba.jit def squareTest(xlist): y = list(range(20)) y1 = np.asarray(y) return y1 and it ran with no trouble, so it looks like it can handle either list comprehension or np.asarray(), but not both. My first guess was that the njit mode can handle everything NumPy, and the mode that is turned off by adding the n to the jit is what handles list comprehension. But no, the first code sample still works when it is changed to njit. What is the problem here, and how can I Numba-fy functions that involve doing NumPy array operations to arrays that are most pythonically made with list comprehensions?
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51052347
tagged with: numba
has comment: http://stackoverflow.com/comment/89133819

http://stackoverflow.com/a/74437492
answers question: http://stackoverflow.com/q/51036394
score: 0
has body: The problem is in pymysql. I connenct by pyodbc and all problems disappeared
type: Answer

http://stackoverflow.com/comment/89317194
comment on: http://stackoverflow.com/a/51151994
type: Comment
has text: This link should help you in loading a JSON file and reading it as a string, and then you can go about with my solution.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89022636
score: 0
type: AnswerComment
has text: Works fine now! Did this, worked this time: `Macbook:~ rose$ cd rose/tensorflow Macbook:tensorflow rose$ source ./bin/activate` and got `(tensorflow) Macbook:tensorflow rose$` as my prompt, which was supposed to happen
type: Comment
comment on: http://stackoverflow.com/a/51014754

http://stackoverflow.com/comment/89042353
type: QuestionComment
has text: How would you define a *valid torrent file?*
comment on: http://stackoverflow.com/q/51024950
score: 3
type: Comment

http://stackoverflow.com/comment/89200531
comment on: http://stackoverflow.com/a/51104705
has text: Why was this downvoted? Downvoting should stop being anonymous and have a report on the downvote.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89214583
type: QuestionComment
score: 1
has text: are you mixing python 2 and 3? Your stack trace mentions python2.7, while your use of `print()` implies python3
type: Comment
comment on: http://stackoverflow.com/q/51113885

http://stackoverflow.com/q/51012032
score: 2
has comment: http://stackoverflow.com/comment/89017840
downvote count: 0
type: UnansweredQuestion
has body: I'm using Ubuntu 16.04 and I'm trying to learn Django and I installed it in my virtual environment and named it myenv, and I started a project named mysite. When I tried to run the manage.py file, it kept saying sqlite3 is not installed. I did install it, but it is saying the same error. When I run python3 manage.py migrate, it says: "ModuleNotFoundError: No module named '_sqlite3'" I installed sqlite using the commands below: sudo add-apt-repository ppa:jonathonf/backports sudo apt-get upgrade sudo apt-get install sqlite3
has comment: http://stackoverflow.com/comment/89046807
has comment: http://stackoverflow.com/comment/89018206
type: Question
linked to: http://stackoverflow.com/q/43993890
has answer: http://stackoverflow.com/a/51012574
tagged with: sqlite
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89048656
upvote count: 2
answer count: 3
tagged with: django
has comment: http://stackoverflow.com/comment/89016861
tagged with: python
has comment: http://stackoverflow.com/comment/89048616
has comment: http://stackoverflow.com/comment/89017836
has title: "No module named '_sqlite3'" when running Django's "python3 manage.py migrate"
tagged with: ubuntu-16.04
has answer: http://stackoverflow.com/a/59220321
has comment: http://stackoverflow.com/comment/89048625
has answer: http://stackoverflow.com/a/57792405

http://stackoverflow.com/q/51013561
tagged with: powerset
has comment: http://stackoverflow.com/comment/89019883
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51013597
has comment: http://stackoverflow.com/comment/89019955
tagged with: algorithm
has title: Expansion of list comprehension leading to infinite loop in listing power sets
has comment: http://stackoverflow.com/comment/89020013
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/89020104
type: AnsweredQuestion
has body: I have been trying to solve the problem of listing power sets on Question 78 on Leetcode. I ran into a solution that uses list comprehensions and it works. I tried expanding it and following through with the Python documentation to make sure I get the correct syntax but I seem to be getting into an infinite loop. Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] The code in the solution is: def subsets(nums): nums.sort() result = [[]] for num in nums: result += [i + [num] for i in result] return result The code with my change is: def subsets(nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [[]] for num in nums: for list_ in result: result.append([num] + list_) return result I think that in each iteration of the for list_ in result: loop, the result is getting bigger and so I wouldn't get to the end of it but why is it not the same case with the list comprehension? What am I missing?
accepted answer: http://stackoverflow.com/a/51013597
type: Question
tagged with: python

http://stackoverflow.com/comment/89287763
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51152043
has text: Possible duplicate of [Simplest way to plot 3d surface given 3d points](https://stackoverflow.com/questions/12423601/simplest-way-to-plot-3d-surface-given-3d-points)
score: 0

http://stackoverflow.com/q/51135543
downvote count: 0
tagged with: python-3.6
has body: I have a use case where I need to bind a ttk progressbar until a video feed is being played. I have made a parent container which needs to hold a Videofeed, and a widget(progressbar). I am using the tk.Label.update() method for displaying my video in the container. Also, I have a flag, which counts the number of frames being displayed. I capped it to count until 60. This flag is also used to set the variable for the progressbar. My video is being displayed but the progressbar is not showing. Can anyone help me fix the problem ? ` import tkinter as tk from tkinter import ttk import time import cv2 from PIL import Image, ImageTk MAX = 60 root = tk.Tk() screen_width,screen_height = root.winfo_screenwidth(),root.winfo_screenheight() root.geometry('{}x{}'.format(screen_width, screen_height)) progress_var = tk.DoubleVar() #here you have ints but when calc. %'s usually floats ImageLabel = tk.Label(root, width=screen_width,height=screen_height,) ImageLabel.pack() progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX) progressbar.pack(fill=tk.X, expand=1) def loop_function(): k = 0 cap=cv2.VideoCapture("myvideo.avi") while k &lt;= MAX: val,frame=cap.read() if val: img = Image.fromarray(frame) imgtk = ImageTk.PhotoImage(image=img) ImageLabel.imgtk = imgtk ImageLabel.configure(image=imgtk) progress_var.set(k) k += 1 time.sleep(1) root.update() cap.release() #root.after(100, loop_function) loop_function() root.mainloop() `
favorite count: 0
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: opencv
score: 1
type: Question
has title: Updating a tkinter progressbar until a video is played

http://stackoverflow.com/comment/89167933
has text: I asked you a [mcve] because I test your example with a trivial test and it worked, so maybe the problem is caused by something that depends on the test, so I ask you to show me your example in particular, maybe I chose an easy test . ;)
score: 0
comment on: http://stackoverflow.com/q/51068778
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51146933
tagged with: arrays
has comment: http://stackoverflow.com/comment/89279096
score: -1
has answer: http://stackoverflow.com/a/51147917
has comment: http://stackoverflow.com/comment/89278716
has comment: http://stackoverflow.com/comment/89278984
has comment: http://stackoverflow.com/comment/89278189
has body: I'm very new to machine learning, and so using a Pokemon dataset, I decided to write a test program to predict a "catch rate" based on the "total" data. I wanted to use linear regression for my training data. But when I run my program, I get the following error: Expected 2D array, got 1D array instead: array=['190' '90' '45' '125' '190' '75' '45' '120' '200' '45' '190' '60' '225' '90' '3' '45' '150' '120' '45' '3' '3' '255' '90' '45' '45' '45' '255' '225' '190' '190' '255' '90' '45' '45' '30' '45' '45' '90' '190' '90' '45' '90' '60' '45' '60' '75' '55' '75' '45' '45' '3' '255' '45' '3' '45' '90' '190' '60' '190' '200' '225' '75' '45' '45' '45' '200' '120' '120' '255' '60' '45' '45' '75' '60' '60' '190' '75' '45' '120' '190' '200' '235' '45' '45' '90' '30' '45' '45' '170' '235' '45' '190' '60' '75' '180' '45' '235' '190' '45' '120' '45' '75' '190' '45' '45' '45' '45' '45' '75' '45' '45' '190' '45' '75' '3' '45' '60' '200' '45' '45' '255' '255' '120' '45' '255' '125' '120' '60' '45' '45' '60' '255' '45' '180' '60' '45' '60' '3' '25' '120' '45' '3' '3' '45' '75' '30' '45' '255' '30' '75' '255' '255' '180' '255' '45' '45' '120' '255' '75' '30' '45' '75' '45' '255' '120' '45' '45' '45' '190' '45' '75' '45' '45' '3' '60' '30' '60' '200' '45' '75' '120' '25' '255' '45' '255' '200' '190' '190' '120' '45' '90' '170' '45' '75' '60' '100' '45' '45' '90' '45' '45' '45' '255' '60' '90' '140' '45' '90' '75' '200' '45' '45' '255' '120' '3' '45' '75' '200' '255' '225' '120' '120' '200' '45' '45' '50' '190' '45' '45' '45' '45' '45' '45' '30' '3' '3' '255' '45' '45' '255' '120' '225' '45' '75' '75' '45' '60' '255' '60' '60' '45' '120' '255' '45' '225' '255' '45' '45' '3' '255' '190' '30' '190' '45' '45' '120' '75' '25' '75' '255' '45' '120' '100' '3' '65' '45' '75' '180' '45' '45' '3' '255' '45' '45' '90' '225' '190' '45' '255' '3' '190' '70' '3' '120' '45' '45' '50' '200' '190' '255' '55' '150' '45' '3' '25' '60' '45' '120' '45' '205' '60' '45' '45' '255' '30' '120' '75' '45' '90' '…
upvote count: 1
has comment: http://stackoverflow.com/comment/89277931
answer count: 1
has comment: http://stackoverflow.com/comment/89278604
has comment: http://stackoverflow.com/comment/89278111
favorite count: 0
tagged with: prediction
has comment: http://stackoverflow.com/comment/89279116
has title: Machine learning and linear regression - Expected 2D array, reshape data
has comment: http://stackoverflow.com/comment/89278072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89279351
has comment: http://stackoverflow.com/comment/89279016
tagged with: python
has comment: http://stackoverflow.com/comment/89278894
has comment: http://stackoverflow.com/comment/89277906
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/89277989
downvote count: 2
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89278460
type: Question
has comment: http://stackoverflow.com/comment/89279679
has comment: http://stackoverflow.com/comment/89278667

performance
tags question: http://stackoverflow.com/q/51122457
tags question: http://stackoverflow.com/q/51100817
tags question: http://stackoverflow.com/q/51013935
tags question: http://stackoverflow.com/q/51129600
tags question: http://stackoverflow.com/q/51022411
tags question: http://stackoverflow.com/q/51092178
tags question: http://stackoverflow.com/q/51097719
tags question: http://stackoverflow.com/q/51143508
tags question: http://stackoverflow.com/q/51077547
tags question: http://stackoverflow.com/q/51086219
tags question: http://stackoverflow.com/q/51077418
tags question: http://stackoverflow.com/q/51067724
tags question: http://stackoverflow.com/q/51025882
tags question: http://stackoverflow.com/q/51034507
tags question: http://stackoverflow.com/q/51142844
tags question: http://stackoverflow.com/q/51130317
tags question: http://stackoverflow.com/q/51119459
tags question: http://stackoverflow.com/q/51150059
tags question: http://stackoverflow.com/q/51134686
tags question: http://stackoverflow.com/q/51141814
tags question: http://stackoverflow.com/q/51155624
tags question: http://stackoverflow.com/q/51026191
tags question: http://stackoverflow.com/q/51075519
tags question: http://stackoverflow.com/q/51152402
tags question: http://stackoverflow.com/q/51013023
tag name: performance
tags question: http://stackoverflow.com/q/51092428
tags question: http://stackoverflow.com/q/51063947
type: Tag
tags question: http://stackoverflow.com/q/51131257
tags question: http://stackoverflow.com/q/51066894

http://stackoverflow.com/a/51136640
has body: A similar question has been answered here, Here's something from the docs. Warning As mentioned above, if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread), then that process will not terminate until all buffered items have been flushed to the pipe. This means that if you try joining that process you may get a deadlock unless you are sure that all items which have been put on the queue have been consumed. Similarly, if the child process is non-daemonic then the parent process may hang on exit when it tries to join all its non-daemonic children. Note that a queue created using a manager does not have this issue. With the queue created with multiprocessing.Manager, this issues is resolved. import time from multiprocessing import Process,JoinableQueue,Queue,Value import multiprocessing def create_row( q_row,y_val): #creating lines. len:720 len of each line_len=720 for i in range(line_len): q_row.put(1) def create_col(q_col,x_val): #creating cols col_len=1280 line_len=720 for i in range(col_len): l = list() for j in range(line_len): l.append(1) q_col.put(l) def main(): #creating row and col Queue manager = multiprocessing.Manager() q_row=manager.JoinableQueue() q_col=manager.JoinableQueue() x_val=Value('i',-1) y_val=Value('i',-1) p1=Process(target=create_row,args=(q_row,y_val)) p2=Process(target=create_col,args=(q_col,x_val)) q_row.join() q_col.join() p1.start() p2.start() p1.join() p2.join() main()
answers question: http://stackoverflow.com/q/51135131
score: 0
type: Answer

http://stackoverflow.com/a/51141352
score: 10
answers question: http://stackoverflow.com/q/51141325
downvote count: 0
type: Answer
has body: If you want any output from the code, then you need to use print, as return only returns the value to the caller. print(jump()) In python shell, however, you can see the returning value of a function without printing. &gt;&gt;&gt; from random import randint &gt;&gt;&gt; &gt;&gt;&gt; def jump(): ... return randint(1, 6) ... &gt;&gt;&gt; jump() 5 &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/89267769
upvote count: 10

http://stackoverflow.com/comment/89165945
has text: What does `sublime.find_resources("AddToFile.sublime-settings")` return?
comment on: http://stackoverflow.com/q/51088271
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57711918
upvote count: 2
has body: I had the same problem. You have to have to set the following in your app.run() debug=True use_reloader=False otherwise it won't work. Attaching is not yet supported, so click on "launch debugger" and there you can set the module you want to execute and the python path (useful if working with virtual environments) and your current working directory. To toggle breakpoints: click F9 in the line To watch variables: either type them out in the console or look at the scope in the sidebar. Hope this helps.
accepted answer of: http://stackoverflow.com/q/51031002
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51031002
type: Answer
score: 2

http://stackoverflow.com/comment/89171128
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51091250
has text: What is the returned value from `os.system()`?

http://stackoverflow.com/comment/89236389
score: 0
type: Comment
type: QuestionComment
has text: I found a funnier one - `(((226553150*1023473145)/5)//10 * 10) % 10`
comment on: http://stackoverflow.com/q/51125676

http://stackoverflow.com/q/51157661
possible better answer: http://stackoverflow.com/a/51157819
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51157819
has answer: http://stackoverflow.com/a/51157753
upvote count: 3
has body: I want to iterate through every .png file in a folder and print every text contained in the Images. The first iteration works fine but the second gives an Error. Code: import pytesseract from PIL import Image import os directory = (r'C:\folder...') for filename in os.listdir(directory): if filename.endswith('.png'): Image = Image.open(filename) im = pytesseract.image_to_string(Image) print(im) Output: Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in Image = Image.open(filename) AttributeError: 'PngImageFile' object has no attribute 'open' What does it mean 'PngImageFile' object has no attribute 'open'? Doesn't Image = Image.open(filename) does exactly that? Thanks in advance Edit: The initial PngError is solved but now another Error with PIL library occured: import pytesseract from PIL import Image import os directory = (r'C:\folder...') for filename in os.listdir(directory): if filename.endswith('.png'): img = Image.open(filename) im = pytesseract.image_to_string(img) print(im) Output: (ocr of 'frame_0000.png' is correct and then) Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in &lt;module&gt; img = Image.open(filename) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'frame_0001.png' Edit2: This is very strange. When I do this: for filename in os.listdir(r'folderpath...'): print(filename) it works perfectly fine, iterating through every file, printing every filename. But when I do this: for filename in os.listdir(r'folderpath...'): print(filename) print(pytesseract.image_to_string(Image.open(filename))) an Error is given: Bewegung_UHF_Plots.m Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 19, in &lt;module&gt; print(pytesseract.image_to_string(Image.open(filename))) File "C:\…
type: Question
has comment: http://stackoverflow.com/comment/114557790
downvote count: 0
has title: OCR every .png file in a folder
accepted answer: http://stackoverflow.com/a/51157753
has comment: http://stackoverflow.com/comment/89340548
answer count: 3
tagged with: ocr
has answer: http://stackoverflow.com/a/78896002
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51183112
type: Answer
has comment: http://stackoverflow.com/comment/89430744
has comment: http://stackoverflow.com/comment/89431117
has comment: http://stackoverflow.com/comment/89430694
score: 1
has comment: http://stackoverflow.com/comment/89431209
upvote count: 1
has comment: http://stackoverflow.com/comment/89431096
has comment: http://stackoverflow.com/comment/89431029
has comment: http://stackoverflow.com/comment/89430998
has comment: http://stackoverflow.com/comment/89430907
accepted answer of: http://stackoverflow.com/q/51088835
has comment: http://stackoverflow.com/comment/89430836
answers question: http://stackoverflow.com/q/51088835
has comment: http://stackoverflow.com/comment/89380411
has comment: http://stackoverflow.com/comment/89430877
type: AcceptedAnswer
downvote count: 0
has body: I've once again git clone'd your Django project's repository and got it working, without having to rework your project's structure, by doing the following: 1. Rework your settings.BASE_DIR variable Typically, the file path to a Django project's settings file is projectname/settings.py but for separated settings it's projectname/settings/&lt;env_name&gt;.py. Therefore, BASE_DIR needs to be reworked from: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) to: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) to account for the extra directory between your project root and your settings file. 2. Change app declaration in INSTALLED_APPS: Your app's dotted location from BASE_DIR is apps.base. Replace the current declaration, base, with apps.base. 3. Fix dotted paths: If any errors arise from dotted paths, check the traceback as it will point to the issue. For example, your current urls.py will likely cause an issue because there is a dotted path to base.urls whereas it should be the explicit apps.base.urls. For instance: urlpatterns = [ url(r'', include('base.urls')), ... ] To the following: urlpatterns = [ url(r'', include('apps.base.urls')), ... ] 4. Migrate models Perform ./manage.py makemigrations &amp;&amp; ./manage.py migrate. Also, as a side-note, migrations directories shouldn't be in .gitignore. Read: Should I be adding the Django migration files in the .gitignore file? And with that I was able to run the below script, at the root of the Django project, without error: import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DzenanElvir.settings.base") django.setup() from apps.base.models import ModelRazred
has comment: http://stackoverflow.com/comment/89359985

http://stackoverflow.com/q/51167072
upvote count: 0
has body: In Python, it's usually neat to write [f(i) for i in range(n)]. I wonder if there is a way to do something like [A.append(f(i)) for i in range(n)] or [A.insert(g(i),f(i)) for i in range(n)].
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89317277
score: -1
has title: Functional way of inserting elements into a list
has answer: http://stackoverflow.com/a/51167645
tagged with: functional-programming
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89317478
tagged with: python
has comment: http://stackoverflow.com/comment/89318231
tagged with: coding-style

http://stackoverflow.com/comment/89262284
score: 1
comment on: http://stackoverflow.com/q/51139011
has text: It would be helpful if you offered an example in code of what you have tried as well as an example of your large text files, string, and expected output. Please see https://stackoverflow.com/help/mcve for creating a Minimal, Complete, and Verifiable example.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51037832
has comment: http://stackoverflow.com/comment/89068029
score: 5
has comment: http://stackoverflow.com/comment/89067305
has comment: http://stackoverflow.com/comment/89067358
has comment: http://stackoverflow.com/comment/89068726
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51037079
has comment: http://stackoverflow.com/comment/89067596
upvote count: 5
answers question: http://stackoverflow.com/q/51037079
has comment: http://stackoverflow.com/comment/89070679
type: Answer
has comment: http://stackoverflow.com/comment/89070152
has comment: http://stackoverflow.com/comment/89070650
has body: You can specify a scoring parameter inside the GridSearchCV object like this using make_scorer from sklearn.metrics import precision_score, make_scorer prec_metric = make_scorer(precision_score) grid_search = GridSearchCV(estimator = logreg, scoring= prec_metric param_grid = param_grid, cv = 3, n_jobs=-1, verbose=3) Once you have fitted your data, you can use results_ attribute to access the scores like this results = grid_search.results_ { 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.8, 0.7, 0.8, 0.9], 'split1_test_score' : [0.82, 0.5, 0.7, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.82], 'std_test_score' : [0.02, 0.01, 0.03, 0.03], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.8, 0.9, 0.7], 'split1_train_score' : [0.82, 0.5, 0.7], 'mean_train_score' : [0.81, 0.7, 0.7], 'std_train_score' : [0.03, 0.03, 0.04], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.007, 0.06, 0.04, 0.04], 'std_score_time' : [0.001, 0.002, 0.003, 0.005], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], } You can also use multiple metrics for evaluation as mentioned in this example. You can make your own custom metric or use one of the metrics specified here. Update : Based on this answer, you should then feed the classfier from grid_search before fitting on the whole data to cross_val_score, to prevent any data leakage.
downvote count: 0

http://stackoverflow.com/q/51098897
has comment: http://stackoverflow.com/comment/89198688
tagged with: kivy
tagged with: http://stackoverflow.com/tag/svg
type: UnansweredQuestion
tagged with: python
has body: Suppose I drew several geometric shapes in kivy (see example below). How can I convert them to a single svg file? from kivy.base import runTouchApp from kivy.lang import Builder KV = ''' BoxLayout canvas: Color rgba: 1,0,0,1 Rectangle size: 100,100 pos: 100,100 Ellipse size: 100,100 pos: 300,100 Triangle points: 500, 100, 500, 200, 600, 100 ''' runTouchApp(Builder.load_string(KV))
has comment: http://stackoverflow.com/comment/89186019
answer count: 0
type: Question
tagged with: canvas
has title: How to convert Kivy canvas to SVG?
score: 0

twitter
tags question: http://stackoverflow.com/q/51106363
tags question: http://stackoverflow.com/q/51164802
tags question: http://stackoverflow.com/q/51129384
type: Tag
tags question: http://stackoverflow.com/q/51069093
tags question: http://stackoverflow.com/q/51114638
tag name: twitter
tags question: http://stackoverflow.com/q/51106928

http://stackoverflow.com/comment/89301465
type: Comment
type: QuestionComment
score: 0
has text: Did you read my answer to [this question](https://stackoverflow.com/questions/42994338/creating-figure-with-exact-size-and-no-padding-and-legend-outside-the-axes)? It seems to me this is exactly what you want.
comment on: http://stackoverflow.com/q/51158405

http://stackoverflow.com/q/51036103
has answer: http://stackoverflow.com/a/51036200
answer count: 1
has title: Collection.loadTable: not found in GEE
favorite count: 0
score: 4
type: UnansweredQuestion
tagged with: python
tagged with: google-earth-engine
has body: When I tried to upload my .shp file in Google Earth Engine Asset and import in Python like this: self.TS_POP = ee.FeatureCollection(users/arafayknysys/pop_TS) And when I tried to load the Geometric Data using self.TS_POP.getInfo(), I get the following error: Collection.loadTable: (*) not found Any help much appreciated
type: Question
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89210082
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51110281
has text: As opposed to `repr`? That works too... Just needs to be immutable to be hashable
score: 0

http://stackoverflow.com/a/51082881
answers question: http://stackoverflow.com/q/51066721
upvote count: 1
has body: Also, is there a way in Kubernetes to catch/find/watch all events of the same job (i.e. deployed under one manifest file) at a time? The short answer is no. All pod events, in any case, go one after another. There is one opportunity that comes into my mind: Because the pods that require custom scheduler can't be scheduled by any other scheduler, your custom scheduler can collect a list of pods related to the same job and schedule them one after another, then go to the list related to the next job. This way you can ensure that resources intended to be used by pods of the first job will not be allocated for one of the pods related to another job before all pods related to the first job is scheduled to nodes. There are annotations and labels in the event the scheduler receives. I didn't check results of the list_namespaces_pod or list_namespaces_event, but I think annotations and labels should be there also. It is possible to set the configuration of the job in the annotations, like number of pods in the job or labels for each pod in the job (e.g.: labels:{job_ID:100,role:master,uid:xxx}, annotations:{[job_ID:none, master:none, worker1:none worker2:none]}). When scheduler sees the first pod with the annotations for a job that he doesn't have yet, he creates a new list of pods for the job ([job_ID:100, master:xxx, worker1:none worker2:none]). When next events appear, scheduler fills this list using pod labels and schedules only lists that are filled up completely ([job_ID:100, master:uid1, worker1:uid2: worker2:uid3]).
has comment: http://stackoverflow.com/comment/89157066
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89310772
has text: @SIM yeah I added `.strip()` also, but I like your style more. Thanks!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51163669
score: 0

http://stackoverflow.com/q/51144702
has answer: http://stackoverflow.com/a/51146914
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51145458
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Taking *ANY csv column format into Django form
score: 0
has body: My code is currently hard coded to only accept csv files in the column format: first_name,last_name,phone,email,address,company However I would like users to be able to upload csv files that are in any* format order and naming scheme and correctly populate our forms. For example: Email,LastName,FirstName,Company,Phone,Address would be a valid column format. How would I go about doing that? Relevant code as follows: dr = csv.reader(open(tmp_file,'r')) data_dict = {} headers = next(dr) print (headers) #skips over first line in csv iterlines = iter(dr) next(iterlines) for row in iterlines: data_dict["first_name"] = row[0] #print(data_dict["first_name"]) data_dict["last_name"] = row[1] #print(data_dict["last_name"]) data_dict["phone"] = row[2] #print(data_dict["phone"]) data_dict["email"] = row[3] #print(data_dict["email"]) data_dict["address"] = row[4] #print(data_dict["address"]) data_dict["company"] = row[5] #print(data_dict["company"]) #adds to form try: form = AddContactForm(data_dict) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user.username first_name = form.cleaned_data.get(data_dict["first_name"]) last_name = form.cleaned_data.get(data_dict["last_name"]) phone = form.cleaned_data.get(data_dict["phone"]) email = form.cleaned_data.get(data_dict["email"]) address = form.cleaned_data.get(data_dict["address"]) company = form.cleaned_data.get(data_dict["company"]) obj.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass
type: Question
answer count: 2

http://stackoverflow.com/q/51111591
upvote count: 2
tagged with: pydev
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89210305
has comment: http://stackoverflow.com/comment/89210197
tagged with: python
has comment: http://stackoverflow.com/comment/89210320
has comment: http://stackoverflow.com/comment/89210389
has comment: http://stackoverflow.com/comment/89210317
has answer: http://stackoverflow.com/a/51138294
score: 2
accepted answer: http://stackoverflow.com/a/51138294
has title: "ModuleNotFoundError: No module named x" : Pydev configuration correct?
has comment: http://stackoverflow.com/comment/89210180
tagged with: installation
downvote count: 0
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89210192
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89210298
has comment: http://stackoverflow.com/comment/89210154
has body: Really struggling with Eclipse Pydev, first time trying it out. Trying to run shell command in python django, however I'm getting the following error: ModuleNotFoundError: No module named 'rango' I checked Project > Properties > PyDev - Django to see settings module and both fields saying: "settings / manage module not found... Here is the screen: https://i.sstatic.net/006pG.jpg Here is the stack trace: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "F:\CAB302\java-latest-released\eclipse\plugins\org.python.pydev.core_6.4.1.201806231219\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'rango' Is the Python Path correct? Also I am not sure what a python path represent? (please explain). For reference Python path screen capture: https://i.sstatic.net/Is9Xc.jpg What would be the correct path for the error in the photo one? I assume its why I am getting the ModuleNotFoundError? Please help!
tagged with: eclipse

http://stackoverflow.com/comment/89742526
type: Comment
has text: You've solved the problem for me too so thank you! Do you know of any way to get updated when there is an official wheel on pypi?
type: AnswerComment
comment on: http://stackoverflow.com/a/51118443
score: 0

http://stackoverflow.com/a/51128776
answers question: http://stackoverflow.com/q/51127473
has body: Inherit BaseSerializer from Serializer class instead of from ModelSerializer. Hence the BaseSerializer will be like class BaseSerializer(serializers.Serializer, object): pass The problem with ModelSerializer is, it expect a Meta class with atleast two fields which are fields and model
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89438806
upvote count: 2
has comment: http://stackoverflow.com/comment/96255361
type: Answer
accepted answer of: http://stackoverflow.com/q/51127473
score: 2

http://stackoverflow.com/comment/89160963
comment on: http://stackoverflow.com/q/51085307
score: 0
has text: Also, there are **lots** of typos in your code: `ser.writ`, `ser.weite`. At least check for spelling error before you post
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51035176
accepted answer of: http://stackoverflow.com/q/51034637
type: Answer
answers question: http://stackoverflow.com/q/51034637
score: 3
downvote count: 0
has body: You are not quoting the timestamp, hence the error. Rather than trying to quote the values manually, use the built-in quoting functionality provided by pymysql as part of the DBI interface. sql = 'INSERT INTO `emp.log` (`log_level`, `log_levelname`, `log`, `created_at`, `created_by`) VALUES (%s, %s, %s, %s, %s)' self.cursor.execute(sql, (levelnum, levelname, msg, createtime, record.name))
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/51021929
answer count: 2
tagged with: yaml
has body: Here below is my yaml file filename: #Name of the JMX files which needs to be executed - URLLogin.txt - URLupload.txt - XlsxFileUpload.txt URLLogin: - this is to test the script XlsxFileUpload: - this is to test the current script I will be storing the filenames in an array. and call a method to get the file description in a loop. If the description is present for the filename it should return 1, else it should return zero Here below is my code for searching the description. #this method is to search a particular string in yaml def searchStringInYaml(filename,string): with open(filename, 'r') as stream: content = yaml.load(stream) if string in content: print string return 1 else: return 0 stream.close()
has title: How to search a particular string and content in a yaml file
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89036392
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89036374
downvote count: 0
accepted answer: http://stackoverflow.com/a/51022089
has comment: http://stackoverflow.com/comment/89036508
has comment: http://stackoverflow.com/comment/89036364
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/51022406
has answer: http://stackoverflow.com/a/51022089
has answer: http://stackoverflow.com/a/51022406
has comment: http://stackoverflow.com/comment/89036311
tagged with: python-2.7
upvote count: 3

http://stackoverflow.com/q/51146120
upvote count: 13
linked to: http://stackoverflow.com/q/14647723
tagged with: django
score: 13
tagged with: jinja2
type: Question
type: AnsweredQuestion
tagged with: forms
downvote count: 0
answer count: 1
has body: I have refrenced this stackoverflow page and tried to display my forms error on the html template. I did: {% if form.error %} {% for field in form %} {% for error in field.errors %} &lt;div class="alert alert-danger"&gt; &lt;strong&gt;&lt;/strong&gt; &lt;/div&gt; {% endfor %} {% endfor %} {% for error in form.non_field_errors %} &lt;div class="alert alert-danger"&gt; &lt;strong&gt;&lt;/strong&gt; &lt;/div&gt; {% endfor %} {% endif %} as said in the stackoverflow question I also tried simply doing: {% if form.error %} This should pop up if there is an error {% endif %} Nothing comes up regardless: Heres my view.py code: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password2') user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('/') else: print(form.errors) form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) I am able to get the form errors onto the django console but it refuses to show up on the template. Printing form.errors prints to the console: &lt;li&gt;password2&lt;ul class="errorlist"&gt;&lt;li&gt;The two password fields didn&amp;#39;t match.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;
favorite count: 0
has title: Django form.errors not showing up in template
tagged with: python
has answer: http://stackoverflow.com/a/51146198
accepted answer: http://stackoverflow.com/a/51146198

http://stackoverflow.com/comment/89160529
has text: @JakeJ sorry, I fixed it!
comment on: http://stackoverflow.com/q/51081337
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51105738
has title: What does append(self) mean in Python classes?
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/51105797
score: 3
tagged with: class
has body: I am new to OOP in Python and working on inheritance concept. I came across the following code: class ContactList(list): def search(self, name): '''Return all contacts that contain the search value in their name.''' matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contact: all_contacts = ContactList() def __init__(self, name, email): self.name = name self.email = email self.all_contacts.append(self) I'm wondering why do we use self.all_contacts.append(self) and how does for contact in self work ?. If I understood correctly, self appoints to the instance of a class (object), and appending to a list is not trivial to me.
upvote count: 3
answer count: 3
favorite count: 0
tagged with: self
tagged with: python
possible better answer: http://stackoverflow.com/a/51105784
has answer: http://stackoverflow.com/a/51105786
accepted answer: http://stackoverflow.com/a/51105786
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51105784
downvote count: 0

http://stackoverflow.com/q/51034973
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51035032
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I'm working in a virtual env using Django 1.8 and Python 2.7. I installed REST framework and created a new project and just finished editing the snippets/models.py file by following the tutorial. When I go to create an initial migration of the snippet model using the command: python manage.py makemigrations snippets I get the error: ImportError: No module named apps My setting.py file INSTALLED_APPS is as follows: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'snippets.apps.SnippetsConfig', ) What am I doing wrong?
type: Question
possible better answer: http://stackoverflow.com/a/51035044
has answer: http://stackoverflow.com/a/57241499
has answer: http://stackoverflow.com/a/51035044
has title: ImportError in Django REST Framework Tutorial 1: Serialization
has answer: http://stackoverflow.com/a/51035032
answer count: 3
has comment: http://stackoverflow.com/comment/89062005
downvote count: 0
tagged with: django-rest-framework
favorite count: 0

http://stackoverflow.com/comment/89149603
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51079771
has text: see edit. Sorry, that was unnecessary complicated :)

pyarrow
tags question: http://stackoverflow.com/q/51084514
tag name: pyarrow
tags question: http://stackoverflow.com/q/51047019
type: Tag

http://stackoverflow.com/a/51023678
answers question: http://stackoverflow.com/q/51023435
score: 2
has comment: http://stackoverflow.com/comment/89039893
has comment: http://stackoverflow.com/comment/89039867
has body: Given df, as word Index 0 easy 1 to 2 get 3 to 4 know 5 to 6 easy 7 of 8 to First, use reset_index to move the dataframe index into a column named 'Index': df = df.reset_index() Next using the following groupby with agg: df.groupby('word')['Index'].agg([list,'count']).reset_index() Output: word list count 0 easy [0, 6] 2 1 get [2] 1 2 know [4] 1 3 of [7] 1 4 to [1, 3, 5, 8] 4
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/51147258
score: 4
type: Answer
has body: It's usually fine to put a comment like that above the line: # google link url full_path = "https://www.google.cz/search?q=" + website_keywords By the way, as of this writing, PEP 8 says that the line limit for comments is only 72. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters. ... Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters. It's not clear if that applies to inline comments, since they're not "long blocks of text", but PEP 8 also says, Inline comments are unnecessary and in fact distracting if they state the obvious. You might consider removing that comment altogether. The fact that it's a Google URL is kind of obvious considering that the string contains "google" in it. There is one case where the comment really does have to be on the same line as what it's commenting about--PEP-484 type comments. In that case, you use parentheses: full_path = ( "https://www.google.cz/search?q=" + website_keywords ) # type: str
accepted answer of: http://stackoverflow.com/q/51147228
upvote count: 4
answers question: http://stackoverflow.com/q/51147228
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89027396
comment on: http://stackoverflow.com/q/51017203
type: QuestionComment
type: Comment
score: 1
has text: The `(0,)` does not have the same number of dimensions as the others.

http://stackoverflow.com/comment/89231732
type: Comment
type: QuestionComment
has text: Is there a particular reason you can't use `df.drop_duplicates`? https://stackoverflow.com/questions/23667369/drop-all-duplicate-rows-in-python-pandas
comment on: http://stackoverflow.com/q/51123275
score: 0

http://stackoverflow.com/a/51203350
accepted answer of: http://stackoverflow.com/q/51145554
has body: I put together a solution for anyone else looking for a similar workflow. It utilizes a python script in the root directory and handles the git commands via subprocess. It also supports autocomplete for the file directory (based on this gist). This script assumes you've already initialized the git repo and setup your remote repo as well. #!/usr/bin/env python import pytest import subprocess import readline import glob class tabCompleter(object): """ A tab completer that can complete filepaths from the filesystem. Partially taken from: http://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input """ def pathCompleter(self,text,state): """ This is the tab completer for systems paths. Only tested on *nix systems """ return [x for x in glob.glob(text+'*')][state] if __name__=="__main__": # Take user input for commit message commit_msg = raw_input('Enter the commit message: ') t = tabCompleter() readline.set_completer_delims('\t') # Necessary for MacOS, Linux uses tab: complete syntax if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") #Use the new pathCompleter readline.set_completer(t.pathCompleter) #Take user input for exercise file for submission ans = raw_input("Select the file to submit to Exercism: ") if pytest.main([]) == 0: """ If all tests pass: add files to index, commit locally, submit to exercism.io, then finally push to remote repo. """ subprocess.call(["git","add","."]) subprocess.call(["git","commit","-m", commit_msg]) subprocess.call(["exercism","submit",ans]) subprocess.call(["git","push","origin","master"])
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51145554
type: Answer

http://stackoverflow.com/comment/90745242
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51081732
has text: Thank you guys, and sorry for an incomplete code

http://stackoverflow.com/comment/124406559
type: AnswerComment
score: 0
type: Comment
has text: PEP656 has led to cibuildwheel now supporting Linux distros that use musl i.e. Alpine Linux, so that might be different now see https://discuss.python.org/t/pep-656-platform-tag-for-linux-distributions-using-musl/7165/40 and https://cibuildwheel.readthedocs.io/en/stable/changelog/#v220
comment on: http://stackoverflow.com/a/51171447

http://stackoverflow.com/a/51160874
downvote count: 0
has comment: http://stackoverflow.com/comment/89307110
has comment: http://stackoverflow.com/comment/89750449
has comment: http://stackoverflow.com/comment/89305653
has comment: http://stackoverflow.com/comment/89305401
upvote count: 2
has comment: http://stackoverflow.com/comment/89560610
has comment: http://stackoverflow.com/comment/89305458
has comment: http://stackoverflow.com/comment/89481152
accepted answer of: http://stackoverflow.com/q/51159585
has comment: http://stackoverflow.com/comment/89309707
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89715476
answers question: http://stackoverflow.com/q/51159585
has comment: http://stackoverflow.com/comment/89305423
has comment: http://stackoverflow.com/comment/89608502
has comment: http://stackoverflow.com/comment/89489334
has comment: http://stackoverflow.com/comment/89707060
type: Answer
has comment: http://stackoverflow.com/comment/89306083
has body: The table values seem to be embedded in a JSON string that can be gotten with json.loads. Then we can get the value by indicating a "regional" key of country's region. It's a bit more complicated but at least it gets the values that we put into a dataframe as follows: import requests from bs4 import BeautifulSoup import json import pandas as pd import os import numpy as np # force maximum dataframe column width pd.set_option('display.max_colwidth', 0) url = 'https://azure.microsoft.com/en-us/pricing/details/virtual-machines/windows/' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') tables = soup.find_all('div', {'class': 'row row-size3 column'}) region = 'us-west-2' # Adjust your region here def parse_table_as_dataframe(table): data = [] header = [] c5 = c6 = c7 = c8 = [] rows = [] columns = [] name = table.h3.text try: # This part gets the first word in each column header so the table # fits reasonably in the display, adjust to your preference header = [h.text.split()[0].strip() for h in table.thead.find_all('th')][1::] except AttributeError: return 'N/A' for row in table.tbody.find_all('tr'): for c in row.find_all('td')[1::]: if c.text.strip() not in (u'', u'$-') : if 'dash' in c.text.strip(): columns.append('-') # replace "&amp;dash; &amp;dash:" with a `-` else: columns.append(c.text.strip()) else: try: data_text = c.span['data-amount'] # data = json.loads(data_text)['regional']['asia-pacific-southeast'] data = json.loads(data_text)['regional'][region] columns.append(data) except (KeyError, TypeError): columns.append('N/A') num_rows = len(table.tbody.find_all('tr')) num_columns = len(header) # For debugging # print(len(columns), columns) # print(num_rows, num_columns) df = pd.DataFrame(np.array(columns).reshape(num_rows, num_columns), columns=header) return df for n, table in enumerate(tables): print(n, table.h3.text) print(parse_table_as_dataframe(table)) gets 24 dataframes, one for each table from the page: 0 B-series Instance …
has comment: http://stackoverflow.com/comment/89305472
has comment: http://stackoverflow.com/comment/89305833
score: 2

http://stackoverflow.com/a/51016312
has body: Try this: import pandas as pd file = open("your.csv", "r") data = pd.read_csv(file, sep = ",") gender = {'male': 1,'female': 0} data.Gender = [gender[item] for item in data.Gender] print(data) Or data.Gender[data.Gender == 'male'] = 1 data.Gender[data.Gender == 'female'] = 0 print(data)
type: Answer
upvote count: 15
score: 14
has comment: http://stackoverflow.com/comment/89025593
answers question: http://stackoverflow.com/q/51016230
has comment: http://stackoverflow.com/comment/89025468
accepted answer of: http://stackoverflow.com/q/51016230
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/a/51063413
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51061685
has comment: http://stackoverflow.com/comment/89141961
downvote count: 0
has body: You are indeed right to note that although the function signature takes as its first argument an input layer inp, it is not passed when the function is called. This trick is achieved with the function decorator @layer that is placed right before the function definition. Here is the definition of the layer decorator: def layer(op): """Decorator for composable network layers.""" def layer_decorated(self, *args, **kwargs): # Automatically set a name if not provided. name = kwargs.setdefault('name', self.get_unique_name(op.__name__)) # Figure out the layer inputs. if len(self.terminals) == 0: raise RuntimeError('No input variables found for layer %s.' % name) elif len(self.terminals) == 1: layer_input = self.terminals[0] else: layer_input = list(self.terminals) # Perform the operation and get the output. # [!] Here it passes the `inp` parameter, and all the other ones layer_output = op(self, layer_input, *args, **kwargs) # Add to layer LUT. self.layers[name] = layer_output # This output is now the input for the next layer. self.feed(layer_output) # Return self for chained calls. return self return layer_decorated It takes as input a function/method via the op parameter and it returns another one, layer_decorated which will replace the original definition of op. So PNet.conv = layer(Pnet.conv). If you look at the definition of layer_decorated, you see that it essentially sets up the first argument of the op function, namely layer_input (line with [!]). It also does some book-keeping to know which layer to use as input based on its name. To simplify things, this allows the programmer to use chained method calls without repeating themselves. It transforms this: x = self.feed('data') #pylint: disable=no-value-for-parameter, no-member x = self.conv(x, 3, 3, 10, 1, 1, padding='VALID', relu=False, name='conv1') x = self.prelu(x, name='PReLU1') x = self.max_pool(x, 2, 2, 2, 2, name='pool1') into this: x = (self.feed('data') #pylint: disable=no-value-for-parameter, no-member .co…

http://stackoverflow.com/comment/89252610
type: AnswerComment
score: 0
type: Comment
has text: @Mathieu, I edited the answer. Can you check if it is what you want?
comment on: http://stackoverflow.com/a/51133041

http://stackoverflow.com/q/51044761
has comment: http://stackoverflow.com/comment/89081189
tagged with: neural-network
has answer: http://stackoverflow.com/a/51045268
answer count: 2
downvote count: 0
score: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51046835
favorite count: 0
has title: Is there a way I can get the coefs_ attribute before fitting sklearn MLPRegressor?
type: UnansweredQuestion
tagged with: python
has body: I'm new in machine learning and I'm practicing to make a neural network that approximates functions. For just the purpose of learning and see the states of the neural network I'd like to know the initial coefficients of the neural network. Here is a reproducible example: import sklearn.neural_network as sknn import numpy as np LIMIT = 10.0 # Function I want to approximate def funcion(x): if x&lt;3: return 0 if x&gt;7: return 12 return 3*(x-3) X = np.array([]) Y = np.array([]) # Data training set for x in np.arange(0.0, LIMIT, 1.5): X = np.append(X, x) Y = np.append(Y, funcion(x)) X = np.append(X,10) Y = np.append(Y, funcion(10)) X = np.reshape(X, (-1,1)) nn = sknn.MLPRegressor( learning_rate_init=0.01, learning_rate = 'constant', activation='logistic', hidden_layer_sizes=(2,1), max_iter=1, random_state=None) print('coefficients: ', nn.coefs_) # THIS GIVES THE ERROR nn.fit(X, Y) Output: Traceback (most recent call last): File "aproxFun2.py", line 41, in &lt;module&gt; print('coefficients: ', nn.coefs_) AttributeError: 'MLPRegressor' object has no attribute 'coefs_' It prints the data whenever I call the nn.coefs_ after I call the nn.fit(X, Y) function, but I want to know the values before fitting.
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89081145

http://stackoverflow.com/comment/133841199
type: AnswerComment
comment on: http://stackoverflow.com/a/72108720
score: 0
type: Comment
has text: @ThomasDecaux well the treatment would have to be different since "foo=2" would be treated by the shell as a single string

http://stackoverflow.com/comment/89044165
type: Comment
has text: @EdwardMinnix I think he wanted to show an example using a lambda function, which might be more useful for the OP. Possibly not the best example here but anyway...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51025659

http://stackoverflow.com/comment/89082102
type: QuestionComment
comment on: http://stackoverflow.com/q/51045369
has text: Code I am using ---> with open('reactions.json') as data_file: data_reactions = json.load(data_file) [*data_reactions]
score: 0
type: Comment

http://stackoverflow.com/a/51162299
has body: The library code you are using says (in its description of a method): This method is usefull since any new command from python to robot make the robot stop https://github.com/SintefRaufossManufacturing/python-urx/blob/193577c0efed8a24d00bd12b3b6e0c7ffefb9dd9/urx/urrobot.py#L356-L357 So it may not be possible to have the robot move continuously by issuing a bunch of commands, since it stops every time it gets a new command. You need to figure out where the furthest place you want to move the robot to is, issue a command to move it there when the button is first pressed (with wait=False, so that your code doesn't sit around waiting for the robot to finish moving), and then use self.r.stop() to stop the robot whenever the button is released.
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51161843
answers question: http://stackoverflow.com/q/51161843
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51069581
type: AnsweredQuestion
has body: I am trying to take a string input in my python code to be converted and implemented into a URL to search the string on the website. The website I am using is songbpm.com and what I want is to search a song and I receive the speed of the song. Finding the relevant information within the HTML is not the problem, I have already finished this and my url creation is working, which is here: import urllib.request import urllib.parse song = input("") fin = "" for i in song: if i == "(": tempone = song song = tempone.split("(")[0] + tempone.split(") ")[1] previous = "" for i in song: if i.isalpha(): temp = fin fin = temp + i else: if previous.isalpha(): temp = fin fin = temp + "-" previous = i songencoded = urllib.parse.quote(song, safe='') print('https://songbpm.com/'+ fin.lower() + '?q=' + songencoded) response = urllib.request.urlopen('https://songbpm.com/'+ fin.lower() + '?q=' + songencoded) text = str(response.read()).split('\\n') The urls, which are returned are identical to the url when I manually enter the search input on the website, however, when I run this code, it always reads the html data for the no results redirect. Also, if I paste the computer-generated URL into the browser, it redirects to the no results page, however, after searching the same string by hand in the browser, the computer-generated url works as well (when retrying). What I have also observed is that after manually opening a certain URL, I can run the code with the same search query and it works - it seems as if searches are cached for a certain amount of time if a user, not a code opens it. How do I tackle this issue of the code, although generating the exact URL, not being able to open webpages similar to the user.
upvote count: 3
accepted answer: http://stackoverflow.com/a/51079675
downvote count: 1
has title: url not working over code but manual search works
has comment: http://stackoverflow.com/comment/89129128
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/51069775
answer count: 2
has comment: http://stackoverflow.com/comment/89132004
possible better answer: http://stackoverflow.com/a/51069775
has comment: http://stackoverflow.com/comment/89131972
has comment: http://stackoverflow.com/comment/89129055
has comment: http://stackoverflow.com/comment/89132067
has comment: http://stackoverflow.com/comment/89132525
has comment: http://stackoverflow.com/comment/89131753
score: 2
has comment: http://stackoverflow.com/comment/89132057
tagged with: url
has comment: http://stackoverflow.com/comment/89132190
has answer: http://stackoverflow.com/a/51079675
favorite count: 0
has comment: http://stackoverflow.com/comment/89131659
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89132337
tagged with: python
has comment: http://stackoverflow.com/comment/89129149

http://stackoverflow.com/q/51151078
upvote count: 1
accepted answer: http://stackoverflow.com/a/51151184
answer count: 1
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89285679
downvote count: 0
has body: I will need these columns:CAD_ADMIN,rank CAD_ADMIN rank 0507502 001 0507503 002 0507504 003 0507505 004 i made the rank column like this: dff['rank']= (dff.groupby('CAD_ADMIN').cumcount()+1).astype(str).str.zfill(3) The thing here is that i need to make a new column that will have: The first 5 numbers from CAD_ADMIN then the letters 'qw' and then the rest of the CAD_ADMIN (6 and 7 numbers in position and then the rank column for example: new_col 05075qw02001 #first line etc.. i tried some lambda functions but it was far from the wanted result.
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51151184
has title: Transfer numbers from other columns by position to a new column in Python?
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89285807

http://stackoverflow.com/comment/89133441
score: 1
comment on: http://stackoverflow.com/q/51071758
has text: Either way, try `df.loc[~(df < 0).any(1)]`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89691475
has text: Yes, I tried just now and still the problem persists - can't get pass the authentication page. I have updated the code with the exact same one I am using to test this problem - and yes, I am running the code from Europe.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51232885
type: Comment

http://stackoverflow.com/a/51151599
score: 1
type: Answer
has body: Use getattr with the 3rd default argument: products = [{'id': x.id, 'fabric': getattr(x.fabric, 'name', 'noname'), 'fabricimg': x.fabric.fabric_cover.url} for x in entry_obj.all()]
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51151510
answers question: http://stackoverflow.com/q/51151510
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51167776
accepted answer of: http://stackoverflow.com/q/51167248
has body: What you have to do is set a fixed width in the first item and the size_hint_x to None. GridLayout: cols:2 Image: width: 200 size_hint_x: None BoxLayout:
type: Answer
answers question: http://stackoverflow.com/q/51167248
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89121348
has text: Have you tried using a path where the `filename` argument is?
score: 0
comment on: http://stackoverflow.com/q/51065611
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51054061
has comment: http://stackoverflow.com/comment/89100114
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89099236
has body: Need Help on 502 Bad Gateway ngnix/1.10.3 I have configured my Django application using Nginx/Gunicorn. It was running fine until I made some changes to the code and reloaded the server. FYI: My settings.py has ALLOWED_HOSTS = ['*'] Error Logs : 2018/06/27 08:36:38 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:36:40 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:36:41 [crit] 7444#7444: *35 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" 2018/06/27 08:39:06 [crit] 7444#7444: *41 connect() to unix://home/ubuntu/www/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 106.51.16.0, server: 18.191.255.247, request: "GET /report/ HTTP/1.1", upstream: "http://unix://home/ubuntu/www/MySite/MySite.sock:/report/", host: "18.191.255.247" Update 1 : This is my nginx config. Is there any issue with this? /etc/nginx/sites-available/MySite server { listen 80; server_name 18.191.255.247; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/www/MySite; } location / { include proxy_params; proxy_pass http://unix://home/ubuntu/www/MySite/MySite.sock; } } How do i verify nginx daemon permission to the project folder (//un…
has answer: http://stackoverflow.com/a/51055791
score: 1
has comment: http://stackoverflow.com/comment/89100777
has answer: http://stackoverflow.com/a/58613303
type: Question
has title: Django - Gunicorn/Nginx - 502 Bad Gateway
tagged with: nginx
answer count: 2
has comment: http://stackoverflow.com/comment/89099991
downvote count: 0
tagged with: unix
favorite count: 0
tagged with: gunicorn
type: UnansweredQuestion

http://stackoverflow.com/comment/89037489
comment on: http://stackoverflow.com/q/51022336
has text: It all depends on your situation. There are lots of things that you could consider - is there always going to be a change in the signal, or is this intended to detect its presence too? Is the change always the same height? How much noise is too much? What do you expect it to do if there is a change, but the noise is so big that it's the same strength as the change in signal?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68575187
score: 6
type: Answer
has body: Install below packages and it will resolve the issue. apt-get install python3-dev default-libmysqlclient-dev build-essential
upvote count: 7
downvote count: 1
answers question: http://stackoverflow.com/q/51062920

http://stackoverflow.com/q/51039409
answer count: 3
tagged with: break
tagged with: python
has comment: http://stackoverflow.com/comment/89070157
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: loops
has comment: http://stackoverflow.com/comment/89080739
type: Question
has answer: http://stackoverflow.com/a/51039521
has answer: http://stackoverflow.com/a/51039453
has title: Break loop with variable - Python
possible better answer: http://stackoverflow.com/a/51039535
has answer: http://stackoverflow.com/a/51039535
has comment: http://stackoverflow.com/comment/89081406
downvote count: 0
has body: I'd like to write my loop in a more compact form. When I have code in this form, everything works fine: a=-1 while a &lt;0: user_move() if (nastede[1]==X) and (nastede[2]==X) and (nastede[3]==X): print("Game Over") break print("END") But when I try to use the code in this form, my loop does not break: y=(nastede[1] and nastede[2] and nastede[3]) a=-1 while a &lt;0: user_move() if y == X: print("Game Over") break print("END") Why does my loop in the second situation not break with nastede[] inside y ? After changes (All Code): nastede=[" ", " ", " ", " ", " ", " ", " ", " ", " "] X="X" def list_global(): global nastede print(" ",nastede[0],"| ",nastede[1]," | ",nastede[2]," ") print("---------------") print(" ",nastede[3],"| ",nastede[4]," | ",nastede[5]," ") print("---------------") print(" ",nastede[6],"| ",nastede[7]," | ",nastede[8]," ") def user_move(): a=-1 while a&lt;0: move_hum=int(input("Write a number from 1 to 8 ?\n")) if (nastede[move_hum] != X) and (nastede[move_hum] != O): nastede[move_hum] = "X" list_global() break else: print("Write different number") a=-1 while a &lt;0: user_move() if all(map(lambda x: x == X, nastede)): print("Game Over") break print("END")
has comment: http://stackoverflow.com/comment/89070319
accepted answer: http://stackoverflow.com/a/51039453
favorite count: 0
has comment: http://stackoverflow.com/comment/89081200
tagged with: tuples

facebook-prophet
tags question: http://stackoverflow.com/q/51063282
type: Tag
tag name: facebook-prophet

http://stackoverflow.com/a/51063769
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51060126
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51060126
has body: We had 2 problems in this case: initially the @f$ closing tag iof the formula was missing (corrected in the question) the formula contained @sum but the content of the formula has the contain LaTeX commands and not doxygen commands and thus the @sum should be \sum.

http://stackoverflow.com/a/51135977
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51135849
has body: Use "with" tag if you want to create any variable in django template. check this answer How to set a value of a variable inside a template code?
type: Answer
has comment: http://stackoverflow.com/comment/89256624

http://stackoverflow.com/a/51013521
answers question: http://stackoverflow.com/q/51013319
accepted answer of: http://stackoverflow.com/q/51013319
has body: You can use random.gauss to generate 6 numbers around a mean with a certain standard deviation (closeness) and as per @PatrickArtner suggestion construct the 7th one, e.g. using 3 standard devs from mean: In []: import random vals = [int(random.gauss(341/7, 3)) for _ in range(6)] vals.append(341 - sum(vals)) vals, sum(vals), sum(vals)/7 Out[]: ([47, 47, 48, 48, 54, 50, 47], 341, 48.714285714285715)
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51046093
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51039393
has comment: http://stackoverflow.com/comment/89125695
type: Answer
answers question: http://stackoverflow.com/q/51039393
has body: If you use the OpenSSL library in Python, you have get_peer_cert_chain that you can apply on your connection object, it will give you a list of certificates as sent by the server, so the end certificate with all intermediates one if needed. See https://pyopenssl.org/en/stable/api/ssl.html#connection-objects : get_peer_cert_chain() Retrieve the other side’s certificate (if any) Returns: A list of X509 instances giving the peer’s certificate chain, or None if it does not have one. Here is one crude example (without any error handling): from OpenSSL import SSL import socket dst = ('www.google.com', 443) ctx = SSL.Context(SSL.SSLv23_METHOD) s = socket.create_connection(dst) s = SSL.Connection(ctx, s) s.set_connect_state() s.set_tlsext_host_name(dst[0]) s.sendall('HEAD / HTTP/1.0\n\n') s.recv(16) certs = s.get_peer_cert_chain() for pos, cert in enumerate(certs): print "Certificate #" + str(pos) for component in cert.get_subject().get_components(): print "Subject %s: %s" % (component) print "notBefore:" + cert.get_notBefore() print "notAfter:" + cert.get_notAfter() print "version:" + str(cert.get_version()) print "sigAlg:" + cert.get_signature_algorithm() print "digest:" + cert.digest('sha256') which gives: Certificate #0 Subject C: US Subject ST: California Subject L: Mountain View Subject O: Google LLC Subject CN: www.google.com notBefore:20180612133452Z notAfter:20180821121300Z version:2 sigAlg:sha256WithRSAEncryption digest:06:C5:12:EB:3C:B1:7F:AB:18:E0:D5:22:E4:25:12:A7:30:AA:27:16:0B:3A:99:CB:3D:11:CF:12:EF:95:2E:41 Certificate #1 Subject C: US Subject O: Google Trust Services Subject CN: Google Internet Authority G3 notBefore:20170615000042Z notAfter:20211215000042Z version:2 sigAlg:sha256WithRSAEncryption digest:BE:0C:CD:54:D4:CE:CD:A1:BD:5E:5D:9E:CC:85:A0:4C:2C:1F:93:A5:22:0D:77:FD:E8:8F:E9:AD:08:1F:64:1B So you have the full detailed content of the certificate, see https://pyopenssl.org/en/stable/api/crypto.html#x509-objects for available info. Then you have to_…
has comment: http://stackoverflow.com/comment/89107760

http://stackoverflow.com/q/51164815
tagged with: python-requests
has body: class DmozSpider(Spider): global requests name = "drugtrials" dt = import_config() allowed_domains = ['chinadrugtrials.org.cn'] start_urls = [ 'http://www.chinadrugtrials.org.cn/eap/clinicaltrials.searchlist' ] def parse(self, response): print 'drugtrials start time :', datetime.datetime.now() f = open('/var/www/html/cde/drugtrials.txt', 'a+') f.write("drugtrials start time" + str(datetime.datetime.now()) + '\n') f.close() dt = import_config() notneedwords_str = dt['not_need_words'] NOTNEEDWORDS = notneedwords_str.split('，') print "NOTNEEDWORDS:", NOTNEEDWORDS db = cx_Oracle.connect(ORACLE_USER, ORACLE_PASSWD, ORACLE_DSN) cursor = db.cursor() sql = """SELECT "id","name","company" FROM "cde" where "sfda_status"&gt;=8""" # **There are 116589 data sets here.** cursor.execute(sql) result = cursor.fetchall() length = len(result) requests = [] zhPattern = re.compile(u'[\u4e00-\u9fa5]+') for i in range(0, length): namearr = result[i][1].split(" ") companyarr = result[i][2].split(" ") arr = namearr + companyarr for m in arr: if not len(m) == 1 and m not in NOTNEEDWORDS: if m in namearr: # 药物别名查询 cursor.execute( """SELECT "cde_usedname","cde_usedname2","cde_usedname3","cde_usedname4","cde_usedname5" from "cde_usedname" where "cde_name"=:cde_name """, {'cde_name': m}) all_bieming1 = cursor.fetchone() all_bieming = [] if all_bieming1: for iva in all_bieming1: if iva is not None: all_bieming.append(iva) print all_bieming all_drug_name = ' '.join(all_bieming) m2 = m + ' ' + all_drug_name else: m2 = m request = FormRequest(dt['drug_url'], formdata={ 'drugs_name': m2 }, dont_filter=True, callback=self.parse_page, meta={'code': result[i][0], 'keyword': m2, 'keyword_type': 'drugs_name'} ) requests.append(request) else: match = zhPattern.search(unicode(m)) if match: request = FormRequest(dt['drug_url'], formdata={ 'appliers': m }, dont_filter=True, callback=self.parse_page, meta={'code': result[i][0], 'keyword': m, 'keyword_type': 'appliers'} ) requests.append(request) else: print'没中…
answer count: 0
tagged with: scrapy
linked to: http://stackoverflow.com/q/48844802
type: Question
has title: The call to callback function failed in yield request in Scrapy
has comment: http://stackoverflow.com/comment/89312910
score: 0
has comment: http://stackoverflow.com/comment/91340622
has comment: http://stackoverflow.com/comment/91331258
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89269104
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51142349
has text: Why would you expect a multi-line string to run correctly when you run a single line? I haven't tried it, but that doesn't sound reasonable.

http://stackoverflow.com/q/51039698
tagged with: python
has title: Copy values from one column to another using Pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51039853
has answer: http://stackoverflow.com/a/51039776
upvote count: 7
linked to: http://stackoverflow.com/q/30357276
type: Question
has answer: http://stackoverflow.com/a/51040234
possible better answer: http://stackoverflow.com/a/51039776
has comment: http://stackoverflow.com/comment/89075094
has body: I have a DataFrame with two columns X and Y: X Y 0 0 111.0 1 3 NaN 2 1 NaN 3 1 112.0 4 2 113.0 5 2 NaN 6 3 114.0 7 3 115.0 8 1 NaN 9 2 116.0 I want to copy in Y only the values of X that correspond to the rows where a NaN is. The expected result should look like this X Y 0 0 111 1 3 3 2 1 1 3 1 112 4 2 113 5 2 2 6 3 114 7 3 115 8 1 1 9 2 116 Is there any way to achieve this?
downvote count: 0
duplicate of: http://stackoverflow.com/q/30357276
accepted answer: http://stackoverflow.com/a/51039853
has answer: http://stackoverflow.com/a/51039824
tagged with: pandas
score: 7
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/89070693

http://stackoverflow.com/q/51161771
has answer: http://stackoverflow.com/a/51162114
tagged with: git-bash
downvote count: 1
score: -1
has title: How do I convert Python 2 code to python 3 code in GitBash?
type: Question
has comment: http://stackoverflow.com/comment/89312607
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89308522
favorite count: 0
has body: I have a file written in Python 2 and I want to convert the code to Python 3, while saving a file of both. How do you do this using Git Bash?
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/89243106
score: 0
type: QuestionComment
has text: Many previous posts should have the info you need. Here's one: https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel/1663826#1663826
comment on: http://stackoverflow.com/q/51129152
type: Comment

http://stackoverflow.com/a/51012133
score: 4
answers question: http://stackoverflow.com/q/51012084
type: Answer
upvote count: 4
downvote count: 0
has body: In [73]: np.maximum(0,np.array([0,3,8,0])-np.array([1,1,1,1])) Out[73]: array([0, 2, 7, 0]) This doesn't explicitly address If either array has 0 for the given index, then the index is left unchanged. but the results match for all examples: In [74]: np.maximum(0,np.array([1,1,1,1])-np.array([0,3,8,0])) Out[74]: array([1, 0, 0, 1]) In [75]: np.maximum(0,np.array([10,10,10,10])-np.array([8,12,8,12])) Out[75]: array([2, 0, 2, 0])

ec2-ami
tag name: ec2-ami
tags question: http://stackoverflow.com/q/51021038
type: Tag

http://stackoverflow.com/comment/89174986
has text: without knowing the full traceback it's hard to say, but one thing is for sure, the Meta class attribute on the StudentsTable model should inherit the Meta class of UsersTable: `class Meta(UsersTable.Meta)`, more here: https://stackoverflow.com/questions/41409233/inheriting-meta-class-in-django-models
score: 0
comment on: http://stackoverflow.com/q/51093387
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89270851
type: QuestionComment
has text: Yes, It finds the html content. But when I use `decompose()` to remove that particular html from soup, it gives error.
comment on: http://stackoverflow.com/q/51143201
score: 0
type: Comment

http://stackoverflow.com/q/51105061
has title: filter out item from ordered dict
has body: For the following ordered dictionary, how can I print just the 1)'Price' and its value 2) rank it in descending order with its corresponding 'room_id' [OrderedDict([('room_id', '1133718'), ('survey_id', '1280'), ('host_id', '6219420'), ('room_type', 'Shared room'), ('country', ''), ('city', 'Singapore'), ('borough', ''), ('neighborhood', 'MK03'), ('reviews', '9'), ('overall_satisfaction', '4.5'), ('accommodates', '12'), ('bedrooms', '1.0'), ('bathrooms', ''), ('price', '74.0'), ('minstay', ''), ('last_modified', '2017-05-17 09:10:25.431659'), ('latitude', '1.293354'), ('longitude', '103.769226'), ('location', '0101000020E6100000E84EB0FF3AF159409C69C2F693B1F43F')]), OrderedDict([('room_id', '3179080'), ('survey_id', '1280'), ('host_id', '15295886'), ('room_type', 'Shared room'), ('country', ''), ('city', 'Singapore'), ('borough', ''), ('neighborhood', 'TS17'), ('reviews', '15'), ('overall_satisfaction', '5.0'), ('accommodates', '12'), ('bedrooms', '1.0'), ('bathrooms', ''), ('price', '77.0'), ('minstay', ''), ('last_modified', '2017-05-17 09:10:24.216548'), ('latitude', '1.310862'), ('longitude', '103.858828'), ('location', '0101000020E6100000E738B709F7F659403F1BB96E4AF9F43F')]), OrderedDict([('room_id', '15303457'), ('survey_id', '1280'), ('host_id', '97053568'), ('room_type', 'Shared room'), ('country', ''), ('city', 'Singapore'), ('borough', ''), ('neighborhood', 'MK05'), ('reviews', '0'), ('overall_satisfaction', '0.0'), ('accommodates', '14'), ('bedrooms', '1.0'), ('bathrooms', ''), ('price', '60.0'), ('minstay', ''), ('last_modified', '2017-05-17 09:10:16.969900'), ('latitude', '1.333744'), ('longitude', '103.764612'), ('location', '0101000020E610000044882B67EFF0594093C7D3F20357F53F')])]
has answer: http://stackoverflow.com/a/51106258
accepted answer: http://stackoverflow.com/a/51106258
answer count: 3
possible better answer: http://stackoverflow.com/a/51105330
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
tagged with: ordereddictionary
has answer: http://stackoverflow.com/a/51105330
type: Question
has answer: http://stackoverflow.com/a/51105118
downvote count: 0

http://stackoverflow.com/a/51033933
type: AcceptedAnswer
has body: IIUC, you have a json string and wish to get values from its attributes. So, given s = ''' {"AudioStreams":[{"JitterInterArrival":10,"JitterInterArrivalMax":24,"PacketLossRate":0.01353227,"PacketLossRateMax":0.09027778,"BurstDensity":null, "BurstDuration":null,"BurstGapDensity":null,"BurstGapDuration":null,"BandwidthEst":25245423,"RoundTrip":520,"RoundTripMax":11099,"PacketUtilization":2843,"RatioConcealedSamplesAvg":0.02746676,"ConcealedRatioMax":0.01598402,"PayloadDescription":"SIREN","AudioSampleRate":16000,"AudioFECUsed":true,"SendListenMOS":null,"OverallAvgNetworkMOS":3.487248,"DegradationAvg":0.2727518, "DegradationMax":0.2727518,"NetworkJitterAvg":253.0633, "NetworkJitterMax":1149.659,"JitterBufferSizeAvg":220,"JitterBufferSizeMax":1211, "PossibleDataMissing":false}]} ''' You can do import json &gt;&gt;&gt; data = json.loads(s) &gt;&gt;&gt; ji = data['AudioStreams'][0]['JitterInterArrival'] 10 In a data frame scenario, if you have a column col of strings such as the above, e.g. df = pd.DataFrame({"col": [s]}) You can use transform passing json.loads as argument df.col.transform(json.loads) to get a Series of dictionaries. Then, you can manipulate these dicts or just access the data as done above.
upvote count: 1
answers question: http://stackoverflow.com/q/51033858
type: Answer
accepted answer of: http://stackoverflow.com/q/51033858
downvote count: 0
has comment: http://stackoverflow.com/comment/89060026
score: 1
has comment: http://stackoverflow.com/comment/89060048

http://stackoverflow.com/a/51143142
upvote count: 2
has body: As said in the comments, to exclude members of the list from being in Column3: df.loc[~df['Column3'].isin(excl_list)] The first part, df['Column3'].isin(excl_list), returns a sequence of True/False terms, one for each row in df. The ~ flips all Trues and Falses, and df.loc[] looks up the trues.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51143074
answers question: http://stackoverflow.com/q/51143074
score: 0
downvote count: 2
type: Answer

http://stackoverflow.com/comment/89237939
score: 0
comment on: http://stackoverflow.com/q/51126115
type: Comment
type: QuestionComment
has text: @VPfB added a few more options that use fstrings.

http://stackoverflow.com/a/51145085
has comment: http://stackoverflow.com/comment/89274815
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89274566
has body: I did exactly as you did, and sort_values worked fine for me. In fact, I didn't have a RangeIndex; just a normal pandas dataframe. Here's my code: import pandas as pd x = [(6,5,4), (3,2,1)] df = pd.DataFrame(x) print(df) # View the unsorted dataframe df.sort_values(by=0) # Sorts by the 0th column print(df) # View the sorted dataframe Even though my columns aren't named, they are still indexed, so I can refer to them by their number when sorting.
has comment: http://stackoverflow.com/comment/89274909
answers question: http://stackoverflow.com/q/51145027
has comment: http://stackoverflow.com/comment/89274515
accepted answer of: http://stackoverflow.com/q/51145027
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89207499
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51110217
has text: Are you missing a `*` there after `(B-r)`?

http://stackoverflow.com/q/51102161
has answer: http://stackoverflow.com/a/51249113
has comment: http://stackoverflow.com/comment/89191488
upvote count: 5
accepted answer: http://stackoverflow.com/a/51176621
has comment: http://stackoverflow.com/comment/89193084
linked to: http://stackoverflow.com/q/3906232
has comment: http://stackoverflow.com/comment/89191586
tagged with: python-2.7
score: 5
has comment: http://stackoverflow.com/comment/89193232
has answer: http://stackoverflow.com/a/51176111
has title: Retain environment of helper python script in main script
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51285615
possible better answer: http://stackoverflow.com/a/51176111
has comment: http://stackoverflow.com/comment/89333768
tagged with: python
linked to: http://stackoverflow.com/q/436198
has comment: http://stackoverflow.com/comment/89191716
has comment: http://stackoverflow.com/comment/89191617
has comment: http://stackoverflow.com/comment/89333116
answer count: 4
has answer: http://stackoverflow.com/a/51176621
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89193673
has comment: http://stackoverflow.com/comment/89192544
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89191636
has body: I've one helper script which I want to call from main script which is acting as a Server. This main script looks like this: Class Stuff(): def __init__(self, f): self.f = f self.log = {} def execute(self, filename): execfile(filename) if __name__ == '__main__': #start this script as server clazz = Stuff() #here helper_script name will be provided by client at runtime clazz.execute(helper_script) Now Client will invoke this helper script by providing it's name to main script(Server). After execution I want to retain variables of helper script (i.e: a,b) in main script. I know one way is to return those variables from helper script to main script. But is there any other way so to retain all variables of helper script. This is how helper script looks like: import os a = 3 b = 4 I tried using execfile and subprocess.
type: Question

http://stackoverflow.com/a/51128080
upvote count: 1
answers question: http://stackoverflow.com/q/51127873
type: AcceptedAnswer
downvote count: 0
has body: Requests is a simple html client, it cannot execute javascripts. You have three more options to try here though! try going over the html source (b) and see if any of the javascripts in the site have the data you need. usually, the page would have the url (which, i assume you want to scrape) in some sort of holder (a javascript code or a json object) that you can scrape off. Try looking at the XHR requests of the site and see if any of the requests query external sources for the video data. In this case, see if you can imitate that request to get the data you need. (last resort) You need to use a phantomjs + selenium browser to download the website (Link1, Link2). You can find out more about how to use selenium in this SO post: https://stackoverflow.com/a/26440563/3986395
accepted answer of: http://stackoverflow.com/q/51127873
type: Answer
score: 1

http://stackoverflow.com/a/51097393
type: Answer
answers question: http://stackoverflow.com/q/51096887
score: 0
has body: I have no experience with this issue but you can try this (http://python3porting.com/problems.html) : from collections import UserDict from collections import MutableMapping as DictMixin import potara # ... etc

http://stackoverflow.com/q/51144717
downvote count: 1
has answer: http://stackoverflow.com/a/51144914
score: 1
type: Question
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89273982
has title: Define a date string using a dictionary
has comment: http://stackoverflow.com/comment/89274008
has body: I want to produce a date in the form m/d/y by putting in 3 numbers and defining the string "date" using the dictionary: {"m":&lt;number&gt;,"d":&lt;number&gt;,"y":&lt;number&gt;} For example, I want to put in 1,5,2000 and have python return "1/5/2000" I do not want to use datetime or separate variables. def date_string(date):
tagged with: python
has comment: http://stackoverflow.com/comment/89273936
has comment: http://stackoverflow.com/comment/89273951
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89279549
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89273910

http://stackoverflow.com/comment/89072146
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51040483
score: 1
has text: It's not a for loop, it's a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).

http://stackoverflow.com/q/51056256
has answer: http://stackoverflow.com/a/51057744
has title: AttributeError: 'str' object has no attribute 'click' while trying to loop through the hrefs and click them through Selenium and Python
tagged with: selenium-webdriver
tagged with: python-3.x
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/89103657
upvote count: 1
has comment: http://stackoverflow.com/comment/89103843
downvote count: 1
has comment: http://stackoverflow.com/comment/89104338
type: Question
has comment: http://stackoverflow.com/comment/89103020
has body: This is the tag containing href. This is the HTML of one of the links when I inspected it. The code I used to for looping through the links is: elems = driver.find_elements_by_xpath("//a[@href]") for elem in elems: print(elem) elem.get_attribute("href").click() but I am getting the error: File "C:/Users/user/Desktop/sel.py", line 31, in (session="7896348772e450d1658543632013ca4e", element="0.06572622905717385-1")> elem.get_attribute("href").click() AttributeError: 'str' object has no attribute 'click' Can any one help please.
has answer: http://stackoverflow.com/a/51056604
tagged with: webdriver
answer count: 3
has answer: http://stackoverflow.com/a/51056940
has comment: http://stackoverflow.com/comment/89105766
favorite count: 0
has comment: http://stackoverflow.com/comment/89103384
has comment: http://stackoverflow.com/comment/89103434
score: 0
tagged with: python

http://stackoverflow.com/comment/89115996
has text: Worked perfectly, thanks!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51062917

http://stackoverflow.com/q/51121782
has title: python: replace non-"normal" characters in a string
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20078816
type: Question
has body: While iterating through different strings I sometimes stumble upon characters that contain strings such as "ś" or even just a " ' " and I want to replace those every single character with a simple "_". So the code I would want is one that meets the following requirements: if character is not a,b,c....Z or a number then character = "_". I wonder what is the most elegant way to implement such a code. Thanks in advance.
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51121796
accepted answer: http://stackoverflow.com/a/51121796
has comment: http://stackoverflow.com/comment/89228810

http://stackoverflow.com/a/54381386
has comment: http://stackoverflow.com/comment/127064542
has comment: http://stackoverflow.com/comment/115857687
has comment: http://stackoverflow.com/comment/115825299
has comment: http://stackoverflow.com/comment/121555281
has comment: http://stackoverflow.com/comment/121561480
type: Answer
has body: For deploying an application to production, one option is to use Waitress, a production WSGI server. Here is an example of using waitress in the code. from flask import Flask app = Flask(__name__) @app.route("/") def index(): return " Hello! " if __name__ == "__main__": from waitress import serve serve(app, host="0.0.0.0", port=8080) Running the application: $ python hello.py Waitress also provides a command line utility waitress-serve. To use that, you can modify the code to the following: from flask import Flask app = Flask(__name__) @app.route("/") def index(): return " Hello! " def create_app(): return app Then we can use waitress-serve as the following: waitress-serve --port=8080 --call hello:create_app And BTW, 8080 is the default port. To validate the deployment, open a separate window: % curl localhost:8080 Hello! % Or directly in your browser http://localhost:8080/. Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
upvote count: 333
downvote count: 1
score: 332
has comment: http://stackoverflow.com/comment/115841835
has comment: http://stackoverflow.com/comment/124743564
has comment: http://stackoverflow.com/comment/115822348
has comment: http://stackoverflow.com/comment/120604733
has comment: http://stackoverflow.com/comment/120603941
has comment: http://stackoverflow.com/comment/124747442
answers question: http://stackoverflow.com/q/51025893

http://stackoverflow.com/a/51062665
has body: If it's not string or bytes-like, what is it? You could check the type of your summarize function and move forward from there. test_text = df_data_1['Event Description (SAP)'].iloc[0] print(type(summarize(test_text)) Another remark: typically you'd want to avoid looping over a dataframe (see discussion). If you want to apply a function to an entire column, use df.apply() as follows: df_data1[‘Summary’] = df_data1['Event Description (SAP)'].apply(lambda x: summarize(x))
type: Answer
has comment: http://stackoverflow.com/comment/89115570
has comment: http://stackoverflow.com/comment/89121058
answers question: http://stackoverflow.com/q/51062519
score: 0
has comment: http://stackoverflow.com/comment/89120976

http://stackoverflow.com/q/51028077
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/89048487
tagged with: python
has comment: http://stackoverflow.com/comment/89048622
has answer: http://stackoverflow.com/a/51028417
upvote count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/89048496
answer count: 1
has body: I have a list of item like this: (the number of item lists can vary) My title http://myurl.com text My title http://myurl.com text ... How with beautiful soup I could get all these data so I can put all of them is a list to have a result like this : [{'title': h3, 'url': url, 'title': title}, {'title': h3, 'url': url, 'title': title}, ...] ? thank you
has title: Multi find beautiful soup
score: -3
downvote count: 4
accepted answer: http://stackoverflow.com/a/51028417
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/89048999

http://stackoverflow.com/q/51090459
tagged with: opencv
linked to: http://stackoverflow.com/q/42461211
has title: How to remove the dash lines in the images using cv2 and python
linked to: http://stackoverflow.com/q/39752235
has comment: http://stackoverflow.com/comment/89222924
linked to: http://stackoverflow.com/q/29200472
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am new to do image precessing. I am trying to remove the dash lines and dotted lines from the images using cv2 in python, but have some difficulties. What I have tried: (1) I got some idea from How to remove horizontal and vertical lines from an image , to remove the lines in the image. So I want to plot the dash lines into lines, and then, remove them. I used the Hough Tranform (Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV?) and (opencv detect dotted lines), but it introduces a lot of unnecessary lines that mess up all the numbers and words. I tuned the 'minLineLength' and 'maxLineGap' but do not help. The reason for these is there are some points in the words and numbers have the same 'maxLineGap' as the dash lines, so there are all plotted into lines. So if I remove the lines, I would remove the part of characters and numbers that have lines, such as 'Liabilities' and '28,056,622'. (2) I tried to use: horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontalsize,1)) But I am not sure how to represent dash lines pattern, and CV_SHAPE_CUSTOM is not available in the cv2. Please provide me with some suggestions. Thanks! The original file The image after I plot line accross the dash lines
score: 1
has comment: http://stackoverflow.com/comment/91375335
upvote count: 1
has answer: http://stackoverflow.com/a/57587113
type: Question

http://stackoverflow.com/q/51139280
type: Question
has title: append two data frames with unequal columns
answer count: 2
has answer: http://stackoverflow.com/a/51139494
has comment: http://stackoverflow.com/comment/89262637
favorite count: 0
tagged with: pandas
has body: I am trying to append two dataframes in pandas which have two different no of columns. Example: df1 A B 1 1 2 2 3 3 df2 A 4 5 Expected concatenated dataframe df A B 1 1 2 2 3 3 4 Null(or)0 5 Null(or)0 I am using df1.append(df2) when the columns are same. But no idea how to deal with unequal no of columns.
tagged with: python
possible better answer: http://stackoverflow.com/a/51139301
has answer: http://stackoverflow.com/a/51139301
accepted answer: http://stackoverflow.com/a/51139494
type: AnsweredQuestion
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/q/51102752
has body: my two dictionaries look like d1={123456 :{u'xyz':u'987'}, 892019:{u'kjl':u'0902'}, 102930491:{u'plm':u'019240',u'kop':u'09829'}} d2= {u'random_no_1': [u'123456', u'892019'], u'random_no_2': [u'102930491']} And I would like to have a combined dictionary. Something like this. d3 = {'random_no_1':{123456:{xyz:987}, 892019:{kjl:0902}}, 'random_no_2':{102930491:{plm:019240,kop:09829}} I tried this loop, but it only prints first to keys. result = {} for k, v in d1.items(): if isinstance(v, list): result[k] = {k: d2.get(k) for k in v} else: result[k] = {v: d2.get(v)} So my result looks like this. result = {'random_no_1':{123456 : None}, 892019: None}, 'random_no_2':{102930491: None} I think the problem is in the loop, any advice will be greatly appreciated.
has answer: http://stackoverflow.com/a/51102812
score: -1
has comment: http://stackoverflow.com/comment/89192833
has title: Append a dictionary to a nested dictionary
type: Question
has answer: http://stackoverflow.com/a/51104940
has comment: http://stackoverflow.com/comment/89192858
upvote count: 0
has comment: http://stackoverflow.com/comment/89193130
has comment: http://stackoverflow.com/comment/89192797
accepted answer: http://stackoverflow.com/a/51102812
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/51103557
favorite count: 0
has answer: http://stackoverflow.com/a/51102843
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51102843

http://stackoverflow.com/a/51140976
upvote count: 1
has body: @afg1997, you can also continue with your own approach just by replacing or with and and with a little modification in your code as follows. &gt;&gt;&gt; p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt'] &gt;&gt;&gt; &gt;&gt;&gt; [x for x in p if not 'two' in x and not 'three' in x] ['/path/one/foo.txt', '/path/four/foo.txt'] &gt;&gt;&gt;
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51140707

http://stackoverflow.com/q/51040853
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89257263
has comment: http://stackoverflow.com/comment/89264552
tagged with: python
has comment: http://stackoverflow.com/comment/89122300
answer count: 0
score: 1
tagged with: equation
upvote count: 1
has comment: http://stackoverflow.com/comment/89112693
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/89123070
has body: I am trying to solve a set of nonlinear equations. I have to solve it for different parameters. Most of the time everything seems to work fine. Like in this case: from scipy.optimize import fsolve import numpy as np p=3 x_diff=3.32 y_diff=-1.93 z_diff=0.64 def cubic(c): r=c[0] u=c[1] F=np.empty((2)) F[0]=y_diff*cos(u)-x_diff*sin(u) F[1]=r+cos(u)*x_diff+y_diff*sin(u)+(r**(2*p-1))*(a**2)*p+z_diff*p*(r**(p-1))*a return F cGuess=np.array([3.,2.]) c=fsolve(cubic,cGuess) x=cubic(c) In the end I tested the result by inserting it into the function cubic(). For the parameters used above the function gives something close to zero as it should. But if I change the Parameter x_diff, y_diff and z_diff. fsolve returns the initial Guess as a solution, which is not the solution to the set of equation as you can see if you insert it in the function cubic(). x_diff=-6.15 y_diff=-2.11 z_diff=0.13 I am quite new to python, so it might be just a stupid mistake, but I can't find it. I really need this to work so thank you for every help! Thanks!
has comment: http://stackoverflow.com/comment/89253520
has comment: http://stackoverflow.com/comment/89255674
tagged with: python-2.7
has title: Python 2.7: fsolve sometimes returns the initial guess instead of the solution:

http://stackoverflow.com/q/51051606
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89094522
has comment: http://stackoverflow.com/comment/89094835
accepted answer: http://stackoverflow.com/a/51051891
has comment: http://stackoverflow.com/comment/89094650
downvote count: 0
answer count: 1
has title: Unable to import python module in script, but can in command prompt
favorite count: 0
has body: I have install scipy to read data from a .mat file. When I am in Python in the command prompt I am able to type the following and get the value I desire: Command Prompt &gt;&gt;&gt; import scipy &gt;&gt;&gt; import scipy.io &gt;&gt;&gt; from scipy.io import loadmat &gt;&gt;&gt; x=loadmat('C:\My websites\Rooftop PV.mat') &gt;&gt;&gt; size = x['component']['Size'][0][0][0][0] &gt;&gt;&gt; print(size) 150 &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.executable 'C:\\...\\Documents\\anaconda3\\python.exe' However, when I run the .py script... .py script import sys print(sys.executable) import scipy import scipy.io from scipy.io import loadmat x = loadmat('C:\My websites\Rooftop PV.mat') size = x['component']['Size'][0][0][0][0] print(size) it is unable to find the scipy.io module, producing this error: Error: C:\Python\pythonw.exe File "C:\Python\testmatfile.py", line 4, in &lt;module&gt; import scipy.io ModuleNotFoundError: No module named 'scipy.io' Any ideas on why this might be? Thanks!
tagged with: python
tagged with: module
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89094937
upvote count: 3
has answer: http://stackoverflow.com/a/51051891
tagged with: scipy
tagged with: import

http://stackoverflow.com/a/51082252
has comment: http://stackoverflow.com/comment/89153401
downvote count: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/89153093
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51081451
has body: In Python function, parameter values are passed by assignment (the parameter passed in is actually a reference to an object, but the reference is passed by value), so if you modify df1 you're modifying the dataframe that was passed as paramter in the function. You might want to use copy def func(df1,df2,df3): df1 = df1.copy() df1.set_index('A',inplace=True) df2['c'] = df1['B'] * df3['G'] return df3 Note : By default deep parameter of the copy function is True, so might use memory, because of data duplication.

http://stackoverflow.com/q/51050146
upvote count: 6
type: AnsweredQuestion
tagged with: string-formatting
linked to: http://stackoverflow.com/q/1995615
score: 6
tagged with: floating-point
type: Question
has title: Python string formatting - combine named placeholder and float formatter for the same argument?
accepted answer: http://stackoverflow.com/a/51050165
tagged with: formatting
possible better answer: http://stackoverflow.com/a/51050187
answer count: 3
has answer: http://stackoverflow.com/a/51050165
downvote count: 0
has body: In Python is possible to combine 2 followings concepts - named arguments and float formatting? '{0:.2f}'.format(pi) and '{first} {last}'.format(first='Hodor', last='Hodor!') https://stackoverflow.com/a/8940627/2230844 https://pyformat.info/#named_placeholders
tagged with: string
has answer: http://stackoverflow.com/a/51050228
favorite count: 0
has answer: http://stackoverflow.com/a/51050187
tagged with: python

http://stackoverflow.com/comment/89245530
type: AnswerComment
score: 0
type: Comment
has text: I need to use findall but your code hasn't used it.
comment on: http://stackoverflow.com/a/51130377

http://stackoverflow.com/comment/111689450
has text: Better to check how you installed facebook module using pip. The command worked out for me was `$ pip install --user facebook-sdk`
comment on: http://stackoverflow.com/q/51041998
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51049975
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/730133
type: Question
accepted answer: http://stackoverflow.com/a/51055103
has body: Using Python 3 Error we get: File "C:/scratch.py", line 27, in run tree = ET.fromstring(responses[0].decode(), ET.XMLParser(encoding='utf-8')) File "C:\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1314, in XML parser.feed(text) xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 163, column 1106 Our code: tree = ET.fromstring(responses[0].decode(), ET.XMLParser(encoding='utf-8')) for i in tree.iter('item'): try: title = i.find('title').text except Exception: pass The responses[0] is from a list of url get requests being returned, but in this case of index 0, testing on one specific url: http://feeds.feedburner.com/marginalrevolution/feed We were able to plug in the XML code to W3 School validator and got: This page contains the following errors: error on line 163 at column 31: Input is not in proper UTF-8, indicate encoding! Bytes: 0x0C 0x66 0x69 0x67 But with the ET.XMLParser(encoding='utf-8') property, shouldn't this fix the error when parsing?
answer count: 1
downvote count: 0
tagged with: xml-parsing
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/51055103
has title: xml.etree.ElementTree.ParseError: not well-formed (invalid token)
tagged with: python
score: 2

http://stackoverflow.com/comment/89278577
has text: @ReblochonMasque There's no real problem with my code. It's just slow and unsophisticated. All it does is 1) get tallies of duplicate-items, 2) removes duplicates from the list, and 3) modifies each duplicated-item string with the previously-gotten duplicate-count in 3 separate `for` loops. I didn't post my clunky code because I can't imagine that a SO member would want to use my code as any sort of starting point.
score: 0
comment on: http://stackoverflow.com/q/51146967
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51031347
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/51031077
answers question: http://stackoverflow.com/q/51031077
type: AcceptedAnswer
downvote count: 0
has body: You're really overthinking this quite a bit. It's simpler to demonstrate in 2D, and the logic is the same: In the figure above, we have a circle centered at (0, 0), and a point located at (0, 1). Now, let's center the circle at (1, 1) and move the point to the same relative position: The new center of our circle is (1, 1), and the point is now located at (1, 2). All you need to do to get this transformation is: 1 + 0 = 1 # new_center_x + point_x 1 + 1 = 2 # new_center_y + point_y It really is that simple! Now numpy has built in functionality to make this even easier, because you can simply add numpy arrays. So if you have your new center, and your initial point, you can calculate the new point like so: new_center = np.array([1, 1]) original_point = np.array([0, 1]) new_center + original_point # array([1, 2]) This translates easily to 3D surfaces: Here we have a sphere centered at (0, 0, 0), and a point at (0, 0, 10). We can use the same logic to move this circle to be centered at (5, 5, 5), with the point still in the same relative position: new_center = np.array([5, 5, 5]) original_point = np.array([0, 0, 10]) new_center + original_point # array([ 5, 5, 15])
has comment: http://stackoverflow.com/comment/89091639

http://stackoverflow.com/comment/89280324
type: Comment
type: QuestionComment
has text: this example from the above library lists all the functions: https://github.com/eliben/pycparser/blob/master/examples/func_defs.py
comment on: http://stackoverflow.com/q/51148129
score: 0

http://stackoverflow.com/comment/89146609
has text: Just to be clear the `data` is coming directly from a temperature sensor using `bluetooth`. If I use `setvbuf` , will this be a problem for the data transfer when used in another part of the code? maybe for the `scan` block buffering is not needed but for the data tranfser, it may be necessary. it is a very low powered device which is why it was implemented.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51078297

http://stackoverflow.com/comment/89171937
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51091547
type: Comment
has text: Drag the executable generated by cx_freeze into a command prompt, and paste the output in your question. There a variety of things that could be going wrong.

http://stackoverflow.com/q/51011601
has comment: http://stackoverflow.com/comment/89016821
tagged with: random
type: Question
possible better answer: http://stackoverflow.com/a/51011791
has answer: http://stackoverflow.com/a/51011791
score: 1
upvote count: 2
has title: Efficient random sampling
has comment: http://stackoverflow.com/comment/89016131
tagged with: python
downvote count: 1
has body: My problem is simple: I've an array with 20 million floats. In that array, every float has a probability p of being randomly altered. The simples way to do so is to move through the array, doing if (rand(0,1) &lt; p) then modify. However, even paralelizing, its slow as hell, and I was thinking if there's a faster way to randomly obtain some indexes to modify. My first thought was to pick up p * n random numbers, where n is the total number of floats in the array, however, that doesnt exactly represent the probability distribution, as nothing in the first case guarantees that only p*n floats will be modified. Ideas? PD: I'm using python for the implementation, probably someone had this problem before and implemented something in the libraries, but I cannot find it.
has answer: http://stackoverflow.com/a/51011947
has answer: http://stackoverflow.com/a/51011757
tagged with: math
has comment: http://stackoverflow.com/comment/89016019
answer count: 5
has comment: http://stackoverflow.com/comment/89016731
has comment: http://stackoverflow.com/comment/89016275
has answer: http://stackoverflow.com/a/51011821
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51014080
accepted answer: http://stackoverflow.com/a/51011757
favorite count: 0
has comment: http://stackoverflow.com/comment/89016083

http://stackoverflow.com/a/51125764
has comment: http://stackoverflow.com/comment/106475015
has comment: http://stackoverflow.com/comment/105390764
type: Answer
score: 6
has body: A major advantage of dataclasses is that they are self-documenting. Assuming the reader of your code knows how dataclasses work (and your attributes are appropriately named), the type-annotated class attributes should be excellent documentation of the constructor. See this example from the official dataclass docs: @dataclass class InventoryItem: '''Class for keeping track of an item in inventory.''' name: str unit_price: float quantity_on_hand: int = 0 def total_cost(self) -&gt; float: return self.unit_price * self.quantity_on_hand If you don't expect that readers of your code would know how dataclasses work then you might want to reconsider using them or adding an explanation or link to the docs in an inline comment after the @dataclass decorator. If you really need a docstring for a dataclass, I'd recommend putting the constructor docstring within the class docstring. For the example above: '''Class for keeping track of an item in inventory. Constructor arguments: :param name: name of the item :param unit_price: price in USD per unit of the item :param quantity_on_hand: number of units currently available '''
downvote count: 3
upvote count: 9
has comment: http://stackoverflow.com/comment/89237372
answers question: http://stackoverflow.com/q/51125415

http://stackoverflow.com/q/51107657
score: 1
tagged with: screen-scraping
has answer: http://stackoverflow.com/a/51107802
has comment: http://stackoverflow.com/comment/89202578
type: Question
answer count: 2
downvote count: 0
has title: Can't scrape some "div" tags from a site
has body: I am trying to scrape job posts from this page: https://www.fl.ru. Probably quite a newbie problem, but it turns out I can get certain tags, while others seem to be unreachable, e.g.: from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://www.fl.ru/projects/") bsObj = BeautifulSoup(html, "lxml") textTags = bsObj.findAll("div", class_="b-post__txt ") print(str(textTags)) Thanks
has comment: http://stackoverflow.com/comment/89202399
has comment: http://stackoverflow.com/comment/89204167
accepted answer: http://stackoverflow.com/a/51107802
tagged with: http://stackoverflow.com/tag/html
tagged with: python
possible better answer: http://stackoverflow.com/a/51107718
favorite count: 0
has answer: http://stackoverflow.com/a/51107718
has comment: http://stackoverflow.com/comment/89205151
upvote count: 1
has comment: http://stackoverflow.com/comment/89202444
type: AnsweredQuestion

http://stackoverflow.com/q/51065521
has answer: http://stackoverflow.com/a/51163241
has comment: http://stackoverflow.com/comment/89301924
has comment: http://stackoverflow.com/comment/89161366
type: Question
has body: I'm trying to get sqlalchemy-continuum to work alongside flask-sqlalchemy and flask-migrate. My __init__.py file looks like this: import os from flask import Flask def create_app(): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SQLALCHEMY_DATABASE_URI='postgres+psycopg2://{}:{}@{}:{}/{}'.format( os.environ['POSTGRES_USER'], os.environ['POSTGRES_PASSWORD'], os.environ['POSTGRES_HOST'], os.environ['POSTGRES_PORT'], os.environ['POSTGRES_DB'] ), SQLALCHEMY_TRACK_MODIFICATIONS=False ) try: os.makedirs(app.instance_path) except OSError: pass from .models import db, migrate db.init_app(app) migrate.init_app(app, db) return app My models.py file looks like this: import sqlalchemy from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from sqlalchemy_continuum import make_versioned db = SQLAlchemy() migrate = Migrate() make_versioned(user_cls=None) class User(db.Model): __versioned__ = {} __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(20), unique=True, nullable=False) def __repr__(self): return '&lt;User {} - {}&gt;'.format(self.username, self.email) sqlalchemy.orm.configure_mappers() I then run the following flask-migrate commands to initialise and migrate the database: flask db init flask db migrate flask db upgrade The output of the flask db upgrade command seems to show the correct tables being created: INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.autogenerate.compare] Detected added table 'transaction' INFO [alembic.autogenerate.compare] Detected added table 'user' INFO [alembic.autogenerate.compare] Detected added table 'user_version' INFO [alembic.autogenerate.compare] Detected added …
score: 4
tagged with: flask
tagged with: flask-sqlalchemy
has title: Using sqlalchemy-continuum with flask-sqlalchemy and flask-migrate
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89299271
tagged with: sqlalchemy-continuum
favorite count: 0
accepted answer: http://stackoverflow.com/a/51163241
tagged with: python
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/89029804
type: AnswerComment
has text: Thanks guys! The almost exact same answer at the same time :)
comment on: http://stackoverflow.com/a/51018601
type: Comment
score: 0

http://stackoverflow.com/comment/89180170
type: AnswerComment
comment on: http://stackoverflow.com/a/51094276
score: 0
type: Comment
has text: Did everything you said to install, and there seemed to be no issues, but when I try and use it it says 'pytinstaller : The term 'pytinstaller' 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.'

http://stackoverflow.com/comment/89256377
comment on: http://stackoverflow.com/a/51136059
score: 0
type: Comment
type: AnswerComment
has text: Working !! Thanks

readfile
tags question: http://stackoverflow.com/q/51056172
type: Tag
tag name: readfile

http://stackoverflow.com/a/56749404
type: Answer
has comment: http://stackoverflow.com/comment/114922565
has comment: http://stackoverflow.com/comment/115350572
has comment: http://stackoverflow.com/comment/107342009
upvote count: 24
has comment: http://stackoverflow.com/comment/135545028
score: 24
has comment: http://stackoverflow.com/comment/100664158
has body: The following filetype xml will highlight Jenkinsfile syntax in PyCharm create a new Jenkinsfile.xml, copy the following xml: &lt;filetype binary="false" description="Jenkinsfile support" name="Jenkinsfile"&gt; &lt;highlighting&gt; &lt;options&gt; &lt;option name="LINE_COMMENT" value="//" /&gt; &lt;option name="COMMENT_START" value="/*" /&gt; &lt;option name="COMMENT_END" value="*/" /&gt; &lt;option name="HEX_PREFIX" value="" /&gt; &lt;option name="NUM_POSTFIXES" value="" /&gt; &lt;option name="HAS_BRACES" value="true" /&gt; &lt;option name="HAS_BRACKETS" value="true" /&gt; &lt;option name="HAS_PARENS" value="true" /&gt; &lt;option name="HAS_STRING_ESCAPES" value="true" /&gt; &lt;option name="LINE_COMMENT_AT_START" value="true" /&gt; &lt;/options&gt; &lt;keywords keywords="def;else;if;import;print;return" ignore_case="true" /&gt; &lt;keywords2 keywords="node" /&gt; &lt;keywords3 keywords="field;library;stage;string" /&gt; &lt;keywords4 keywords="try;catch;finally" /&gt; &lt;/highlighting&gt; &lt;extensionMap&gt; &lt;mapping pattern="Jenkinsfile" /&gt; &lt;/extensionMap&gt; &lt;/filetype&gt; and place it under macOS ~/Library/Preferences/PyCharmXX/filetypes Linux copy to /.PyCharmXX/config/filetypes Win copy to &lt;User home&gt;\.PyCharmXX\config\filetypes https://github.com/galCohen88/pycharm-jenkinsfile
has comment: http://stackoverflow.com/comment/101478699
answers question: http://stackoverflow.com/q/51124878
has comment: http://stackoverflow.com/comment/100243035
downvote count: 0
has comment: http://stackoverflow.com/comment/100200628
has comment: http://stackoverflow.com/comment/118415515
has comment: http://stackoverflow.com/comment/100279356
has comment: http://stackoverflow.com/comment/100632042
has comment: http://stackoverflow.com/comment/100676320

http://stackoverflow.com/q/51047473
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51048083
score: 0
has comment: http://stackoverflow.com/comment/89087258
tagged with: python
has body: Let's say I have a dataframe below. a b c 0 one two three 1 three one two I want to make row 0 and 1 to be treated as a same list? or something, since both row contains 'one', 'two', 'three' even though the order is different. Should I make a new column which stores all the string from a, b, c column such as, a b c d 0 one two three one two three 1 three one two three one two and then compare row 0 and 1 of column d? After this, I want to do .groupby('d') and as a result, 'one two three' and 'three one two' must not be seperated. I can't think of a way to solve this and need help.
has title: Python - check several columns and compare string
has answer: http://stackoverflow.com/a/51048203
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89086897

http://stackoverflow.com/comment/89131022
type: Comment
comment on: http://stackoverflow.com/q/51070538
score: 0
type: QuestionComment
has text: im stuck on how to transfer the certain part of the split 1001, 1002, etc into the empty list frames

http://stackoverflow.com/comment/89306114
comment on: http://stackoverflow.com/a/51156985
type: AnswerComment
score: 0
type: Comment
has text: I was under the impression that the justification from, "... having an apps package for namespace declarations is totally fine, especially if you plan to have multiple apps; in fact, this is what Django does itself ..." inferred that the Django Python package is a Django project because it puts its reusable (and not installed) apps in a directory. I was simply pointing out that Python package != Django project's apps, so the Django package doesn't *actually* do that. Maybe I misinterpreted what you said

http://stackoverflow.com/comment/89209442
type: Comment
has text: I fixed it to return the values, however i am confused about what should go after the while loop of x!=1.
type: QuestionComment
comment on: http://stackoverflow.com/q/51111163
score: 0

http://stackoverflow.com/comment/89251232
score: 2
has text: Then in all probability what you actually want is a *dictionary*: `{"a": 2}["a"] == 2`.
type: QuestionComment
comment on: http://stackoverflow.com/q/51133287
type: Comment

http://stackoverflow.com/a/51109466
has comment: http://stackoverflow.com/comment/89206358
has comment: http://stackoverflow.com/comment/89206282
has comment: http://stackoverflow.com/comment/89206232
has body: These are Python's file types: .py files are not binary files, they are pure Python code. .pyc and .pyo are Python compiled files (which are not fully binary either). The only difference is that the latter is optimized. .pyw does not say anything about being a binary or not. It just doesn't open a console window on Windows machines. (Runs using pythonw.exe instead of python.exe by default) Any text editor should be able to open .py files correctly. According to your screenshot, it might be python code compiled with some sort of py2exe just in elf. Maybe cx_freeze? Getting out the code will not be easy at all: You can either get it straight out from memory by using a debugger like gdb or attempting to decompile it somehow. Even then you would only get the .pyc which is a barely understandable piece of code.
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89206455
has comment: http://stackoverflow.com/comment/89206205
type: Answer
has comment: http://stackoverflow.com/comment/89206042
answers question: http://stackoverflow.com/q/51109420
upvote count: 3
has comment: http://stackoverflow.com/comment/89206061

http://stackoverflow.com/comment/127259929
comment on: http://stackoverflow.com/a/58401290
score: 0
type: AnswerComment
has text: @vaporK I think I am sure. Look at this: https://www.calculator.net/standard-deviation-calculator.html?numberinputs=4.1450%2C+4.0104%2C+4.0228%2C+4.4689%2C+3.7810&ctype=p&x=97&y=22
type: Comment

http://stackoverflow.com/q/51045241
has comment: http://stackoverflow.com/comment/89082109
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/89147182
score: 0
has body: I'm working on a project with Django Rest Framework in which I need to make a post request in which I need to pass a JSON object against a TextField along with the other fields, How can I pass a JSON object like this: { "no_of_svc": 3, "svc1": { "name": "details", "imagePullPolicy": "IfNotPresent", "versions": { "v1": { "name": "details-v1", "image": "example-details-v1" } }, "port": { "port": 9080, "name": "http" } }, "svc2": { "name": "ratings", "versions": { "v1": { "name": "ratings-v1", "image": "example-ratings-v1" }, "v2": { "name": "ratings-v2", "image": "example-ratings-v2" }, "port": { "port": 9080, "name": "http" } } }, "svc3": { "name": "reviews", "versions": { "v1": { "name": "reviews-v1", "image": "example-reviews-v1", "containerPort": 9080 }, "v2": { "name": "reviews-v2", "image": "example-reviews-v2" }, "port": { "port": 9080, "name": "http" } } } } and later parse it in the create method of generics.ListCreateAPIView ? Here's my model: services = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class DeploymentOnUserModel(models.Model): deployment_name = models.CharField(max_length=256, ) credentials = models.TextField(blank=False) project_name = models.CharField(max_length=150, blank=False) project_id = models.CharField(max_length=150, blank=True) cluster_name = models.CharField(max_length=256, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=150, choices=services) configuration = models.TextField() routing = models.TextField() def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing and not self.configuration: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs)
tagged with: python-3.x
tagged with: django-request
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89088798
answer count: 0
has comment: http://stackoverflow.com/comment/89088761
has comment: http://stackoverflow.com/comment/89082317
has comment: http://stackoverflow.com/comment/89149948
type: Question
has title: Django Rest Framework Get a JSON object in the request and parse in ListCreateAPIView

http://stackoverflow.com/q/51086721
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51086835
tagged with: python
has title: convert pandas dataframe of strings to numpy array of int
upvote count: 1
has body: My input is a pandas dataframe with strings inside: &gt;&gt;&gt; data 218.0 221.0 222.0 224.0 71,299,77,124 227.0 50,283,81,72 229.0 231.0 84,349 233.0 235.0 240.0 53,254 Name: Q25, dtype: object now i want a shaped ( .reshape(-1,2) ) numpy array of ints for every row like that: &gt;&gt;&gt; data 218.0 [] 221.0 [] 222.0 [] 224.0 [[71,299], [77,124]] 227.0 [[50,283], [81,72]] 229.0 [] 231.0 [[84,349]] 233.0 [] 235.0 [] 240.0 [[53,254]] Name: Q25, dtype: object i dont know how to get there by vector operations. can someone help?
has answer: http://stackoverflow.com/a/51086878
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51086835
possible better answer: http://stackoverflow.com/a/51086878
type: Question
tagged with: numpy
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/51040164
score: 0
type: Answer
has body: This will list all your process and match process by its name.If process found then break loop. import psutil process = psutil.pids() for id in process: proc = psutil.Process(id) if proc.name() == "some process": # add here your process name print("Found") break
answers question: http://stackoverflow.com/q/51039960

http://stackoverflow.com/a/51051700
downvote count: 0
has comment: http://stackoverflow.com/comment/89099685
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89099384
answers question: http://stackoverflow.com/q/51043043
has body: The error message is independent of shiny: library(reticulate) library(doParallel) library(foreach) library(parallel) source_python("multip.py") cl &lt;- makeCluster(detectCores(), type = 'PSOCK') registerDoParallel(cl) # throws: Error in unserialize(socklistn) : error reading from connection foreach(i = 1:5) %dopar% fsq(i) stopCluster(cl) I interpret this such that one cannot serialize a Python function as one can serialize a R function. A simple workaround is to use source_python within the loop: library(doParallel) library(foreach) library(parallel) cl &lt;- makeCluster(detectCores(), type = 'PSOCK') registerDoParallel(cl) foreach(i = 1:5) %dopar% { reticulate::source_python("multip.py") fsq(i) } stopCluster(cl)
accepted answer of: http://stackoverflow.com/q/51043043
type: AcceptedAnswer

http://stackoverflow.com/q/51023214
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51042882
has comment: http://stackoverflow.com/comment/89041390
favorite count: 0
has body: I'm trying to remove noise from image, i'm trying to make white pixel if certain condition met but i'm struggling to make that happen. This is my image and i want to remove all gray color lines only want high intensity color like blue red and green . Sorry for my editing This is my code where i have tried to check the condition which succeed then i'll change the pixel to white height, width = image.shape[0:2] for i in range(0, height): # looping at python speed... for j in range(0, width): # print(image) if ((image[i][j][1] * 255 == image[i][j][2] * 255 == image[i][j][3] * 255) or ( (image[i][j][0] * 255 == image[i][j][1] * 255) and ( image[i][j][3] * 255 &gt;= 245))): # print(image[i][j][2] * 255) image[i][j] = 0 plt.imshow(image) plt.savefig("filename.png") plt.show()
accepted answer: http://stackoverflow.com/a/51042882
tagged with: python
tagged with: noise-reduction
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51024399
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89040737
has title: How to remove noise from image in python
downvote count: 1
has answer: http://stackoverflow.com/a/51024399

http://stackoverflow.com/comment/89165761
type: Comment
comment on: http://stackoverflow.com/a/51087603
has text: Great ! thank you very much ;), I tried to accept your answer but I haven't enough reputations.
type: AnswerComment
score: 0

http://stackoverflow.com/a/51030920
answers question: http://stackoverflow.com/q/51030395
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You're looking at two completely different sources of information, the tutorial and the language reference. The tutorial section The Module Search Path (besides only describing the default behavior) is also describing only what happens when a module is actually imported. If the module is already in the cache, this process doesn't happen. That's not explained here, because it's already covered in the previous section, More on Modules: A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. ... Note For efficiency reasons, each module is only imported once per interpreter session. It doesn't explain the mechanism by which this happens, because this is just a tutorial. Meanwhile, in the reference docs for the import system, the module cache section explains the first thing that happen on an import statement. Notice that it's not exactly true that Python avoids executing the module's statements if the module has already been imported, or that it's only imported once for efficiency. That's a consequence of the fact that the default loaders put the module in the sys.modules cache. And if you replace the loaders, or monkey with the cache after the fact, a module will in fact be imported and executed multiple times. Subsequent sections—starting with the next section, Finders and loaders—similarly describe the details of how the module is found, more rigorously and in more detail than the Module Search Path section of the tutorial: Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an import path for modules. So again, it's not exactly true that the interpreter first searches for a built-in module. Instead, the interpreter just searches its finders in order, and by def…
accepted answer of: http://stackoverflow.com/q/51030395
type: Answer
has comment: http://stackoverflow.com/comment/89054222

http://stackoverflow.com/comment/89044966
score: 1
has text: But I don't observe the other thing you describe. The threads are running until they finish, in my case, even though I don't use a `with` block
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51026027

smtplib
tags question: http://stackoverflow.com/q/51060567
type: Tag
tag name: smtplib

http://stackoverflow.com/q/51019509
has answer: http://stackoverflow.com/a/76517709
has answer: http://stackoverflow.com/a/55970069
has comment: http://stackoverflow.com/comment/89038424
has answer: http://stackoverflow.com/a/59763655
has comment: http://stackoverflow.com/comment/89031772
has answer: http://stackoverflow.com/a/60296976
has answer: http://stackoverflow.com/a/57943066
has answer: http://stackoverflow.com/a/51023067
answer count: 7
possible better answer: http://stackoverflow.com/a/55970069
tagged with: cudnn
has comment: http://stackoverflow.com/comment/89038189
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89037977
has comment: http://stackoverflow.com/comment/89038364
has comment: http://stackoverflow.com/comment/89038099
has title: Tensorflow: ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory
has body: I have recently installed tensorflow-gpu using pip. But when I am importing it it is giving the following error: ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory I have gone through all the answers of stackoverflow related to this issue but none of them worked for me. libcudnn.so.7 is present in both the following directories /usr/local/cuda/lib64 and /usr/local/cuda-9.0/lib64 . Also, I have added the following path in my .bashrc file: export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}} export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} export PATH=/usr/local/cuda/bin${PATH:+:${PATH}} export LD_LIBRARY_PATH=/usr/local/cuda/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} Please help me in resolving this
tagged with: python
has comment: http://stackoverflow.com/comment/97642864
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89038331
accepted answer: http://stackoverflow.com/a/51023067
tagged with: tensorflow
type: Question
upvote count: 22
downvote count: 0
has answer: http://stackoverflow.com/a/59426727
score: 22

http://stackoverflow.com/comment/89304899
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51160386
has text: @UmangGupta, i am using the same version.
score: 0

http://stackoverflow.com/comment/89050919
has text: What values are you summing again?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51028364
score: 0

http://stackoverflow.com/q/51023367
has comment: http://stackoverflow.com/comment/89321118
possible better answer: http://stackoverflow.com/a/51033246
downvote count: 0
has answer: http://stackoverflow.com/a/51033246
has answer: http://stackoverflow.com/a/51169105
favorite count: 0
has body: I have used tensorflow object detection-api to train my own object detector.But at that time, the images were annotated using labelimg which create xml file for each image.Now I have got labeled images which have json file for each image.So how I use these json files to create tfrecords.
has title: How to make tfrecords from json annotated images
tagged with: python
tagged with: object-detection
type: AnsweredQuestion
tagged with: object-detection-api
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/51169105
has comment: http://stackoverflow.com/comment/89049151
tagged with: tensorflow
type: Question
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89270607
has comment: http://stackoverflow.com/comment/89048871
answer count: 2
linked to: http://stackoverflow.com/q/38381887

http://stackoverflow.com/a/51079186
type: Answer
answers question: http://stackoverflow.com/q/51078621
has comment: http://stackoverflow.com/comment/89147208
upvote count: 1
has body: You can use the list slicing, some_list[start:stop:step] winners_list = df['winner'].tolist() df1 = pd.DataFrame() df1['Team1'] = winners_list[0::2] df1['Team2'] = winners_list[1::2] Take the winners from df as list (you can also take as pandas.core.series.Series and use slicing but when you use it to create a data frame you will face issues because of indexing) Create a new dataframe and take the even indexed elements from winners list as Team1 Take the odd indexed elements from the winners list as Team2.
downvote count: 0
score: 1

http://stackoverflow.com/q/51034522
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89098967
has answer: http://stackoverflow.com/a/51058559
type: Question
has title: How to suppress/mute Maya script editor warning correctly with Python or Mel?
downvote count: 0
answer count: 1
favorite count: 0
has body: I need to open some large/messy Maya scenes from other artists. It always prompts out a lot of warnings and freezes Maya for a long time. I try to write a custom "open file" with python to suppress warning messages. But it seems not really "mute" script editor entirely. Let's say, when I open Hypershade window after open file, warnings prompt out again since I have lots of missing textures. The script I use now is: import maya.cmds as cmds import maya.mel as mel filename = cmds.fileDialog2(fileMode=1) reporter = mel.eval( 'string $tmp = $gCommandReporter;' ) cmds.scriptEditorInfo(reporter,suppressWarnings=True,suppressInfo=1,se=1,ch=1) cmds.disableIncorrectNameWarning() cmds.file( filename[0], i=True ); Thank you
has comment: http://stackoverflow.com/comment/89071057
tagged with: maya
tagged with: python
tagged with: mel
type: UnansweredQuestion

http://stackoverflow.com/comment/89084940
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51046398
has text: What did you try so far? Where exactly are you stuck?
score: 0

http://stackoverflow.com/comment/89190908
score: 0
type: Comment
type: QuestionComment
has text: You forgot to tell us the actual error you get, please edit your question to include a copy-paste (as text) the full and complete output.
comment on: http://stackoverflow.com/q/51101834

http://stackoverflow.com/comment/117399463
type: QuestionComment
has text: If the blocks are always the same length and line of interest is alway the Nth one in group, you don't need to use a regex to get them—there are simpler ways.
type: Comment
comment on: http://stackoverflow.com/q/51073045
score: 0

http://stackoverflow.com/q/51100149
tagged with: python
accepted answer: http://stackoverflow.com/a/51130694
type: AnsweredQuestion
has title: Resize images and merge data sets in python
type: Question
tagged with: deep-learning
has body: I have two datasets, images1 and images2(generated in the function below, by reading images in a loop via given path) def measure(images1,path): images2=[] for filename in glob.glob(path): #looking for pngs temp = cv2.imread(filename).astype(float) images2.append (augm_img) print(np.array(images2).dtype) print(np.array(images).dtype) print(np.array(images2).shape) print(np.array(images).shape) Prints outputs: float64 float64 (1, 24, 24, 3) (60000, 32, 32, 3) (2, 24, 24, 3) (60000, 32, 32, 3) (3, 24, 24, 3) (60000, 32, 32, 3) (4, 24, 24, 3) (60000, 32, 32, 3) .... .... etc After reading images from path i want to resize images2 read from file to same size as images (:,32,32,3) And merge these two datasets in one (via concatenate or append?) in order to train my model. Until now i cant find a way to do this so any advice would be helpful.
answer count: 1
tagged with: dataset
tagged with: training-data
has answer: http://stackoverflow.com/a/51130694
score: 0

http://stackoverflow.com/a/51056236
accepted answer of: http://stackoverflow.com/q/51055909
has body: From the Website you stated: Miscellaneous routines (scipy.misc) Various utilities that don’t have another home. So the use is to have a place to put routines, which do not necessarily fit somewhere else. Imagine it as a drawer where one puts all the things that one does not know where to put them, but one does not want to have them laying around in order to find them easier. For more detail you might want to take a closer look into the routines (into your drawer), in order to explore which functionalities are covered by scipy.misc
has comment: http://stackoverflow.com/comment/89140712
answers question: http://stackoverflow.com/q/51055909
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89142904

http://stackoverflow.com/comment/89151926
has text: i can write it for you but the point is your question is too global try something first and then ask in stackoverflow read django's docs
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51081572
score: 0

http://stackoverflow.com/q/51048004
has answer: http://stackoverflow.com/a/51048169
tagged with: javascript
answer count: 3
score: 3
favorite count: 0
tagged with: parsing
has title: Reading an Exported Javascript Object in Python
has answer: http://stackoverflow.com/a/77364503
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: Is it possible to read/parse an exported Javascript or Typescript JSON-like object in Python? For example: In myJava.js: export const myObj = { entry: val entry2: val2 ... } In parseJava.py: def parseJava(): # Some code to read in the javascript object javaObjAsDictionary = someFunction("myJava.js") Does such a "someFunction()" exist? If not, are there any clean ways around this? Thanks in advance!
has answer: http://stackoverflow.com/a/51048436
type: Question
upvote count: 4

http://stackoverflow.com/q/51097057
upvote count: 2
has title: python read bigger csv line by line
answer count: 3
downvote count: 1
has body: Hello i have huge csv file (1GB) that can be updated (server often add new value) I want in python read this file line by line (not load all file in memory) and i want to read this in "real time" this is example of my csv file : id,name,lastname 1,toto,bob 2,tutu,jordan 3,titi,henri in first time i want to get the header of file (columns name) in my example i want get this : id,name,lastname and in second time, i want read this file line by line not load all file in memory and in third time i want to try to read new value between 10 seconds (with sleep(10) for example) i search actualy solution with use pandas i read this topic : Reading a huge .csv file import pandas as pd chunksize = 10 ** 8 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk) but i don't unterstand, 1) i don't know size of my csv file, how define chunksize ? 2) when i finish read, how says to pandas to try to read new value between 10 seconds (for example) ? thanks for advance for your help
has answer: http://stackoverflow.com/a/51098313
has answer: http://stackoverflow.com/a/51098679
possible better answer: http://stackoverflow.com/a/51097239
has answer: http://stackoverflow.com/a/51097239
linked to: http://stackoverflow.com/q/17444679
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51098313
tagged with: pandas
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89181797
tagged with: python
has comment: http://stackoverflow.com/comment/89181985
linked to: http://stackoverflow.com/q/237079
favorite count: 0

http://stackoverflow.com/comment/89033334
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51020300
type: Comment
has text: There is no "best way", but this seems very common sense to me...

http://stackoverflow.com/q/51032155
has comment: http://stackoverflow.com/comment/127022989
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/1271320
has comment: http://stackoverflow.com/comment/127175917
score: -1
type: Question
has title: Why can a python generator only be used once?
linked to: http://stackoverflow.com/q/23416381
answer count: 1
has comment: http://stackoverflow.com/comment/127016685
has comment: http://stackoverflow.com/comment/127035138
has answer: http://stackoverflow.com/a/51032176
has body: Once I use a generator once, it can't be used again. Why is this? Consider the following code: def generator(n): a = 1 for _ in range(n): yield a a += 1 def run_generator(generator): for a in generator: print(a, end = " ") If I were to execute this: count_generator = generator(10) run_generator(count_generator) run_generator(count_generator) It would only print: 1 2 3 4 5 6 7 8 9 10 Basically, the generator just dies after a single execution. I know that the fact that a generator can only be used once is something built into Python, but why is it like this? Is there a specific reason to only allowing a generator object to be executed once?
accepted answer: http://stackoverflow.com/a/51032176
tagged with: python
upvote count: 4
favorite count: 0
tagged with: generator
has comment: http://stackoverflow.com/comment/89056829
linked to: http://stackoverflow.com/q/1756096
has comment: http://stackoverflow.com/comment/89057463
downvote count: 5
duplicate of: http://stackoverflow.com/q/25336726

http://stackoverflow.com/a/51022617
type: Answer
has comment: http://stackoverflow.com/comment/89038755
has comment: http://stackoverflow.com/comment/89038442
has comment: http://stackoverflow.com/comment/89037855
has body: Since you are interested in the status code of the ping command call the using of the subprocess.check_call would be more appropriate. Also, pass args as the list instead of string, that's preferred way of calling bash command from python, please see the body of the while loop below: try: # I've added -i and -c flags for fast ping command. Run `man ping` in terminal for flags description. subprocess.check_call(['ping', '-c', '5', '-i', ' 0.2', ip]) except subprocess.CalledProcessError: Pingisdown(ip) # NOTE: Update to process only ip. else: print (ip+ " is up") Please let me know if the error won't disappear after applying suggested handling.
has comment: http://stackoverflow.com/comment/89038137
answers question: http://stackoverflow.com/q/51022298
has comment: http://stackoverflow.com/comment/89037758
has comment: http://stackoverflow.com/comment/89037914
score: 0

http://stackoverflow.com/q/51155511
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89312692
upvote count: 1
has comment: http://stackoverflow.com/comment/89297616
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51192348
has body: I'm having this error sometimes: Fatal Python error: (pygame parachute) Segmentation Fault This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Some times when a run the program I received this error, but I received this error before use the pygame, and the try,except doesn't catch nothing. I'm making a program with this configuration. I do not know what else to do, please help.: Windows 10 64bits python 2.7 64bits pygame. __version__: '1.9.3' Tkinter.__version__: '$Revision: 81008 $' ttk.__version__: '0.3.1' pickle.__version__: '$Revision: 72223 $' pyserial.__version__: '2.7'
tagged with: pyserial
answer count: 1
downvote count: 0
has title: Fatal Python error: (pygame parachute) Segmentation Fault nothing work
score: 1
favorite count: 0
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/89166592
type: Comment
type: QuestionComment
has text: The test isn't passing: `Ran 0 tests in ...` it didn't run your test case. Can you post your full test script as well as how you're invoking it?
comment on: http://stackoverflow.com/q/51089099
score: 9

http://stackoverflow.com/a/65412950
answers question: http://stackoverflow.com/q/51114729
downvote count: 0
has body: This is an issue that was due to missing plural forms in en translation catalogs. As a result django was inserting "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" as a default (which isn't valid syntax). It was fixed when django 2.0 was released. See this issue for details. For anyone having problems with this, it may be worth checking your version of django, and updating if necessary.
type: AcceptedAnswer
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51114729

http://stackoverflow.com/comment/89320372
score: 0
type: Comment
has text: just add a field to the document, but the value of the field comes from the document it self.
type: AnswerComment
comment on: http://stackoverflow.com/a/51166748

django-forms
tags question: http://stackoverflow.com/q/51045926
tags question: http://stackoverflow.com/q/51066703
tags question: http://stackoverflow.com/q/51040472
tags question: http://stackoverflow.com/q/51139051
tags question: http://stackoverflow.com/q/51157296
tags question: http://stackoverflow.com/q/51033515
tags question: http://stackoverflow.com/q/51034802
tags question: http://stackoverflow.com/q/51034526
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/51163017
tags question: http://stackoverflow.com/q/51162146
tags question: http://stackoverflow.com/q/51053509
tags question: http://stackoverflow.com/q/51050277
tags question: http://stackoverflow.com/q/51081730
tags question: http://stackoverflow.com/q/51054301
tags question: http://stackoverflow.com/q/51166801
tags question: http://stackoverflow.com/q/51155248
tags question: http://stackoverflow.com/q/51090505
tags question: http://stackoverflow.com/q/51012506
tags question: http://stackoverflow.com/q/51013909
tags question: http://stackoverflow.com/q/51082873

http://stackoverflow.com/comment/89242492
type: Comment
type: QuestionComment
has text: That _looks_ like an Angular issue. And no, `django-compressor` is not installed by default unless it is installed by a third party library.
comment on: http://stackoverflow.com/q/51128831
score: 0

http://stackoverflow.com/comment/89077881
has text: Seems like what you are trying to manipulate is already a Python dictionary. Did you try to print it?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51043464

http://stackoverflow.com/comment/89103447
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51056095
has text: "the method `change` gets a REFERENCE to the class variable `variable`" - no, it gets a reference to a string object. `variable` also has a reference to that string object. Rebinding one reference doesn't affect the other. Python references only refer to objects, not variables.

http://stackoverflow.com/comment/89252484
has text: how do you `nn.init` your weights?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51102220

http://stackoverflow.com/a/51159280
accepted answer of: http://stackoverflow.com/q/51139009
type: Answer
has body: Reason why you sometimes get URI to data result and not actual data result is that the data result is not yet ready. It sometimes takes a while to compute report. Besides the URI you also get HTTP status 202. It means that request was accepted, but result is not done yet. Check HTTP status with getcode() method. If you get 202, request the URI again until you get 200 and then read data result.
answers question: http://stackoverflow.com/q/51139009
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51159898
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89304430
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/89303900
type: Question
has comment: http://stackoverflow.com/comment/89306274
has comment: http://stackoverflow.com/comment/89303153
has title: Find numbers after a string "Quote" in a dataframe column
has answer: http://stackoverflow.com/a/51159981
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51161434
downvote count: 0
has comment: http://stackoverflow.com/comment/89303151
favorite count: 0
possible better answer: http://stackoverflow.com/a/51159981
accepted answer: http://stackoverflow.com/a/51161434
has comment: http://stackoverflow.com/comment/89303391
tagged with: python
has body: I have a customer care call log in an excel sheet. Below is the format of the data i have So# Comments 1 sjhsh QUOTE 234566 1 sdsds customer call QUote 239876 Call back 2 adsdfh unknown call from customer QUOTE 189067 sdkjsd woieweio 3 QUOTE 657894 customer called for service I am reading this data from excel and need to get 6 digits afetr the text "QUOTE" in each row and then add the extracted digits as a new column 1.The rows might have multiple "QUOTE" mentions 2.The rows might not have "QUOTE"at all Can someone please help me out with this substring search using python import pandas as pd import re file=pd.read_excel("C:/Users/rkatta/Desktop/Book1.xlsx") file.set_index('Index', inplace=True, drop=True) comments=file['InternalComments'] quotenum=[] keyword= 'QUOTE' for i in comments: try: befor_keyowrd, keyword, after_keyword = comments[i].partition(keyword) num=after_keyword[:6] quotenum.append(num) except AttributeError: befor_keyowrd, keyword, after_keyword ='' quotenum.append(after_keyword)
tagged with: regex

http://stackoverflow.com/comment/89244849
has text: https://drive.google.com/file/d/1tfL33lfvtKN5vfFwmWbTypMHoC_VO462/view?usp=sharing When i implemented your method, Calender is not showing in DateField and time field is showing which is not required. You can see the screenshot in the google drive link above.Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/51117032
score: 0
type: Comment

http://stackoverflow.com/comment/89149360
comment on: http://stackoverflow.com/q/51080445
has text: self check if the attribute in the instance then in the class
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89361132
type: Comment
type: QuestionComment
has text: Great! Why don't you post this as an answer below? It might help someone else!
comment on: http://stackoverflow.com/q/51164056
score: 0

http://stackoverflow.com/a/51125111
accepted answer of: http://stackoverflow.com/q/51125082
type: AcceptedAnswer
downvote count: 0
has body: We can convert the dataframe df to a list of dictionaries with: df_dicts = df.T.to_dict().values() But of course that does not give us fully the requested format, nor is this a JSON blob. But we can use this as a base to extend it. We can for example wrap every dictionary into another dictionary by performing a mapping: result = list(map(lambda x: {'model': 'profiles.track', 'fields': x}, df_dicts)) Finally we can construct a JSON blob with: import json json_blob = json.dumps(result) This will construct a string that is a JSON dump of result. We can for example print it with: print(json_blob)
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51125082

http://stackoverflow.com/comment/89080314
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51043573
has text: your `PolynomialFeatures` preprocessor should be able to construct the polynomials for the Linear Regression for you. There even might be some preprocessor for combining features. btw. the number of coefficients should equal the number of features you put into your model.
score: 0

http://stackoverflow.com/comment/89095123
has text: Sorry that this was unclear, as honestly I'm having trouble figuring out what to do. I'm aware that the quotes makes the expression a string, I just put those there to show that I'm fine with anything in that section being changed. I'm also not checking for the key "K", that signifies Key Up. The problem is that pygame has pretty specific keys and they're not strings as far as I can tell so I can't have the user enter something and then deal with their input that way. Essentially I'm trying to convert user input to something pygame will recognise.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51051236
type: Comment

http://stackoverflow.com/q/51048972
has comment: http://stackoverflow.com/comment/89089237
has answer: http://stackoverflow.com/a/51049032
has comment: http://stackoverflow.com/comment/89089326
tagged with: python
has comment: http://stackoverflow.com/comment/89089945
has body: Is there any way to declare such static variables in java by which I can return java object after their initialization for example We can do this in python like this schedule.every(10).minutes.do(job) Where, by calling every(10). minutes I just initialize minutes variable. Is it possible to do such things in java too? Something like this: Myclass.function().variable.anothorFunction(); EDIT: As in case of methods, I can easily do this in java too like this. public static MyClass function(){ return new MyClass(); }
has comment: http://stackoverflow.com/comment/89089275
has comment: http://stackoverflow.com/comment/89089117
has comment: http://stackoverflow.com/comment/89090284
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/231767
score: 1
has comment: http://stackoverflow.com/comment/89089806
has comment: http://stackoverflow.com/comment/89089975
has comment: http://stackoverflow.com/comment/89089818
tagged with: java
has comment: http://stackoverflow.com/comment/89089252
has comment: http://stackoverflow.com/comment/89090527
linked to: http://stackoverflow.com/q/33073671
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89089826
accepted answer: http://stackoverflow.com/a/51049032
has comment: http://stackoverflow.com/comment/89089680
has comment: http://stackoverflow.com/comment/89089870
linked to: http://stackoverflow.com/q/1052476
possible better answer: http://stackoverflow.com/a/51049376
tagged with: static-methods
has answer: http://stackoverflow.com/a/51049376
answer count: 2
has comment: http://stackoverflow.com/comment/89090046
has comment: http://stackoverflow.com/comment/89089948
has comment: http://stackoverflow.com/comment/89090400
has title: How to return object while initializing variable in java?
favorite count: 0
tagged with: static
has comment: http://stackoverflow.com/comment/89089900
upvote count: 2
has comment: http://stackoverflow.com/comment/89089954

http://stackoverflow.com/comment/90178080
type: AnswerComment
type: Comment
has text: I was able to download the .whl file but was unfamiliar with installing .whl files. To install the downloaded package simply run: python -m pip install C:\PathToWHLFile\filename.whl. (https://stackoverflow.com/questions/27885397/how-do-i-install-a-python-package-with-a-whl-file)
score: 3
comment on: http://stackoverflow.com/a/51118443

http://stackoverflow.com/q/51100057
score: 4
upvote count: 4
has title: keras list of Numpy arrays not the size model expected
has answer: http://stackoverflow.com/a/51100984
answer count: 1
downvote count: 0
tagged with: keras
has body: I am having trouble finding the correct way of passing multiple inputs to a model. The model has 2 inputs noise image of shape (256, 256, 3) input image of shape (256, 256, 3) and 1 output output image of shape (256, 256, 3) I am producing the images via ImageDataGenerator: x_data_gen = ImageDataGenerator( horizontal_flip=True, validation_split=0.2) And I am producing the samples via a python generator: def image_sampler(datagen, batch_size, subset="training"): for imgs in datagen.flow_from_directory('data/r_cropped', batch_size=batch_size, class_mode=None, seed=1, subset=subset): g_y = [] noises = [] bw_images = [] for i in imgs: # append to expected output the original image g_y.append(i/255.0) noises.append(generate_noise(1, 256, 3)[0]) bw_images.append(iu_rgb2gray(i)) yield(np.array([noises, bw_images]), np.array(g_y)) When trying to train the model with: generator.fit_generator( image_sampler(x_data_gen, 32), validation_data=image_sampler(x_data_gen,32,"validation"), epochs=EPOCHS, steps_per_epoch= 540, validation_steps=160 ) I receive an error stating: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays while the message is quite clear, I do not understand how to fix the generation process to solve it. I tried: yield([noises, bw_images], np.array(g_y)) but this didn't work as it would reach a different error: AttributeError: 'list' object has no attribute 'shape' what am I missing?
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51100984
tagged with: machine-learning
tagged with: tensorflow
type: Question
tagged with: neural-network

http://stackoverflow.com/a/51130196
accepted answer of: http://stackoverflow.com/q/51126928
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51126928
has body: "No constant is added by the model unless you are using formulas." Therefore try something like below example. Variable names should be defined according to your data set. Use, regressor_OLS = smf.ols(formula='Y_variable ~ X_variable', data=df).fit() instead of, regressor_OLS = sm.OLS(endog=y, exog=X).fit()
has comment: http://stackoverflow.com/comment/89257109
type: Answer
score: 5
upvote count: 5

http://stackoverflow.com/comment/89309829
has text: try: `df.groupby('Month_of_Year')['CallsPresented'].mean()`
comment on: http://stackoverflow.com/q/51163175
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51033776
tagged with: tkinter
has body: I'm writing one of my first programs, and I can't figure out how to fix this issue. I started learning Python like a week ago and am still very new to Tkinter and OOP in general. I got this script (D&amp;D NPC Generator) working without using OOP, but I wanted to see how to do it with OOP since that's how most people seem to prefer using Tkinter. Here's the code for the Input window: class Input: def __init__(self, master): ideals = ["Good", "Evil", "Lawful", "Chaotic", "Neutral", "Other"] ideal_selection = StringVar() ideal_selection.set(ideals[0]) self.name_label = Label(master, text="NPC Name: ") self.name_entry = Entry(master) self.ideal_label = Label(master, text="Ideal Type: ") self.ideal_entry = OptionMenu(master, ideal_selection, *ideals) self.submit_button = Button(text="Submit", command=self.close_window) self.name_label.grid(row=0, column=0) self.name_entry.grid(row=0, column=1) self.ideal_label.grid(row=1, column=0) self.submit_button.grid(columnspan=2, row=3, column=0) self.ideal_entry.grid(row=1, column=1) def close_window(self): global name global ideal_type name = self.name_entry.get() ideal_type = self.ideal_selection.get() self.master.destroy() And it's returning: AttributeError: 'Input' object has no attribute 'ideal_selection' I have no idea what's going wrong. My goal with this GUI window is to have the user type in a name for the NPC and then select an option from a drowbown menu for what kind of ideal the user wants the NPC to have. A fix and explanation of what I did wrong would be very helpful, thank you.
type: Question
accepted answer: http://stackoverflow.com/a/51033848
has title: Trying to Return an Input from a Dropdown Menu to a Variable in Tkinter
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51033848
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51065953
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51065375
has comment: http://stackoverflow.com/comment/89121878
has comment: http://stackoverflow.com/comment/89122118
has body: You need to use .idxmax() to get the first occurance of string1 and then slice to that position. history = dfx.iloc[:(dfx['col1']==v1).idxmax()+1] Output: col1 0 abc 1 bcd 2 string1
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51065375

http://stackoverflow.com/a/51121761
accepted answer of: http://stackoverflow.com/q/51121661
answers question: http://stackoverflow.com/q/51121661
type: Answer
score: 21
upvote count: 21
type: AcceptedAnswer
downvote count: 0
has body: filter() with multiple parameters joins them with AND statements: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filter To perform OR queries in django you can use Q objects: from django.db.models import Q ticket_query = request.event.tickets.filter(Q(status='on-sale') | Q(status='paused')).prefetch_related('ticket_tax') More details here: https://docs.djangoproject.com/en/2.0/topics/db/queries/#complex-lookups-with-q

http://stackoverflow.com/a/62238326
score: -1
downvote count: 2
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51125696
has body: if args.mode == "train": # Load Data data, labels = load_dataset('C:/Users/PC/Desktop/train/k') # Train ML models knn(data, labels,'C:/Users/PC/Desktop/train/knn.pkl' )
has comment: http://stackoverflow.com/comment/125860159

http://stackoverflow.com/comment/89303685
type: QuestionComment
comment on: http://stackoverflow.com/q/51157679
score: 0
type: Comment
has text: @Tim Is the error code same because the last time you said it was same, it was actually different.

http://stackoverflow.com/a/51021070
downvote count: 0
has body: The first answer is that the species names does not exist. You can check that on the ncbi website. like here: https://www.ncbi.nlm.nih.gov/search/?term=Stereum+rameale https://www.ncbi.nlm.nih.gov/search/?term=vibrio_lutjanus Vibrio lutjanus seems not existing anyways if you look at other websites. For example https://www.arb-silva.de/search/ or There is no solution to overcome this (in case of finding taxon id's), but you could do a double check if the name is right. Taxonomy is difficult, every body gives a different name and there are lots of synonyms. You can use the api's of taxonomic name website's like gbif or global names. [EDIT] You can also check the taxon id of the genus if species is not available. Here you can download the taxonomy information of the NCBI: ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/new_taxdump/ You need to download the zip file and probably need the files rankedlineage.dmp and merged.dmp The global names website can also be used for genus level. Dont know if entrez from BioPython can look up id's of genus level maybe that is also an option.
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51020376
answers question: http://stackoverflow.com/q/51020376
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51165569
has answer: http://stackoverflow.com/a/51306836
tagged with: trumbowyg
tagged with: django
answer count: 1
has comment: http://stackoverflow.com/comment/89315051
upvote count: 5
tagged with: javascript
has comment: http://stackoverflow.com/comment/89318370
accepted answer: http://stackoverflow.com/a/51306836
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89421301
favorite count: 0
tagged with: ajax
has body: I'm using Trumbowyg, a WYSIWYG JavaScript editor which has a feature of rendering images from URLs pasted in. It also has an upload plugin which enables uploading local images and custom server side handling. My python/django function upload_image() can successfully detect the uploaded image - however when I use the URL image input, my python function cannot detect it. Trumbowyg simply renders the image without going through my python backend. Here's my code: $('#id_content').trumbowyg({ btnsDef: { // Create a new dropdown image: { dropdown: ['insertImage', 'upload'], ico: 'insertImage' } }, // Redefine the button pane btns: [ ['strong', 'em', 'del'], ['link'], ['image'], // Our fresh created dropdown ], plugins: { // Add imagur parameters to upload plugin for demo purposes upload: { serverPath: '/upload_image/', fileFieldName: 'content_image', urlPropertyName: 'url' } } }); def upload_image(request): print('Success') #only prints when I use the upload input, not the URL input Why can in detect the uploaded image but not the URL input?
type: Question
score: 5
tagged with: python
has title: Trumbowyg: Django server can detect file upload but not image URL input
has comment: http://stackoverflow.com/comment/89421150

http://stackoverflow.com/comment/89310464
score: 0
comment on: http://stackoverflow.com/q/51163400
type: QuestionComment
type: Comment
has text: Its a LocalDb - my bad for not clarifying. Was not fully aware of all that was in your link, taking it all in now.

http://stackoverflow.com/a/76468432
has comment: http://stackoverflow.com/comment/134870585
has comment: http://stackoverflow.com/comment/138943270
score: 0
has comment: http://stackoverflow.com/comment/138921022
answers question: http://stackoverflow.com/q/51131834
type: Answer
has body: as pointed in this stackoverflow response link, just adding '==' at the end of the string will do the trick
has comment: http://stackoverflow.com/comment/138943752

http://stackoverflow.com/q/51084206
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: Using Python, I want to search for a text string in Col2 based on Col1. So in the example below, if the text/string is 9880, then in Col2 I want to search for text with 9880.xxx and then extract it to a new row in a new column. I want to be able to do this for multiple rows. The example below is contained all in one Excel row, and therefore the text in col2 is all in one Excel cell. Example: data in Excel Col1 Col2 9880 | line of text | single | 9880.01 | Excel | line of text | row | 9880.02 | | line of text | | 9880.03 | New column: Colx Excel row1 9880.01 Excel row2 9880.02 Excel row3 9880.03 I know how to read Excel data and save it to a dataframe and write back to Excel. It's the search and and extract part I need help with. Maybe I could pull it off using Pandas split command, then melt, and then followed by Groupby. I tried to look for similar examples in Stack overflow, but something that was sort of close was here: Python - Extract text from string. Everything else was related to using VBA. Any suggestions are appreciated. Edited 06/28/2018: I think I can achieve this by using the 'findall' command, but not sure on how to construct the for loop so that it could go to the next item in the dataframe as read in from Excel. Perhaps use enumerate from the list that I am searching through. 9880 'line of text' 9450 'line of text' 4530 'line of text'
tagged with: python
downvote count: 0
answer count: 0
score: 1
has title: python Want to extract text/string from Excel cell based on string/text from another cell
tagged with: excel
type: Question
linked to: http://stackoverflow.com/q/40458087
tagged with: pandas

http://stackoverflow.com/q/51087300
accepted answer: http://stackoverflow.com/a/51087383
tagged with: python
tagged with: request
type: AnsweredQuestion
type: Question
has title: Python request behaviour
has body: I want to check if a website exists. I use the request module to make a get request and check the status code after the request was made. def check_website_exist(self, url): result = True request = requests.get("http://"+url) print(request.status_code) if request.status_code == 200: output.info("website found!") return result else: output.error("website not found!") result = False return result When I make a request for the site 'www.isdfugpdohsiughsdopiughdsfoiguf.com' I get the status code 200, even though the site doesn't exists. Why do I get a 200 status code, but the website doesn't exist?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89163120
has comment: http://stackoverflow.com/comment/89163202
tagged with: http-status-code-200
has answer: http://stackoverflow.com/a/51087383

http://stackoverflow.com/comment/89114291
comment on: http://stackoverflow.com/a/51059066
type: AnswerComment
has text: @nrvaller - reason is I need same values per negatives rows, so need cumulative sum for positive values for grouping by it.
type: Comment
score: 1

http://stackoverflow.com/q/51084661
upvote count: 1
has comment: http://stackoverflow.com/comment/89160701
has title: Extract the specific columns and strings from a file using linux or python
possible better answer: http://stackoverflow.com/a/51084861
favorite count: 0
tagged with: pattern-matching
score: 0
tagged with: linux
tagged with: bioinformatics
tagged with: python
has comment: http://stackoverflow.com/comment/89157854
type: AnsweredQuestion
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51087991
has body: I have encountered a problem when dealing with a 12 Gb file. I'm a newbie when it comes to linux. I hope someone here could help me, any suggestions are appreciated. I have a file named phase_3.vcf which is like these: ##INFO=&lt;ID=EAS_AF,Number=A,Type=Float,Description="Allele frequency in the EAS populations"&gt; ##INFO=&lt;ID=EUR_AF,Number=A,Type=Float,Description="Allele frequency in the EUR populations"&gt; ##INFO=&lt;ID=AFR_AF,Number=A,Type=Float,Description="Allele frequency in the AFR populations"&gt; ##INFO=&lt;ID=AMR_AF,Number=A,Type=Float,Description="Allele frequency in the AMR populations"&gt; ##INFO=&lt;ID=SAS_AF,Number=A,Type=Float,Description="Allele frequency in the SAS populations"&gt; #CHROM POS ID REF ALT QUAL FILTER INFO 1 10177 rs367896724 A AC . . dbSNP_150;E_Freq;E_1000G;EAS_AF=0.3363;SAS_AF=0.4949;AFR_AF=0.4909 1 10235 rs540431307 T TA . . dbSNP_150;E_Freq;E_1000G;EAS_AF=0.0000;AMR_AF=0.0014; 1 10352 rs555500075 T TA . . dbSNP_150;EAS_AF=0.4306;EUR_AF=0.4264;SAS_AF=0.4192; 1 10505 rs548419688 A T . . TSA=SNV;E_Freq;EAS_AF=0.0000;AMR_AF=0.0000;AFR_AF=0.0008 1 10506 rs568405545 C G . . dbSNP_150;TSA=SNV;MA=G;MAF=0.000199681;EAS_AF=0.0000; And I wanna keep the first 5 columns and the strings "EAS_AF=" and the numbers followed them. To make it simple, the expected form of the outcome named result.txt should be like these: #CHROM POS ID REF ALT INFO 1 10177 rs367896724 A AC EAS_AF=0.3363 1 10235 rs540431307 T TA EAS_AF=0.0000 1 10352 rs555500075 T TA EAS_AF=0.4306 1 10505 rs548419688 A T EAS_AF=0.0000 1 10511 rs534229142 G A EAS_AF=0.0000 1 10539 rs537182016 C A EAS_AF=0.0000
tagged with: vcf-variant-call-format
has answer: http://stackoverflow.com/a/51084861
answer count: 2
has answer: http://stackoverflow.com/a/51087991

http://stackoverflow.com/comment/89185865
comment on: http://stackoverflow.com/a/51080557
type: Comment
has text: the problem is that those data sets are results of mongodb aggregation functions, they are in fact cursors, I don't know how to exploit them as dicts
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89276264
type: Comment
comment on: http://stackoverflow.com/a/51145687
type: AnswerComment
score: 0
has text: Very interesting ... how does one turn a list of `strings` in `dirs` into the `iterable` required by `shy_snake`?

http://stackoverflow.com/q/51052785
tagged with: python
answer count: 0
tagged with: pytorch
type: UnansweredQuestion
type: Question
has body: I’m trying to implement a character RNN for the purpose of spell correction and tokenization. The model is based on the practical pytorch GRU-RNN implementation of a seq2seq model - the loss function is masked cross entropy like they use here and I’m using a 2 layer bidirectional GRU for my encoder/decoder. I am also using scheduled sampling with a teacher forcing ratio of 0.5. The problem I’m having is that the system is struggling to output end tokens. Sentences such as ‘do3s t4is w0rk’ are being correctly changed to ‘does this work’, but then random tokens are outputted until either the system reaches it’s max output length or seemingly randomly puts down an EOS token, making the output something like ‘does this workkkkkk orwk EOS’. Does anyone have any insight into this problem? I tried unmasking my loss function but this lead to the system outputting PAD tokens now. The system is able to overfit very easy sets so I don’t think there’s a bug in the training. Any input would be appreciated!
tagged with: seq2seq
tagged with: recurrent-neural-network
has title: Pytorch Spell Check Character RNN not outputting end tokens
score: 0
tagged with: spell-checking
has comment: http://stackoverflow.com/comment/89115133
has comment: http://stackoverflow.com/comment/89096742

http://stackoverflow.com/q/51124815
has comment: http://stackoverflow.com/comment/89234756
has comment: http://stackoverflow.com/comment/89234728
has title: running a nested loop on a list of unknown length
type: Question
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89234727
favorite count: 0
has comment: http://stackoverflow.com/comment/89234667
has answer: http://stackoverflow.com/a/51125199
score: 0
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89234615
type: UnansweredQuestion
has body: I have defined a list as: comp = [] comp.append(["A", "B", "C", "D"]) comp.append(["E", "F", "I"]) In real case, I don't know the length of comp or comp[x] Now, I am trying to run a nested loop on this, but failed. What I mean is, if I run my current snippet: for compsi in range(len(comp)): for elemn in range(len(comp[compsi])): print(comp[compsi][elemn]) the output is A B C D E F I. What I am trying is, for each element of comp[0], the full comp[1] will run, so that, I will get: A E F I B F I C F I D E F I and so; When I know I len(comp) = 2, I can easily do this using nested for loop as: for lo in range(len(comp[0])): for l1 in range(len(comp[1])): print(...) But, how I can achieve the same when I don't know the lenght of comp? Kindly help! Ok, say, we have comp=[['A', 'B', 'C', 'D'], ['E', 'F', 'G'], ['H'], ['I', 'J','K']]. We will end up with: A E H I A E H J A E H K A F H I ... B E H I B E H J B E H K ... D G H K in this way.
tagged with: list

http://stackoverflow.com/comment/89130776
comment on: http://stackoverflow.com/a/51070265
score: 0
type: AnswerComment
type: Comment
has text: What's the benefit of doing that over putting it in the closure?

http://stackoverflow.com/comment/89213746
has text: You should know that virtual memory is not the memory a process uses. It is the address space the OS offers to it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51113122

http://stackoverflow.com/a/51110857
has body: To check firewall status run $ ufw status Please show you URL_BASE without real IP. What operating system is on your server? You send test request from the CURL to URL of the Telegram or of your server? Can you getting response from your server if you run simple app? Example: from aiohttp import web async def hello(request): return web.Response(text='Hello world!') app = web.Application() app.add_routes([web.get('/', hello)]) web.run_app(app, host='localhost', port=3003) Check response: $ curl localhost:3003 Hello world! Please provide more detailed information on how you troubleshoot.
answers question: http://stackoverflow.com/q/51108826
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89230881

http://stackoverflow.com/comment/89335783
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51160343
has text: Can you provide the paper?
score: 0

http://stackoverflow.com/comment/89021631
score: 0
type: Comment
has text: I apologize the error from flask was an input error
type: QuestionComment
comment on: http://stackoverflow.com/q/51014386

http://stackoverflow.com/comment/89133320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51068439
score: 0
has text: This works for me.. **Check your development environment** [![telethon install](https://i.sstatic.net/Ab7Wg.png)](https://i.sstatic.net/Ab7Wg.png)

http://stackoverflow.com/comment/89196420
type: Comment
comment on: http://stackoverflow.com/a/51101313
score: 0
type: AnswerComment
has text: The performance of sets is way better than lists. I got what I wanted, thanks!

http://stackoverflow.com/comment/89267308
has text: When you create the table, you need to include a column like `id INT AUTOINCREMENT`
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51141455
type: QuestionComment

http://stackoverflow.com/comment/89023890
has text: also, just to clarify, I am able to programmatically make trades with 100% success in other situations. When I trade USDT for ETH using the same functions I am not having any issues at all.
comment on: http://stackoverflow.com/q/51014226
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51012542
has body: Working on Linux with python 3.5 Assume sbdart is executable and we have a file called output1.csv sbdart looks like this for our test case: echo $1 echo "$(cat $1)" output1.csv is as follows: &amp;INPUT WLINF = 0.250 WLSUP = 4.0 WLINC = 0.5 IDAY = 289 ALAT = {row['Lat']} ALON = {row['Long']} IDATM = 3 ISALB = 5 IAER = 5 WLBAER = .500,.675,.870,.936,1.02 WBAER = 5*0.9 GBAER = 5*0.8 TIME = {row['sama']} QBAER = {','.join(extinction_pct(row))} ZOUT = 0.0,15.0 / &gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.check_output(['./sbdart output1.csv'],shell=True) b"output1.csv\n&amp;INPUT\nWLINF = 0.250\nWLSUP = 4.0\nWLINC = 0.5\nIDAY = 289\nALAT = {row['Lat']}\nALON = {row['Long']}\nIDATM = 3\nISALB = 5\nIAER = 5\nWLBAER = .500,.675,.870,.936,1.02\nWBAER = 5*0.9\nGBAER = 5*0.8\nTIME = {row['sama']}\nQBAER = {','.join(extinction_pct(row))}\nZOUT = 0.0,15.0\n/\n" &gt;&gt;&gt;
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51011742

http://stackoverflow.com/q/51042768
has body: I've found the following definition in the docs but it's still not clear to me: Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value Do you have any examples?
tagged with: python
tagged with: valueerror
upvote count: 2
type: UnansweredQuestion
has title: What is a ValueError
has answer: http://stackoverflow.com/a/51042840
has comment: http://stackoverflow.com/comment/89076482
score: -2
type: Question
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/89076515
favorite count: 0
has answer: http://stackoverflow.com/a/51042863
tagged with: python-3.x

http://stackoverflow.com/a/51066237
type: Answer
score: 2
upvote count: 2
has body: by giving a direct path to the gpg home directory and to the gpg binary location within my python script like this gpg = gnupg.GPG(gnupghome="C:\path_to_gnupg" ,gpgbinary="C:\path_to_gpg.exe") the service was able to run directly. It must have been having troubles locating the secret keys on its own.
downvote count: 0
answers question: http://stackoverflow.com/q/51044613

http://stackoverflow.com/q/51145774
tagged with: python-3.x
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/3751791
has body: I am using PyDev in Eclipse on Windows to write code in Python 3.6.5. I get an error when running this single line of code: print("•") This is the error I get: SyntaxError: Non-UTF-8 code starting with '\x95' in file C:\Users\short\workspace\Python Test 4\src\foo.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details I thought Python 3.6 was supposed to make UTF-8 the default encoding. What am I doing wrong?
has answer: http://stackoverflow.com/a/51145827
accepted answer: http://stackoverflow.com/a/51145827
type: AnsweredQuestion
type: Question
has title: Printing Unicode Character in Python 3.6.5
answer count: 2
possible better answer: http://stackoverflow.com/a/51145815
upvote count: 1
has answer: http://stackoverflow.com/a/51145815
favorite count: 0
tagged with: python
tagged with: utf-8

http://stackoverflow.com/a/51160143
score: 14
has comment: http://stackoverflow.com/comment/89305453
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89305538
type: Answer
answers question: http://stackoverflow.com/q/51159672
upvote count: 14
accepted answer of: http://stackoverflow.com/q/51159672
has body: Spark can have difficulty dealing with object datatypes. A potential workaround is to convert everything to a string first: sdf = sqlCtx.createDataFrame(df.astype(str)) One consequence of this is that everything, including nan will be converted to string. You will need to take care to properly handle these conversions and cast the columns to the appropriate type. For instance, if you had a column "colA" with floating point values, you can use something like the following to convert the string "nan" to a null: from pyspark.sql.functions import col, when sdf = sdf.withColumn("colA", when(col("colA") != "nan", col("colA").cast("float")))

http://stackoverflow.com/comment/89100468
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51050622
has text: Can you give an example of what you are looking for?
type: Comment

http://stackoverflow.com/comment/89117735
type: Comment
type: AnswerComment
has text: What is `ui` in this context?
comment on: http://stackoverflow.com/a/51063758
score: 0

http://stackoverflow.com/a/51089402
has body: You can print the encoded_string to the console, copy it from there and paste it into your code. The encoded_string will look something like: 'R0lGODlhUABFAHAAA ... Qiq0Z1q2XN6oYYoQIBAQA7' Use it in code like this example: import tkinter as tk image_string = 'R0lGODlhUABFAHAAA ... Qiq0Z1q2XN6oYYoQIBAQA7' root = tk.Tk() imgFrame = tk.Frame(root) imgFrame.pack() img = tk.PhotoImage(data=image_string) imgLabel = tk.Label(imgFrame, image=img) imgLabel.pack()
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51088946
has comment: http://stackoverflow.com/comment/89167271
has comment: http://stackoverflow.com/comment/89172723
accepted answer of: http://stackoverflow.com/q/51088946
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51167595
has body: The error message / traceback points you to the place where the error was detected, not necessarly the point where it really happens. We can't reproduce the error since you didn't post a proper MCVE (we don't know what's in your data) but chances are the real problem is actually in one of the numerous other values concatenated from data upper in the code (remember that for python the whole deployment = deployment + '''(...)''' is a single statement. But anyway: you're doing it wrong right from the start. Instead of concatenation, you want to use string formatting operations, which are much more readable AND will take care of the necessary conversions.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89318253
answers question: http://stackoverflow.com/q/51167397
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89274515
type: AnswerComment
comment on: http://stackoverflow.com/a/51145085
type: Comment
score: 0
has text: you are right. what if I want to filter the records on the second column value larger than 2?

http://stackoverflow.com/q/51046440
has title: pyqt4: connect a slider to refresh a plot
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45090982
tagged with: python
has answer: http://stackoverflow.com/a/51049411
score: 0
has comment: http://stackoverflow.com/comment/89084370
type: Question
has body: I am trying to design a GUI to refresh a plot i.e. plot(timeS, dataS), using a slider corresponding to the time vector (timeS) of the data that I want to display (dataS) which is varying in time. I have tried to connect the slider to my plot function which has a lot of input self.slider.valueChanged.connect(self.myPlotFunction(.....)), which is located in the init part of my class, but I can't use the input of the defined function myPlotFunction(). So I want that when I start dragging the slider, the plot changes according to the time/position of the slider. Moreover my time vector is made of floats while the slider allows int values.
tagged with: pyqt4
tagged with: pyqt
answer count: 1

http://stackoverflow.com/q/51127307
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: mojibake
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51127373
score: 1
has comment: http://stackoverflow.com/comment/89239683
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89239658
type: Question
has body: I'm using Python's requests.get() to get some Facebook profiles HTML. Some of them redirect the request to a new url. When this new url has special characters, such as 'á', the request.get() method enters a redirect loop until an exception is raised. I found a workaround to correct the redirect url string, found in the response header under the "Location" key, but it is far from an elegant solution. import requests # This case works. Response [200] r = requests.get('https://www.facebook.com/profile.php?id=4') print(r) # This fails. Redirect location has special characters. # raises requests.exceptions.TooManyRedirects: Exceeded 30 redirects. not_working_url = 'https://www.facebook.com/profile.php?id=100010922979377' try: r = requests.get(not_working_url) except Exception as e: print(e) # Exceeded 30 redirects. # Workaround r = requests.get(not_working_url, allow_redirects=False) redirect_url = r.headers["Location"] print(redirect_url) # "https://www.facebook.com/people/TomÃ¡s-Navarro-Febre/100010922979377" # Special character 'á' on "/Tomás_Navarro_Febre/" is displayed as 'Ã¡'. # This fixes the string. redirect_url = redirect_url.encode('raw_unicode_escape').decode('utf-8') print(redirect_url) # "https://www.facebook.com/people/Tomás-Navarro-Febre/100010922979377" # Now it works. Response [200] r = requests.get(redirect_url) print(r) There must be a better way to deal with this. I tried a bunch of different headers, and using requests.Session(), but none of them worked. Thanks in advance for any help.
has title: HTTP 301 redirect url encoding issue
accepted answer: http://stackoverflow.com/a/51127373
tagged with: encoding
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89239616

http://stackoverflow.com/comment/89286966
type: Comment
comment on: http://stackoverflow.com/q/51151660
score: 0
has text: I want to request the session i started in the first function, so i tried to do so using request.session, using uid variable that was stated in the first function , and this worked in some tutorial but not working here and I don't know why
type: QuestionComment

http://stackoverflow.com/comment/89080944
score: 0
type: AnswerComment
type: Comment
has text: @MaddieGraham, the edit should explain why it wasn't working.
comment on: http://stackoverflow.com/a/51039453

http://stackoverflow.com/comment/89119780
type: AnswerComment
comment on: http://stackoverflow.com/a/51064760
score: 0
type: Comment
has text: so to use this in my purpose I would want to have 30,100 then?

http://stackoverflow.com/comment/89177691
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51094522
has text: delete all entry using django shell and try again...
score: 0

http://stackoverflow.com/comment/89086585
comment on: http://stackoverflow.com/a/51047506
type: Comment
has text: Thanks, I'm indeed not familiar enough with `einsum`. I'm concerned about the performance of `einsum` compared to `dot`; in my case I'm using the Intel distribution for Python and the speed gain on `dot` is significant. Do you think there would be a way to use `dot` so that the same optimizations can take place ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89158717
type: QuestionComment
comment on: http://stackoverflow.com/q/51085161
score: 1
has text: Why do you want them in variables? Variable count is predefined when writing the code. Lists or other data structures can expand as needed.
type: Comment

http://stackoverflow.com/comment/89313095
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51161334
has text: I didn't pick up on that originally! Thanks for your help!

http://stackoverflow.com/a/51065697
upvote count: 1
answers question: http://stackoverflow.com/q/51065581
accepted answer of: http://stackoverflow.com/q/51065581
has body: Is this what you need ? df.applymap(lambda x : pd.DataFrame(x).name.tolist()) Out[278]: genres keywords 0 [dual identity, love of one's life] [sequel, superhero] 1 [pizza boy, marvel comic] [tentacle, super villain] Update df.applymap(lambda x : pd.DataFrame(x).name.str.cat(sep=',')) Out[280]: genres keywords 0 dual identity,love of one's life sequel,superhero 1 pizza boy,marvel comic tentacle,super villain
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89121491
type: Answer
score: 1

http://stackoverflow.com/a/51145950
type: Answer
has comment: http://stackoverflow.com/comment/89276930
downvote count: 0
answers question: http://stackoverflow.com/q/51145940
score: 1
has body: You can using select_dtypes df.select_dtypes('object').columns.tolist() Or using dtypes df.dtypes.reset_index().groupby(0)['index'].apply(list)
upvote count: 1
has comment: http://stackoverflow.com/comment/89276890

http://stackoverflow.com/a/51040363
has comment: http://stackoverflow.com/comment/89072026
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51039943
accepted answer of: http://stackoverflow.com/q/51039943
score: 1
has body: You can make a factory method like this ... def factory(a, b): def g(c): print(f'this is {c}') return f'other stuff using {a}, {b} and {c}' # if you want to return g then use it like &gt;&gt;&gt; f = factory('scene1', 'int') &gt;&gt;&gt; msg = f('part1') this is part1 &gt;&gt;&gt; print(msg) other stuff using scene1, int and part1
upvote count: 1

http://stackoverflow.com/a/67092882
type: Answer
answers question: http://stackoverflow.com/q/51146399
has body: I made it using the recursive function. Although I have to break the functions out when the condition is met as many as I call recursive functions. class Song: def __init__(self, name): self.name = name self.next = None def next_song(self, song): self.next = song def is_repeating_playlist(self): first = self.name def recursion(self,first): if self.next == None: return False while not first == self.next.next.name: recursion(self.next, first) break print('break out') return True return recursion(self,first) first = Song("Hello") second = Song("Eye of the tiger") third = Song("mamma mia!") fourth = Song("lion king") first.next_song(second) second.next_song(third) third.next_song(fourth) fourth.next_song(first) print(first.is_repeating_playlist())
score: 0

http://stackoverflow.com/comment/89409219
type: Comment
comment on: http://stackoverflow.com/a/51165793
type: AnswerComment
has text: So I actually ended up using the corr to make a BenT's work more readable. Thanks.
score: 0

http://stackoverflow.com/a/51151898
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51151816
answers question: http://stackoverflow.com/q/51151816
upvote count: 2
has body: Use np.timedelta64 working with all columns converted to 2d numpy array: df = pd.DataFrame(df.values / np.timedelta64(1, 'h'), columns=df.columns, index=df.index) print (df) a b c 0 0.002222 0.733333 0.575833 1 5.083333 0.250000 4.066667 2 1.032500 1.033333 1.532778 If want use apply: df = df.apply(lambda x: x/np.timedelta64(1, 'h')) print (df) a b c 0 0.002222 0.733333 0.575833 1 5.083333 0.250000 4.066667 2 1.032500 1.033333 1.532778 Or total_seconds: df = df.apply(lambda x: x.dt.total_seconds() / 3600) print (df) a b c 0 0.002222 0.733333 0.575833 1 5.083333 0.250000 4.066667 2 1.032500 1.033333 1.532778
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51122863
type: Answer
has comment: http://stackoverflow.com/comment/89237088
has comment: http://stackoverflow.com/comment/89236138
score: 2
has comment: http://stackoverflow.com/comment/89235748
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51122020
has comment: http://stackoverflow.com/comment/89238721
answers question: http://stackoverflow.com/q/51122020
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89235696
has body: Try below code to get required data without extra "sleeps": import requests import csv from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException # ----------------------------------------------HANDLING-SELENIUM-STUFF------------------------------------------------- driver = webdriver.Chrome() driver.get('https://www.usta.com/en/home/play/facility-listing.html?searchTerm=&amp;distance=5000000000&amp;address=Palo%20Alto,%20%20CA') wait = WebDriverWait(driver, 8) links = [] while True: new_links = wait.until(EC.visibility_of_all_elements_located((By.LINK_TEXT, "MORE INFO"))) links.extend([link.get_attribute("href") for link in new_links]) try: next_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li[title='Next page']&gt;a"))) next_button.click() except TimeoutException: break wait.until(EC.staleness_of(new_links[-1])) # Do whatever you need with links
upvote count: 2

http://stackoverflow.com/q/51014338
has comment: http://stackoverflow.com/comment/89025134
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
has title: Can someone help me vectorize this for-loop?
tagged with: genetic
has comment: http://stackoverflow.com/comment/89021490
answer count: 0
has comment: http://stackoverflow.com/comment/89023785
has comment: http://stackoverflow.com/comment/89023750
linked to: http://stackoverflow.com/q/49175337
has comment: http://stackoverflow.com/comment/89022356
type: Question
has comment: http://stackoverflow.com/comment/89021588
has comment: http://stackoverflow.com/comment/89021495
score: 4
has comment: http://stackoverflow.com/comment/89023848
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/89021710
has comment: http://stackoverflow.com/comment/89023760
downvote count: 0
has body: I'm trying to make my code more efficient. I'm not super familiar with vectorization. I can do simple ones but I'm having trouble wrapping my head around this one def mate(self, parent1, parent2): length = parent1.size parent1 *= 1e6 parent2 *= 1e6 parent1 = parent1.astype(int) parent2 = parent2.astype(int) child1 = [] child2 = [] for i in range(length): hold1 = parent1[i] hold2 = parent2[i] hold1 = np.binary_repr(hold1, 30) hold2 = np.binary_repr(hold2, 30) pivot = np.random.randint(0, length) childGene1 = hold1[:pivot] + hold2[pivot:] childGene2 = hold2[:pivot] + hold1[pivot:] childGene1 = int(childGene1, 2) / 1e6 childGene2 = int(childGene2, 2) / 1e6 child1.append(childGene1) child2.append(childGene2) return [child1, child2] It's a mating function I made for a genetic algorithm. How should I go about vectorizing this loop?
favorite count: 0

http://stackoverflow.com/a/51061890
has comment: http://stackoverflow.com/comment/89922536
upvote count: 1
has body: The expected output format {Subject: Body} looks like a dictionary to me, so I would advise you stick with dictionaries as a container. The following will skip any line that starts with "To:", "From:", or "\n". If it encounters a subject line, it generates an entry in a dictionary for that subject line and adds the concatenation of subsequent lines until the next subject line as values to the current subject line. with open("testing.txt") as f: data = {} for line in f: if any(line.startswith(kw) for kw in ("From:", "To:", "\n")): continue if line.startswith("Subject:"): current_subject = line.split(":")[-1].strip() else: data.setdefault(current_subject, "") data[current_subject] += line print(data) # {'This is the sample request one...': 'Hey there, \nThis is the smaple email just for the test purpose.\nNo intentions to hurt somebodys feleings at all.\nThanks, \n', # 'This is the sample request second...': 'Hey there, \nthis is another sample mail body and just to test the py script working\nthis si the part of the data preprocesing \nthanks'} Feel free to strip unwanted characters from the lines, as you see fit. I hope this helps.
score: 1
has comment: http://stackoverflow.com/comment/89968381
downvote count: 0
answers question: http://stackoverflow.com/q/51061222
type: Answer

http://stackoverflow.com/comment/94441790
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52023152
has text: thanks for the asnwer @Satyajit, just a reminder that the answer still contains `with tf.as_default():` instead of `with graph.as_default():`

http://stackoverflow.com/comment/89164139
has text: I don't know what you're logging or how your logging works, but you could put `predictions={"value": logits}`, and use it instead of the `classes` you had.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51066076
type: Comment

http://stackoverflow.com/q/51106995
tagged with: tkinter
score: 0
has answer: http://stackoverflow.com/a/68393858
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89202964
has answer: http://stackoverflow.com/a/51108059
type: UnansweredQuestion
answer count: 4
has body: I just want to know how could I insert a picture into the splash screen? from tkinter import * #splash screen class SplashScreen(Frame): def __init__(self, master=None, width=0.8, height=0.6, useFactor=True): Frame.__init__(self, master) self.pack(side=TOP, fill=BOTH, expand=YES) # get screen width and height ws = self.master.winfo_screenwidth() hs = self.master.winfo_screenheight() w = (useFactor and ws * width) or width h = (useFactor and ws * height) or height # calculate position x, y x = (ws / 2) - (w / 2) y = (hs / 2) - (h / 2) self.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) self.master.overrideredirect(True) self.lift() if __name__ == '__main__': root = Tk() sp = SplashScreen(root) sp.config(bg="#3632ff") m = Label(sp, text="MH60 NAVIGATION APP") m.pack(side=TOP, expand=YES) m.config(bg="#3366ff", justify=CENTER, font=("calibri", 29)) Button(sp, text="PRESS TO START", bg='red', command=root.destroy).pack(side=BOTTOM, fill=X) root.mainloop()
has answer: http://stackoverflow.com/a/75364419
favorite count: 0
has answer: http://stackoverflow.com/a/68393616
type: Question
has title: How to insert a picture into the splash screen?
tagged with: python

http://stackoverflow.com/q/51116689
answer count: 1
has comment: http://stackoverflow.com/comment/89239614
has body: Bokeh version: 0.13 Python version: 3 Hi, I have a use-case in which I use vbar_stack to plot a list of say company counts, stacked over a period of dates. This is a bokeh app in which the x-axis is the dates and y-axis is the counts. I have been able to generate x-range dynamically by this p.x_range.factors = [] p.x_range.factors = list(dates) But since the company list is also changing dynamically how do I update stackers in runtime. I think stackers cannot be taken from CDS also, I am kind of stuck over this. I would highly appreciate any help on this. Edits to further elaborate the problem Sorry If I am not able to express my problem statement properly but here is what I am trying to do. This is my DataFrame, with column names as c1-c3 and their count { "c1": [1, 2, 3], "c2": [1, 4, 6], "c3": [6, 2, 4], "dates": ['21-06-2018', '22-06-2018', '23-06-2018'] } Dates are on x-axis and c1-c3 are stacked. Note that this runs on the server(App). A user can select the date range from a drop-down and so, dates, as well as these c1...cn, are dynamic in nature. currently these 2 approaches I am using: I update the Column Data source and x_range p.x_range.factors = [], p.x_range.factors = list(dates) then I again call vbar_stack but this is superimposing on previous graphs I set p.renderes=[] this solves the superimpose problem but it clear all axis title toolbar and legends. which I tried explicitly setting but it's not working We recently started using Bokeh I am not sure I am using the right approach Can anyone help on this? Thanks!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89272042
has title: How to dynamically update stackers value in vbar_stack in bokeh?
has comment: http://stackoverflow.com/comment/89272682
tagged with: bokeh
has comment: http://stackoverflow.com/comment/89248449
has comment: http://stackoverflow.com/comment/89262993
type: Question
has comment: http://stackoverflow.com/comment/89268646
has answer: http://stackoverflow.com/a/51144345
score: 0

datetime-format
tags question: http://stackoverflow.com/q/51072902
tag name: datetime-format
type: Tag

http://stackoverflow.com/comment/89309307
comment on: http://stackoverflow.com/q/51162923
has text: this is the error you get when trying to load an empty string. have you verified the response body is not empty?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/89062529
comment on: http://stackoverflow.com/a/51025196
score: 0
type: AnswerComment
type: Comment
has text: Thank you! You made it seem a lot simpler than I thought it would be.

http://stackoverflow.com/comment/89043587
type: QuestionComment
score: 1
has text: Your csv is delimited by a semi-colon, use `df = pd.read_csv('input.csv', sep=';')`, currently all your columns are loading into a single column which is why it can't find that column
comment on: http://stackoverflow.com/q/51025590
type: Comment

http://stackoverflow.com/comment/89117368
score: 0
comment on: http://stackoverflow.com/q/51063038
type: QuestionComment
type: Comment
has text: `client.list_rows` rows is going to send `rest call` to get rows from `google BigQuery table` rest is writing to disc.

http://stackoverflow.com/q/51025312
score: 5
has comment: http://stackoverflow.com/comment/89043043
upvote count: 5
tagged with: ubuntu
answer count: 1
downvote count: 0
has title: Start a python script at startup automatically?
favorite count: 0
has answer: http://stackoverflow.com/a/51026631
tagged with: cron
has comment: http://stackoverflow.com/comment/89043116
tagged with: python
type: AnsweredQuestion
has body: I followed multiple tutorials available on stackoverflow about starting a python script at startup but none of them works. I need to activate a virtualenv then start a flask server I tried init.d method I made an start.sh in /etc/init.d/ #!/bin/sh ### BEGIN INIT INFO # Provides: skeleton # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Should-Start: $portmap # Should-Stop: $portmap # X-Start-Before: nis # X-Stop-After: nis # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # X-Interactive: true # Short-Description: Example initscript # Description: This file should be used to construct scripts to be # placed in /etc/init.d. ### END INIT INFO cd /home/ion/ source /home/ion/py35/bin/activate cd /home/ion/Desktop/flask/ nohup python main.py &amp; echo "Done" Its permissions are chmod at +x ion@aurora:/etc/init.d$ ll start.sh -rwxr-xr-x 1 root root 625 Jun 25 19:10 start.sh* Went to /etc/rc.local #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. /etc/init.d/start.sh exit 0 Didn't work cronjob method sudo crontab -e and appended @reboot sh '/etc/init.d/start.sh' Didn't worked either , where am I wrong? Manual triggered logs (py35) ion@aurora:~/Desktop/flask$ python main.py WARNING:tensorflow:From /home/ion/Desktop/flask/encoder.py:57: calling l2_normalize (from tensorflow.python.ops.nn_impl) with dim is deprecated and will be removed in a future version. Instructions for updating: dim is deprecated, use axis instead 2018-06-25 19:34:05.511943: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA * Serving Flask app "main" (lazy loading) * Environment: production WARNING: Do not use the development server in a produ…
accepted answer: http://stackoverflow.com/a/51026631
tagged with: startup
type: Question

http://stackoverflow.com/q/51035611
type: Question
tagged with: css-selectors
score: 2
accepted answer: http://stackoverflow.com/a/51035636
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: selenium-chromedriver
upvote count: 2
has body: I'm using selenium to click on a button and the HTML code for the button is like: div class="_1WZqU PNlAR" role="button"&gt;Join group&lt;/div I tried with all possible solution: driver.find_element_by_css_selector('._1WZqU.PNlAR').click() driver.find_element_by_css_selector('_1WZqU PNlAR').click() But its throwing an error no such element: Unable to locate element: {"method":"css selector","selector":"._1WZqU.PNlAR"}
tagged with: selenium
has answer: http://stackoverflow.com/a/51035636
has title: Button action not working in selenium python

http://stackoverflow.com/a/51066007
has body: Since you are already using the ORM features, it really is similar to that SQLAlchemy with multiple Many to Many Relationships and there is a tutorial on this scenario, however with a subtle difference that you want a class for AssocCompaniesActivities. Preamble for imports and other set up to have your original code work: from sqlalchemy import * from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) Base = declarative_base() This is the updated class definition: from sqlalchemy.orm import relationship class Companies(Base): __tablename__ = 'companies' identifier = Column(Integer, primary_key=True) id = Column(String) label = Column(String) activities_area = relationship("Activities", secondary='assoc_companies_activities', back_populates='companies') def __init__(self, id, label): self.id = id self.label = label class Activities(Base): __tablename__ = 'activities_area' identifier = Column(Integer, primary_key=True) name = Column(String) companies = relationship("Companies", secondary='assoc_companies_activities', back_populates='activities_area') def __init__(self, name): self.name = name class AssocCompaniesActivities(Base): __tablename__ = 'assoc_companies_activities' identifier = Column(Integer, primary_key=True) company_id = Column(Integer, ForeignKey("companies.identifier"), nullable=True) activities_area_id = Column(Integer, ForeignKey("activities_area.identifier"), nullable=True) # Should declare primary key for company_id and activities_area_id, # or better yet, just create a simple un-mapped table like in the docs def __init__(self, company_id , activities_area_id): self.company_id = company_id self.activities_area_id = activities_area_id Set up the db, session: session = Session() Base.metadata.create_all(engine) Finally, add the example data: company1 = Companies(id='company1', label='f…
score: 2
has comment: http://stackoverflow.com/comment/89154528
answers question: http://stackoverflow.com/q/51060165
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51060165
has comment: http://stackoverflow.com/comment/89123087
type: Answer
upvote count: 2

http://stackoverflow.com/q/51030608
possible better answer: http://stackoverflow.com/a/51031475
has comment: http://stackoverflow.com/comment/89082175
has comment: http://stackoverflow.com/comment/89062007
has body: I'm trying to get the index values out of a numpy array, I've tried using intersects instead to no avail. I'm simply trying to find like values in 2 arrays. One is 2D and I'm selecting a column, and the other is 1D, just a list of values to search for, so effectively just 2 1D arrays. We'll call this array a: array([[ 1, 97553, 1], [ 1, 97587, 1], [ 1, 97612, 1], [ 1, 97697, 1], [ 1, 97826, 3], [ 1, 97832, 1], [ 1, 97839, 1], [ 1, 97887, 1], [ 1, 97944, 1], [ 1, 97955, 2]]) And we're searching say, values = numpy.array([97612, 97633, 97697, 97999, 97943, 97944]) So I try: numpy.where(a[:, 1] == values) And I'd expect a bunch of indices of the values, but instead I get back an array that's empty, it spits out [(array([], dtype=int64),)]. If I try this though: numpy.where(a[:, 1] == 97697) It gives me back (array([2]),), which is what I would expect. What weirdness of arrays am I missing here? Or is there maybe even an easier way to do this? Finding array indices and matching arrays seems to not work as I expect at all. When I want to find the unions or intersects of arrays, by indice or unique value it just doesn't seem to function. Any help would be super. Thanks. Edit: As per Warrens request: import numpy a = numpy.array([[ 1, 97553, 1], [ 1, 97587, 1], [ 1, 97612, 1], [ 1, 97697, 1], [ 1, 97826, 3], [ 1, 97832, 1], [ 1, 97839, 1], [ 1, 97887, 1], [ 1, 97944, 1], [ 1, 97955, 2]]) values = numpy.array([97612, 97633, 97697, 97999, 97943, 97944]) I've found that numpy.in1d will give me a correct truth table of booleans for the operation, with a 1d array of the same length that should map to the original data. My only issue here is now how to act with that, for instance deleting or modifying the original array at those indices. I could do it laboriously with a loop, but as far as I know there are better ways in numpy. Truth tables as masks are supposed to be quite powerful with numpy from what I have been able to find.
has comment: http://stackoverflow.com/comment/89082443
has answer: http://stackoverflow.com/a/51031475
type: Question
tagged with: numpy
has title: Finding indices of values in 2D numpy array
answer count: 2
has answer: http://stackoverflow.com/a/51031323
tagged with: arrays
has comment: http://stackoverflow.com/comment/89053563
has comment: http://stackoverflow.com/comment/89092911
tagged with: python
has comment: http://stackoverflow.com/comment/89089758
linked to: http://stackoverflow.com/q/33678543
favorite count: 0
has comment: http://stackoverflow.com/comment/89088272
has comment: http://stackoverflow.com/comment/89061899
has comment: http://stackoverflow.com/comment/89083184
accepted answer: http://stackoverflow.com/a/51031323
upvote count: 2
has comment: http://stackoverflow.com/comment/89055950
has comment: http://stackoverflow.com/comment/89087360
has comment: http://stackoverflow.com/comment/89302304
downvote count: 1
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/89276388
has text: oh no ... I just realized my application is limited to python2.7 because I need to use Jython.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51145687

http://stackoverflow.com/a/51157603
downvote count: 0
has body: Using pandas Dataframes you can proceed as follows: my_dataframe = pd.DataFrame(Keyword, columns=["Keyword", "Score"]) The result is the following: NOTE: you really should consider using lowercase variable names.
type: Answer
answers question: http://stackoverflow.com/q/51157473
score: 2
upvote count: 2

http://stackoverflow.com/comment/89237023
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51124947
has text: @AlexHall: huh! I ran it on PyPy on a Mac to get those timings. I tried your exact source code and tried all of Py3, Py2 and PyPy. Some variance but not the same as the real.it version. Your optimized solution is a bit faster indeed. Thanks!

http://stackoverflow.com/q/51031929
has comment: http://stackoverflow.com/comment/89064847
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89057282
has body: I am trying to read images files with tensorflow and get the labels from the path as follows: import tensorflow as tf filename_queue = tf.train.string_input_producer( tf.matching_files( tf.constant(["./positive_images/*.jpg", "./negative_images/*.jpg"]))) image_reader = tf.WholeFileReader() file_name, image_file = image_reader.read(filename_queue) label = tf.map_fn(lambda x: "positive" in x, file_name) image = tf.image.decode_jpeg(image_file, channels=1) with tf.Session() as sess: # Required to get the filename matching to run. tf.global_variables_initializer() # Coordinate the loading of image files. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) filename1 = sess.run([label]) print(filename1) image_tensor = sess.run([image]) print(image_tensor) coord.request_stop() coord.join(threads) However I get the error: in map_fn raise ValueError("elems must be a 1+ dimensional Tensor, not a scalar") ValueError: elems must be a 1+ dimensional Tensor, not a scalar Reading the images seems to work, but the filename can not be parsed correctly. What am I doing wrong?
score: 0
tagged with: image-recognition
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89325855
answer count: 0
has title: Reading images and extract label from path with TensorFlow

generator
tags question: http://stackoverflow.com/q/51040813
tags question: http://stackoverflow.com/q/51070461
tags question: http://stackoverflow.com/q/51092901
tags question: http://stackoverflow.com/q/51071212
type: Tag
tags question: http://stackoverflow.com/q/51030664
tag name: generator
tags question: http://stackoverflow.com/q/51032155
tags question: http://stackoverflow.com/q/51038878

minimalmodbus
tags question: http://stackoverflow.com/q/51021148
tag name: minimalmodbus
type: Tag

http://stackoverflow.com/comment/89298429
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51157219
type: QuestionComment
has text: If it's telling you "no such file or directory" it means exactly that -- you're telling it to run "server.py" but "server.py" doesn't exist in the current directory.

http://stackoverflow.com/comment/91714336
score: 0
type: Comment
has text: Please keep in mind that pip wont work in anaconda. https://stackoverflow.com/questions/45917541/what-is-the-effect-of-using-pip-to-install-python-packages-on-anaconda/45919845#45919845
type: AnswerComment
comment on: http://stackoverflow.com/a/51163114

http://stackoverflow.com/q/51099292
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89195204
has title: Python Selenium Chrome redirecting to slow and returning nothing
has comment: http://stackoverflow.com/comment/89197427
tagged with: selenium
has comment: http://stackoverflow.com/comment/89196696
type: Question
score: 0
has body: I am automating one hospital application, need to get document by customer id, on first 2 pages where in i am filling details automation working fine but after clicking on SUBMIT to get details, chrome becomes too slow and returns blank penal after 3-5 minutes, manually all is working well. Python 2.7 Selenium 3.13 Chrome Driver 2.4 Chrome Version 67 Manual Behaviour - Screen 1 : Login -- Screen2 : Validate patient by name and addmassion date and click SET--Screen3 : downlaod reports. all are woring successful. Automation Behaviour - Screen 1- Login Successful - Screen 2 Details Typed clicked on SET --Screen 3: page is keep loading for 3/4 minutes and returns a blank page. Error Chrome Message Popup comes just before screen 3 loading as :- Error occured while processing the request at server - -1 &gt; from selenium import webdriver &gt; &gt; from selenium.webdriver.common.by import By &gt; &gt; from selenium.webdriver import ActionChains &gt; &gt; from selenium.webdriver.support.ui import Select &gt; &gt; import time &gt; &gt; options=webdriver.ChromeOptions() &gt; &gt; options.add_argument("user-data-dir=C:\\Users\\hitesh &gt; kumar\\AppData\Local\\Google\\Chrome\\User Data") &gt; &gt; driver= webdriver.Chrome(executable_path="C:\\chrome &gt; driver\\chromedriver.exe",chrome_options=options) &gt; &gt; driver.get("http://10.**.***.12/****/WBLogin.aspx") &gt; &gt; select_searchby_from_list = &gt; Select(driver.find_element_by_name("$ddlFieldName01")).select_by_visible_text("patient_number") &gt; &gt; patient_number = "OPD21062018823" &gt; &gt; txt_patient_number = driver.find_element_by_name("$txtFieldValue01").send_keys(patient_number) &gt; &gt; select_department_from_list=Select(driver.find_element_by_name("ddlFieldName02")).select_by_visible_text("OPD") &gt; &gt; DOA = "21062018" &gt; &gt; txt_DOA = driver.find_element_by_name("$txtFieldValue02").send_keys(DOA) &gt; &gt; btn_set=driver.find_element(By.XPATH, '//*[@id="ucCriteria_txtFieldValue02"]').click()
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/89196418

http://stackoverflow.com/comment/89099157
has text: @DavidM Sure, you can use loops, replace repeating fragments with `for-in` constructions. I think that the main modification you would like to do is to place your loop into your _model building function_ instead of `MyModel` class. Probably you don't need additional wrappers, use functional API, and then you can use any loops or conditional constructions you want.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51041136

http://stackoverflow.com/a/51063952
accepted answer of: http://stackoverflow.com/q/51063696
downvote count: 0
answers question: http://stackoverflow.com/q/51063696
type: Answer
has comment: http://stackoverflow.com/comment/89134728
score: 5
upvote count: 5
has body: You to need to encode the string as ASCII, because as you said, it's an ASCII string. Example, quick-and-dirty solution: print(hex(sum('1c03e8'.encode('ascii')) % 256))
type: AcceptedAnswer

http://stackoverflow.com/comment/89273652
comment on: http://stackoverflow.com/a/51144281
score: 0
has text: Thanks for all the help with this. So I have api.py, which contains this (which you've helped with): https://paste.ee/p/eMbR0 It should only be able to operate once every 10 seconds, correct? I set up a test command in test.py: https://paste.ee/p/o3or7 When I run the `test` command, it prints "!" instantly. Am I not implementing this properly?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89166441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51085083
score: 0
has text: The second security-impacting bug is caused by the reliance on a newline-delimited stream to list filenames. If someone runs `d=/home/blahblah/$'\n'/etc/passwd$'\n'; mkdir "$d" && touch "$d/foo"`, then your `find` would return `/etc/passwd` as a result, and your code would copy it over despite not being under `/home/blahblah`.

http://stackoverflow.com/comment/89094933
type: Comment
has text: Yes, single quotes. This is a `str`
comment on: http://stackoverflow.com/q/51051619
score: 0
type: QuestionComment

http://stackoverflow.com/q/51048867
type: Question
has comment: http://stackoverflow.com/comment/89088894
has comment: http://stackoverflow.com/comment/89089507
has comment: http://stackoverflow.com/comment/89090540
has answer: http://stackoverflow.com/a/51049232
has comment: http://stackoverflow.com/comment/89089610
has comment: http://stackoverflow.com/comment/89088896
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51049111
has comment: http://stackoverflow.com/comment/89089375
favorite count: 0
has comment: http://stackoverflow.com/comment/89088946
type: UnansweredQuestion
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/89089752
has comment: http://stackoverflow.com/comment/89088851
downvote count: 2
has title: python - editing csv by adding chars to each row
has body: I've got this dataset in a .csv file: https://www.dropbox.com/s/2kzpzkhoiolhnlc/output.csv?dl=0 19,3,12 3 12 16,4 26,15,8,3 2 8 15 20 12,25,20,2,16 12,16 12,25 2,16 1,12 16,4 11,19,25,20 11,20,16,21 25,20,21 ..... for each row, if numbers are less then 51 than I need to add ? until having 51 chars in that row. For example, in the first row I have 19,3,12, so I have to add 48 ? to have a row like this: 19,3,12,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? In the second row I have just one number, so I have to add 50 ?, the same for the other rows. Could you help me please? EDIT: I've tried with this but didn't work, it just added "" to some rows: import pandas as pd df = pd.read_csv('output.csv', sep=';') df = df.fillna('?') df.to_csv('sorted2.csv', index=False)

http://stackoverflow.com/comment/89278455
comment on: http://stackoverflow.com/a/51146645
type: AnswerComment
has text: This is actually better! Kudos @abarnert
score: 0
type: Comment

http://stackoverflow.com/a/51109538
has body: Indeed, you need groupby but on the column 'make' and you can use filter with a function creating a tuple from 'sale' column: outdf = df.groupby('make').filter(lambda x: tuple(x.sale)== (1,0)) and you get the expected output: make country other_columns sale 0 honda tokyo data 1 1 honda hirosima data 0 2 toyota tokyo data 1 3 toyota hirosima data 0 6 ferrari tokyo data 1 7 ferrari hirosima data 0 8 nissan tokyo data 1 9 nissan hirosima data 0 if the order between 1 and 0 is not always satisfy for a same 'make', you can use a sort_values on 'sale' column first
answers question: http://stackoverflow.com/q/51109245
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/89206827
downvote count: 0

http://stackoverflow.com/comment/89116218
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51052752
score: 1
has text: I was able to reproduce your result by modifying my code, however it is still not correct. What works now is that both the dataframe and the graph contain the same amount of edges. Applying alpha values or a specific width per arrow still applies the wrong edge data per edge. Edit: I've added your code in my example code and posted the "new" dataframe (which is just scaled from 0.1-1.0 in the v-column instead of 1-10, so alpha values can be applied). As you can see, if you run the code, the connection between 0x5abf99... and 0x523564..., which has the value 1.0 associated, is not solid

http://stackoverflow.com/comment/89159104
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51085101
type: QuestionComment
has text: @ChristianSauer each test does not get a fresh database - that's what we are trying to set up. I was surprised there wasn't an equivalent module in Python for database cleaning, which makes me wonder if it's built into pytest or something. Please excuse me, as I said, I'm a noob to Python and thanks for the help.

http://stackoverflow.com/a/51026993
has body: You got the "repetition" because you add the req_path two times: one here: # Joining the base and the requested path abs_path = os.path.join("c:", BASE_DIR, req_path) and one here: files = [os.path.join(req_path, file) for file in files] the second should look like this: files = [f for f in files] # (or just be deleted)
downvote count: 0
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51025540
type: Answer

http://stackoverflow.com/a/51093054
downvote count: 0
has body: Using an Item is optional; they're just a convenient way to declare your data model and apply validation. You can also use a plain dict instead. If you do choose to use Item, you will need to import it for use in the spider. It's not discovered automatically. In your case: from items import CrowdfundingItem As a spider runs the parse method on each page, you can load the extracted data into your Item or dict. Once it's loaded, yield it, which passes it back to the scrapy engine for processing downstream, in pipelines or exporters. This is how scrapy enables "storage" of the data you scrape. For example: yield Product(name='Desktop PC', price=1000) # uses Item yield {'name':'Desktop PC', 'price':1000} # plain dict
has comment: http://stackoverflow.com/comment/89174567
answers question: http://stackoverflow.com/q/51092757
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89175161
has comment: http://stackoverflow.com/comment/89175283
has comment: http://stackoverflow.com/comment/89174416
has comment: http://stackoverflow.com/comment/89174469
has comment: http://stackoverflow.com/comment/89176411

http://stackoverflow.com/a/51162111
has body: You don't have to encode them as utf-8; Try passing them as normal strings to pandas read_sql function, it should work fine, if not, then you have a problem somewhere else... but encoding is not what you want here. Pyodbc accepts unicode strings in the query as normal, so that is not your problem at all. I suggest also reading the Unicode section on pyodbc documentation that contains specific unicode configuration for some databases, although in your case I don't see that being a problem at all, because it is related to the database driver encoding and not your sql query, which should be a normal unicode string every time.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89307967
score: 2
has comment: http://stackoverflow.com/comment/89307727
has comment: http://stackoverflow.com/comment/89307945
answers question: http://stackoverflow.com/q/51162092
accepted answer of: http://stackoverflow.com/q/51162092
has comment: http://stackoverflow.com/comment/89307796

http://stackoverflow.com/comment/109893700
has text: The only way that I've found to verify the boto3 client is to try to use a client method and wrap that in a try/except. From what I remember the "S3" is an enum mapping...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/61546535
type: Comment

http://stackoverflow.com/a/51249428
has body: You have an observe call on the plot1 figure which subsequently updates the plot1 figure... which results in a recursive loop. If you put an if statement in the function then it can be set so it only runs after the first operation only. # We'll start with bqplot's matplotlib inspired API from bqplot import pyplot as plt # Let's begin by importing some libraries we'll need import numpy as np import ipywidgets as wi def make_data(x, sigma_noise): """ Generates a sine wave :param x: x value, scalar or vector between 0 and .. :param sigma_noise: standard deviation of the noise added to the data """ y = np.sin(x) noise = np.random.normal(loc=0, scale=sigma_noise, size=len(x)) y_noise = y + noise return y_noise def update_plot(message): # print(message) if message['name'] == 'value': y_noise = make_data(x, slider.value) plot_1.y = y_noise noise = 2 x = np.linspace(0, 10) y = make_data(x, noise) figure = plt.figure(title='Test', animation_duration=100) #figure.animation_duration = 250 plot_1 = plt.scatter(x, y) plot_1.observe(update_plot, ['x','y']) slider = wi.FloatSlider(description='noise', value=0.001, min=0, max=1) slider.observe(update_plot, 'value') wi.VBox([slider, figure])
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89487085
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51090853

http://stackoverflow.com/q/51036939
has title: Overload server django deploy with apache2 and mod_wsgi
favorite count: 0
tagged with: apache2
has comment: http://stackoverflow.com/comment/91930523
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89227462
score: 2
tagged with: mod-wsgi
has body: I'm with several problem with overload at deploy django with apache2 and mod_wsgi. Follow my steps and setup: Server: Ubuntu 18.04 running at Windows Linux Subsystem (WSL). Install sudo apt install python3 python3-dev python3-pip virtualenv apache2 apache2-dev mysql-server phpmyadmin php-mbstring php-gettex libmysqlclient-dev So, I created a vhost file ServerName 127.0.0.20 ServerAlias divisor.local ErrorLog /mnt/d/divisor/logs/error.log CustomLog /mnt/d/divisor/logs/access.log combined #provide from mod_wsgi-express --conf LoadModule wsgi_module "/mnt/d/divisor/env3/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" Alias /static /mnt/d/divisor/framework/static Alias /media /mnt/d/divisor/framework/media Require all granted Require all granted Require all granted WSGIScriptAlias / /mnt/d/divisor/framework/framework/wsgi.py WSGIDaemonProcess divisor display-name=divisor-modwsgi python-path=/mnt/d/divisor/framework/:/mnt/d/divisor/env3/lib/python3.6/site-packages WSGIProcessGroup divisor WSGIApplicationGroup %{GLOBAL} With virtualenv active I run: pip install django mod_wsgi When I run apache start. Less than 3 seconds apache overload with 2 proccess. Follow "top" on terminal: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 6272 www-data 18 42+ 318844 31608 8692 S 100.7 0.4 0:13.21 apache2 6274 www-data 18 42+ 2017236 8668 3924 S 100.7 0.1 0:12.29 apache2 I try found the problem with sudo lsof -p 6272, log apache2 6272 www-data 0r CHR 1,3 65583669573738507 /dev/null apache2 6272 www-data 1w CHR 1,3 65583669573738507 /dev/null apache2 6272 www-data 3u sock 0,0 8978 can't identify protocol apache2 6272 www-data 5r FIFO 0,0 8995 pipe apache2 6272 www-data 6w FIFO 0,0 8995 pipe apache2 6272 www-data 8w REG 0,2 0 562949954063676 /var/log/apache2/other_vhosts_access.log apache2 6272 www-data 9w REG 0,13 19168 281474976719069 /mnt/d/divisor/logs/access.log apache2 6272 www-data 10w REG 0,2 27268 562949954063675 /var/log/apache2/…
type: Question
has comment: http://stackoverflow.com/comment/89097465
downvote count: 0

http://stackoverflow.com/comment/89118600
type: AnswerComment
type: Comment
has text: [My best guess is you are not fullfilling all of the requirements, e.g. making sure all users have permission to access the Python installation.](https://www.ibm.com/support/knowledgecenter/SS3RA7_18.0.0/modeler_r_nodes_ddita/clementine/r_intro_pyspark.html)
score: 0
comment on: http://stackoverflow.com/a/51036310

http://stackoverflow.com/comment/89213965
comment on: http://stackoverflow.com/q/51112867
score: 0
type: Comment
type: QuestionComment
has text: @zwer I think [`random.choices(iterable,k=number of elems returned)`](https://docs.python.org/3.6/library/random.html#random.choices) would better suit his needs.

http://stackoverflow.com/a/51069536
type: Answer
score: 2
upvote count: 2
has body: Let the dictionary be cd then:- &gt;&gt;&gt; def foo(cd): ... for x in cd: ... if cd[x] == {}: ... cd[x] = "" ... else: foo(cd[x]) ... return cd &gt;&gt;&gt; cd = {"a":{},"b":{"c":{}}} &gt;&gt;&gt; foo(cd) {'a': '', 'b': {'c': ''}} The thinking process goes like this:- Firstly make a processor which will process your dictionary and replace all empty dictionaries with empty strings. Then just give all the dictionaries the opportunity to meet that processor.
answers question: http://stackoverflow.com/q/51069082
downvote count: 0

http://stackoverflow.com/q/51047954
has answer: http://stackoverflow.com/a/51048595
has title: create list of increasing number of repeated characters
favorite count: 0
has answer: http://stackoverflow.com/a/51047999
tagged with: repeat
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89086971
has answer: http://stackoverflow.com/a/51048139
answer count: 4
has body: I'm trying to create this kind of output in Python ["k", "kk", "kkk", "kkkk", ...] ["rep", "reprep", "repreprep", ...] That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element. I can't find a way to do this easily, without loops.. Thanks,
upvote count: 2
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51047999
tagged with: escaping
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51047984
score: 1
has answer: http://stackoverflow.com/a/51047984

http://stackoverflow.com/comment/89039356
has text: So what you want is to have the `post` function have the signature `post(url, json, wait_exponential_multiplier, exponential_max)`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51023322
type: Comment

http://stackoverflow.com/comment/89082443
comment on: http://stackoverflow.com/q/51030608
score: 0
has text: It would be great if you can create a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) that we can run to reproduce that behavior. If what you say it true, that's a bug in the function.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51165271
has body: Using c_float for argtypes and c_int for restype works for me: foo.c: int foo(const char* dir, float a, float b, float c, float d ) { printf("%s\n", dir); printf("%f\n", a); printf("%f\n", b); printf("%f\n", c); printf("%f\n", d); return 0; } With Python 2.7: &gt;&gt;&gt; f = ctypes.CDLL('./foo.so') &gt;&gt;&gt; f.foo.argtypes = [ctypes.c_char_p, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float] &gt;&gt;&gt; f.foo.restype = ctypes.c_int &gt;&gt;&gt; f.foo('hello', 1.0, 1.1, 1.2, 1.3) hello 1.000000 1.100000 1.200000 1.300000 0 &gt;&gt;&gt;
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89314196
type: Answer
answers question: http://stackoverflow.com/q/51164980
accepted answer of: http://stackoverflow.com/q/51164980

http://stackoverflow.com/a/51070998
type: Answer
score: -1
has body: You can create a class with an __add__ method: class Ip: def __init__(self, _ip:str, _stop = 999) -&gt; None: self.ip = _ip self.stop = _stop def __add__(self, _val): _ip = list(map(int, self.ip.split('.'))) _r = 0 while _r &lt; 4: result = _ip[3 -_r]+_val if result &lt; self.stop: _ip[3 - _r] += _val break _ip[3 - _r] += _val%self.stop _val = _val%self.stop _r += 1 _ip[4 - _r] = 1 return Ip('.'.join(map(str, _ip))) def __repr__(self): return f'&lt;IP {self.ip}&gt;' p = Ip('192.168.1.1') new_p = p + 1 print(new_p) print(p + 1000) Output: &lt;IP 192.168.1.2&gt; &lt;IP 192.168.2.1&gt;
downvote count: 1
answers question: http://stackoverflow.com/q/51070784
has comment: http://stackoverflow.com/comment/89133744
upvote count: 0

http://stackoverflow.com/comment/89134853
type: QuestionComment
comment on: http://stackoverflow.com/q/51071343
has text: The website address is https://carmel.orangetheoryfitness.com/apps/otf/classes however it is behind a login page so I am not certain you will be able to view it. I have provided a copy of the html at a pastebin. https://pastebin.com/BnvdZmSp. I am currently using beautifulsoup to search the html. Do I need to be using something else?
score: 0
type: Comment

http://stackoverflow.com/comment/89233559
type: AnswerComment
has text: Already tried little Endian but it didnt work. I found the solution myself. Posted a new answer.
comment on: http://stackoverflow.com/a/51110030
type: Comment
score: 0

http://stackoverflow.com/q/51102243
has body: When creating Python script on Jupyter, is it possible to call a function from another Python file? When I try to call, it works on Terminal but does not work on Jupyter.
has answer: http://stackoverflow.com/a/58267758
has answer: http://stackoverflow.com/a/51102352
type: Question
has comment: http://stackoverflow.com/comment/89191742
score: 4
favorite count: 0
answer count: 3
tagged with: python
has title: Is it possible to call function from another Python file on Jupyter?
tagged with: jupyter
tagged with: jupyter-notebook
type: UnansweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/63761168
upvote count: 7

http://stackoverflow.com/a/51027162
answers question: http://stackoverflow.com/q/51025188
type: Answer
has comment: http://stackoverflow.com/comment/89047630
has body: You probably have checkpoint files for an old version or your model. Clear the output folder and re-run your script. P.S.: I ran it on my machine and it works fine
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51025188

http://stackoverflow.com/comment/89103101
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51055979
has text: @HarshSharma - I test your original solution and poblem is with filtering `Internaldf[Internaldf['Status']=='deny'][Internaldf['SrcIP']!="NA"][Internaldf['DstIP']!="NA"][Internaldf['TimeStamp']-Internaldf['TimeStamp'].iloc[0]<pd.tslib.Timedelta(minutes=30)]`, check [this](https://stackoverflow.com/q/41710789) for more info

http://stackoverflow.com/q/51099514
tagged with: returnn
has comment: http://stackoverflow.com/comment/89187029
type: Question
has comment: http://stackoverflow.com/comment/89186423
answer count: 1
has answer: http://stackoverflow.com/a/51099583
has body: When I am trying to execute the following command: python3.6 rnn.py demos/demo-act-lstm.12ax.config (this config). I get the following error: Device cpu0 proc exception: When compiling the inner function of scan the following error has been encountered: The initial state (`outputs_info` in scan nomenclature) of variable IncSubtensor{Set;:int64:}.0 (argument number 2) has dtype float32, while the result of the inner function (`fn`) has dtype float64. This can happen if the inner function of scan results in an upcast or downcast. Unhandled exception &lt;class 'ValueError'&gt; in thread &lt;_MainThread(MainThread, started 140379522152192)&gt;, proc 12162.
accepted answer: http://stackoverflow.com/a/51099583
score: 0
tagged with: python
has title: Error when running rnn.py on a config file
type: AnsweredQuestion

http://stackoverflow.com/q/51148730
has comment: http://stackoverflow.com/comment/89281561
score: 4
has comment: http://stackoverflow.com/comment/89281715
has body: My debugger uses AST instrumentation to get notifications for all logical steps of code execution (including steps in expression evaluation). There is one step I'm not able to pin down -- the moment when for-loop is just about to assign new value to the loop variable. Inside For-node the loop variable (or something more complicated) is represented with an expression inside target attribute. This expression has ctx attribute set to ast.Store(). I don't know how to trace the usage of this node. As a special case, I could replace simple loop variables with indexing to locals(): for locals()["i"] in range(10): print(i) This would give me a ctx=ast.Load() node inside the ctx=ast.Store() node and I know how to trace this. Unfortunately this won't scale to more complex targets. How does the interpreter use these ctx=ast.Store() expressions? Can I somehow instrument them directly to get notified when interpreter performs the store operation?
accepted answer: http://stackoverflow.com/a/51149910
has title: How to instrument Python AST for tracing store operations?
has comment: http://stackoverflow.com/comment/89281781
answer count: 1
has comment: http://stackoverflow.com/comment/89281922
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51149910
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: interpreter
downvote count: 0
has comment: http://stackoverflow.com/comment/89282111
has comment: http://stackoverflow.com/comment/89282015
favorite count: 0
type: Question
tagged with: abstract-syntax-tree

http://stackoverflow.com/a/51062831
has body: Use np.cumsum or pd.Series.cumsum what perfectly working with numeric and strings: df['NewCol'] = df.groupby('colA')['colB'].apply(np.cumsum) Or: df['NewCol'] = df.groupby('colA')['colB'].apply(pd.Series.cumsum) print (df) colA colB NewCol 0 1 val1 val1 1 1 val2 val1val2 2 1 val3 val1val2val3 3 2 val4 val4 4 2 val5 val4val5 5 2 val6 val4val5val6 6 3 val7 val7 7 3 val8 val7val8 8 3 val9 val7val8val9
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51060309

http://stackoverflow.com/comment/89519772
type: Comment
has text: `list(map(lambda ...))` is *not* a list comprehension.
comment on: http://stackoverflow.com/a/51156780
type: AnswerComment
score: 0

http://stackoverflow.com/q/51163233
has comment: http://stackoverflow.com/comment/89519128
answer count: 1
has body: I am having a heck of a time getting a load data local infile to work with python. I have tried a bunch of different ways in Python 3.6.5: sqlpath = '\\corp.domain.com\dept\DCGSI\Extracts\SIM\' sqlpath = "\\corp.domain.com\dept\DCGSI\Extracts\SIM\" sqlpath = '\\\\corp.domain.com\\dept\\DCGSI\\Extracts\\SIM\\' sqlpath = '//corp.domain.com/dept/DCGSI/Extracts/SIM/' sqlpath = os.path.join("\\corp.domain.com","dept","DCGSI","Extracts","SIM") sqlpath = os.path("\\\\corp.domain.com\dept\DCGSI\Extracts\SIM\") I can't seem to get the escaping right for use in the following to save my sanity. I have read at least 10 different posts here and tried all those suggestions. What am I doing wrong so I can use the unc path in the loadQuery. Here is the (CURRENT) entire script: import config import os import pymysql username = config.username dbpassword = config.dbpassword dbhost = config.dburl conn = pymysql.connect(host=dbhost, port=3306,user=username,password=dbpassword,db='dcgsreports',autocommit=True,local_infile=1) path = '//corp.domain.com/dept/DCGSI/Extracts/SIM' tables = [] files = [] fileNames = os.listdir(path) for fileNames in fileNames: if fileNames.endswith(".csv"): files.append(fileNames) tables.append(fileNames.split('.')[0]) for f,t in zip(files, tables) : truncQuery = '''TRUNCATE TABLE %s''' %t loadQuery = '''LOAD DATA LOCAL INFILE '//corp.domain.com/dept/DCGSI/Extracts/SIM/%s' INTO TABLE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES;''' %(f, t) print(loadQuery) cursor = conn.cursor() cursor.execute(truncQuery) cursor.execute(loadQuery) conn.commit() conn.close() that print statement shows the following is what should be passed as the query (which should be correct): LOAD DATA LOCAL INFILE '//corp.domain.com/dept/DCGSI/Extracts/SIM/SIM_Availability.csv' INTO TABLE SIM_Availability FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ' ' IGNORE 1 LINES; All of the tables are empty though which s…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89519427
tagged with: unc
has title: Python and MySQL escape sequence for UNC path
tagged with: python
has comment: http://stackoverflow.com/comment/89309796
type: AnsweredQuestion
tagged with: mysql
has comment: http://stackoverflow.com/comment/89310099
type: Question
has answer: http://stackoverflow.com/a/51272576
accepted answer: http://stackoverflow.com/a/51272576
has comment: http://stackoverflow.com/comment/89519469
has comment: http://stackoverflow.com/comment/89519575
score: 0

http://stackoverflow.com/a/51016889
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51016711
has body: This code is collecting a string representation of a, and then building another string with it. You need to define an external list, to account for the list comprehension expression. c = ["{}".format(a) for b, a in sorted(values.items()) if a and b not in ['SecureHash']] Further, to break down how c is being assembled, you can expand the list comprehension: c = [] for b, a in sorted(values.items()): if a and b not in ['SecureHash']: c.append('{}'.format(a)) Finally, just combine the three parts: data = formatted_data + "|" + "|".join(c)
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89027694

http://stackoverflow.com/comment/89091017
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51048031
has text: Okay, but why are you still passing the folder? I thought you wanted to use the zipped file? "can't figure out how to do the same with zipped folders that are inputted to function."

http://stackoverflow.com/comment/89503638
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51126702
has text: Thank you very much for your informative answer and sorry, for my late response. An other problem in my Pipeline (analyzing a 1.8 billion edges graph containing protein sequences) came up and I had to focus on it for the last weeks. I will test your suggestion using vfork() as soon as i find the time.

http://stackoverflow.com/a/51084443
answers question: http://stackoverflow.com/q/51083887
score: 0
type: Answer
has body: Assuming the model is foreign keyed to the user, you're looking for the on_delete property of the foreign key, use models.SET() See: https://docs.djangoproject.com/en/2.1/ref/models/fields/ https://docs.djangoproject.com/en/2.1/_modules/django/db/models/deletion/#SET

http://stackoverflow.com/q/51093232
has answer: http://stackoverflow.com/a/51093247
tagged with: python
tagged with: pygame
has title: Increase a variable up to a maximum size
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/51093263
has body: I'm working on a simple game that you put the number of enemies and you hit them or cure yourself. But, the player has a maximum amount of 500 of life. The cure uses random.randint(10,14). if player_sp &gt;= 10: if player_vida &lt; 500: cura = random.randint(10,14) player_vida += cura print("Foi adicionado %i de vida!"%cura) player_sp -= 10 This is the code to cure, but if you are curing the player the amount of life may pass 500. How can I cure the player without exceeding 500 in python? I tried making another if else using player_vida >= 500 but it didn't work.
type: Question
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51093263
favorite count: 0
possible better answer: http://stackoverflow.com/a/51093247

http://stackoverflow.com/a/51028942
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51019043
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89150062
has body: The flags GCC gets come from one of the env variables. Enter $ python -c "from distutils import sysconfig;\ print(sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',\ 'BASECFLAGS', 'LDFLAGS', 'CCSHARED', 'LDSHARED', 'SO'))" to print them. This is what distutils uses by default for extension compilation. Now check which env var introduces which flag and override the env vars accordingly, for example $ CC="gcc-7.3.0" CFLAGS="-Ofast" python setup.py build_ext to use the specific compiler version and turn on O3 optimizations. Also, it looks like you're using numpy.distutils instead of vanilla distutils, so be aware of extra include/link flags numpy adds under the hood.
has comment: http://stackoverflow.com/comment/89146965
has comment: http://stackoverflow.com/comment/89146912

http://stackoverflow.com/q/51021140
has title: Can't click on the first suggestion or first value
has answer: http://stackoverflow.com/a/51021582
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: python
tagged with: selenium-chromedriver
tagged with: selenium
type: Question
has body: I'm trying to scrape the data from the website http://www.lacoteimmo.com/prix-de-l-immo/location/pays/france.htm#/. I'm struggling to click on the first suggestion. I managed this code as below: #!/usr/bin/python # -*- coding: utf-8 -*- import re import time import csv import unittest import sys import datetime import os.path import pandas as pd from geopy.geocoders import GoogleV3 from datetime import datetime from selenium import webdriver from bs4 import NavigableString from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import WebDriverException from bs4 import BeautifulSoup from bs4.element import Tag from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.remote.errorhandler import ErrorHandler def main(self): CITIES = ["La Rochelle"] self.driver = webdriver.Chrome() driver=self.driver ID=1 for city in CITIES: print str(city) +" , "+str(ID) ID+=1 try: driver.get("http://www.lacoteimmo.com/prix-de-l-immo/location/pays/france.htm#/") driver.implicitly_wait(30) driver.find_element_by_css_selector("#mapAutosuggest").send_keys(city) # Enter city # Wait until autosuggestion come and click on first suggestion condition = EC.visibility_of_element_located((By.CSS_SELECTOR, '#mapAutosuggest + span &gt; span:nth-child(1)')) WebDriverWait(driver, 5).until(condition).click() driver.implicitly_wait(50) except NoSuchElementException: #spelling error making this code not work as expected pass self.driver.quit()
has answer: http://stackoverflow.com/a/51026349

http://stackoverflow.com/q/51025634
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51025731
has comment: http://stackoverflow.com/comment/89043818
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89043736
has comment: http://stackoverflow.com/comment/89043796
has comment: http://stackoverflow.com/comment/89043720
has answer: http://stackoverflow.com/a/51025694
has body: I have a list of tuples consisting of x,y coordinates ordered in a specific way and want to convert this to a dictionary, where each tuple has a different key. How should I do this? If names is not doable, numbers would be fine as well. Eventually the goal is to plot all the different points as categories. # list of tuples ordered_points = [(1188.0, 751.0),(1000.0, 961.0),(984.0, 816.0),(896.0, 707.0),(802.0, 634.0),(684.0, 702.0),(620.0, 769.0)] # what I want orderder_points_dict = {'pointing finger':(1188.0, 751.0), 'middle finger':(1000.0, 961.0) etc...}
has answer: http://stackoverflow.com/a/51025745
possible better answer: http://stackoverflow.com/a/51025743
has comment: http://stackoverflow.com/comment/89043761
has answer: http://stackoverflow.com/a/51025743
downvote count: 0
linked to: http://stackoverflow.com/q/209840
has title: Convert a list of tuples to dictionary, giving each tuple a different key
favorite count: 0
accepted answer: http://stackoverflow.com/a/51025694
tagged with: python

http://stackoverflow.com/comment/89221126
has text: @connectyourcharger But your keyboard input gives you the newlines locally when you type and hit Enter, so you don't need to print newlines from the code.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51117422
type: AnswerComment

http://stackoverflow.com/q/51045533
tagged with: pandas
tagged with: python
has title: Python - Pandas histogram width
accepted answer: http://stackoverflow.com/a/51046054
tagged with: plot
type: Question
type: AnsweredQuestion
answer count: 1
has body: I am doing a histogram plot of a bunch of data that goes from 0 to 1. When I plot I get this As you can see, the histogram 'blocks' do not align with the y-axis. Is there a way to set my histogram in order to get the histograms in a constant width of 0.1? Or should I try a diferent package? My code is quite simple: import pandas as pd import numpy as np from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt np.set_printoptions(precision=10, threshold=10000, linewidth=150,suppress=True) E=pd.read_csv("FQCoherentSeparableBons5.csv") E = E.ix[0:,1:] E=np.array(E,float) P0=E[:,0] P0=pd.DataFrame(P0,columns=['P0']) scatter_matrix(P0, alpha=0.2, figsize=(6, 6), diagonal='hist',color="red") plt.suptitle('Distribucio p0') plt.ylabel('Frequencia p0') plt.show() PD: If you are wondering about the data, I is just a random distribution from 0 to 1.
tagged with: histogram
has answer: http://stackoverflow.com/a/51046054
score: 0

http://stackoverflow.com/q/51073982
has answer: http://stackoverflow.com/a/51074032
duplicate of: http://stackoverflow.com/q/4289331
downvote count: 3
linked to: http://stackoverflow.com/q/4289331
type: Question
answer count: 2
has title: RegEx: Extract Unknown # of Numbers of Unknown Length, With Separators, and Characters to Ignore
has comment: http://stackoverflow.com/comment/89137492
score: -2
has answer: http://stackoverflow.com/a/51074051
favorite count: 0
has body: I am looking to extract numbers in the format: [number]['/' or ' ' or '\' possible, ignore]:['/' or ' ' or '\' possible, ignore][number]['/' or ' ' or '\' possible, ignore]:... For example: "4852/: 5934: 439028/:\23" Would extract: ['4852', '5934', '439028', '23']
tagged with: python
tagged with: regex
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/a/51061195
type: Answer
has body: Okay requests gets only the html and doesnt load the js you have to use webdriver for that you can use Chrome, Firefox and etc.. i use PhantomJS because is running in the background its "headless" browser. Underneath you will find some example code that will help you understand how to use it from bs4 import BeautifulSoup import time from selenium import webdriver driver = webdriver.PhantomJS() driver.get("https://www.betbrain.com/football/world/") time.sleep(5)# you can give it some time to load the js html = driver.page_source soup = BeautifulSoup(html, 'lxml') for i in soup.findAll("span", {"class": "Participant1"}): print (i.text)
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/89113304
has comment: http://stackoverflow.com/comment/89113315
has comment: http://stackoverflow.com/comment/89113767
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51060212
answers question: http://stackoverflow.com/q/51060212

http://stackoverflow.com/comment/89058519
type: Comment
type: QuestionComment
has text: Your code worked for me with my simple xml files. I think your xml files may be malformed.
comment on: http://stackoverflow.com/q/51033050
score: 0

http://stackoverflow.com/a/51105282
accepted answer of: http://stackoverflow.com/q/51105003
answers question: http://stackoverflow.com/q/51105003
type: AcceptedAnswer
downvote count: 0
has body: Just check that suggest has at least one item: you can have an error without a proposed correction: for error in language: if len(error.suggest())&gt;0: correction = error.suggest()[0] error.replace("%s" %(correction))
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/51063868
score: 0
type: Answer
has body: You can define your output directory outside your loop. You may, as below, wish to check whether it exists, creating the directory via os.mkdir if it does not exist. # define output directory output_dir = os.path.join(root, 'Contact Account Name') # create the directory if it doesn't exist if not os.path.exists(output_dir): os.mkdir(output_dir) for i, x in carriers.groupby('Contact Account Name'): # create output path from output directory p = os.path.join(output_dir, f'{i.upper()}.csv') x.to_csv(p, index=False) Note in the example above I use f-strings, available in Python 3.6+ and more readable / efficient.
answers question: http://stackoverflow.com/q/51063597

http://stackoverflow.com/comment/89132406
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51063623
type: AnswerComment
has text: Is is better to not place stuff under a home directory, it complicates lots of things.

http://stackoverflow.com/q/51027889
score: -1
has comment: http://stackoverflow.com/comment/89048903
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89048315
answer count: 1
has body: I have two hundred thousand records in the SQL table. The model has 6 fields. Considered that duplicate is the match of 3 or more fields with any another tuple in this table. I need to find duplicates and their number for each row in this table
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51028305
has title: Search for duplicates
tagged with: duplicates
type: Question
tagged with: search

http://stackoverflow.com/a/51023793
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51022080
type: Answer
has comment: http://stackoverflow.com/comment/89110957
accepted answer of: http://stackoverflow.com/q/51022080
has body: pip is not a full blown package manager, it doesn't have such concepts as "This package is incompatible with that" or "This package replaces that". What you're trying to do is emulating these important concepts. Unfortunately that doesn't work. pip runs setup.py on user hosts only for source distributions (sdist). For eggs/wheels pip runs setup.py on the developer host and there is no way to configure a pre-install script to be run on user hosts, and wheels these days is the preferred distribution format. You best bet is to ask user (via documentation) to uninstall docker-py manually.
score: 0

pca
tag name: pca
tags question: http://stackoverflow.com/q/51040075
type: Tag
tags question: http://stackoverflow.com/q/51064456

http://stackoverflow.com/comment/89265439
type: Comment
has text: You should check if user isn't staff before login it
comment on: http://stackoverflow.com/a/51139890
score: 0
type: AnswerComment

http://stackoverflow.com/q/51034265
tagged with: python
accepted answer: http://stackoverflow.com/a/51034302
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89060666
possible better answer: http://stackoverflow.com/a/51034318
has title: Trouble with Palindrome function in python
type: Question
has comment: http://stackoverflow.com/comment/89089603
tagged with: palindrome
has body: I'm having trouble in an online course for python, specifically a palindrome problem These are the instructions, but the function must be case-insensitive and not see spaces. I think the issue is in my return blocks or my flow. I think I need to use the lower function, but I'm honestly not sure. def student_func(x): for string in x: x.lower() y = x.replace(" ", "") if y[::-1]==y: return True else: return False
has comment: http://stackoverflow.com/comment/89060691
has answer: http://stackoverflow.com/a/51034302
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89060617
has comment: http://stackoverflow.com/comment/89061002
has answer: http://stackoverflow.com/a/51034318

http://stackoverflow.com/q/51079515
upvote count: 1
tagged with: qtablewidget
has comment: http://stackoverflow.com/comment/89152036
has title: Why Performance of PyQt5 QTableWidget Setitem Much Faster than PySide2?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89152760
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89147826
score: 1
has body: I have a data with 1000 records showing in QTableWidget (13 columns), after refresh 4 times, I get setItem 52000 times, and using pycharm Profile method, the time for 52000 times is 84ms. After PySide2 come out ( Qt for Python 5.11 mid May), I only change from "from PyQt5... import ..." to "from PySide2... import ..." for my program, the time for 52000 times is 3171ms. I know both PyQt5 and PySide2 depend on Qt5, but the performance shocked. I want to use PySide2 for future with LGPL, how can I fix it ? #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from PySide2.QtWidgets import QApplication, QTableWidgetItem, QMainWindow, QTableWidget class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(200, 300, 960, 540) self.table = QTableWidget() self.setCentralWidget(self.table) self.table.setRowCount(1000) self.horizontal_header = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"] self.table.setColumnCount(len(self.horizontal_header)) self.table.setHorizontalHeaderLabels(self.horizontal_header) for i in range(4): self._run() raise NameError def _run(self): for row in range(1000): for column in range(13): item = QTableWidgetItem('1') self.table.setItem(row, column, item) if __name__ == '__main__': app = QApplication(sys.argv) mainwindow = MainWindow() mainwindow.show() sys.exit(app.exec_())
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89148818
tagged with: pyside2
tagged with: pyqt5

http://stackoverflow.com/q/51161506
possible better answer: http://stackoverflow.com/a/51164627
has comment: http://stackoverflow.com/comment/89312355
tagged with: sum
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89316854
upvote count: 2
accepted answer: http://stackoverflow.com/a/51202904
has comment: http://stackoverflow.com/comment/89312814
has body: I'm working with a data frame like this, but bigger and with more zone. I am trying to sum the value of the rows by their names. The total sum of the R or C zones goes in total column while the total sum of either M zones goes in total1 . Input: total, total1 are the desired output. ID Zone1 CHC1 Value1 Zone2 CHC2 Value2 Zone3 CHC3 Value3 total total1 1 R5B 100 10 C2 0 20 R10A 2 5 35 0 1 C2 95 20 M2-6 5 6 R5B 7 3 23 6 3 C2 40 4 C4 60 6 0 6 0 10 0 3 C1 100 8 0 0 0 0 100 0 8 0 5 M1-5 10 6 M2-6 86 15 0 0 0 0 21
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/89312670
has comment: http://stackoverflow.com/comment/89307592
has comment: http://stackoverflow.com/comment/89306587
favorite count: 0
has title: Summing by string names Pandas
has answer: http://stackoverflow.com/a/51202904
has comment: http://stackoverflow.com/comment/89312479
has comment: http://stackoverflow.com/comment/89311585
tagged with: python
has comment: http://stackoverflow.com/comment/89306729
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89369339
score: 1
has comment: http://stackoverflow.com/comment/89306475
has comment: http://stackoverflow.com/comment/89312755
has answer: http://stackoverflow.com/a/51164627
has comment: http://stackoverflow.com/comment/89312442
type: Question
answer count: 2

http://stackoverflow.com/comment/89021053
type: Comment
comment on: http://stackoverflow.com/q/51013775
score: 0
has text: Also: Cosmos DB collections are *not* limited to 10,000 RUs. Only single-partition collections are limited that way. If you create a partitioned collection (easiest to do this through the portal, at least as you're starting out), you can turn the RU up significantly higher (at least 100K RU without having to make a support request to go higher - I can't recall exactly)
type: QuestionComment

http://stackoverflow.com/q/51164739
has body: If I had a nested list: Nes = [[2, 2], [4, 4], [8, 8], [16, 16]] Would there any possible way to "unnest" it by making all the brackets inside the list go away so that Nes now looks like: Nes = [2, 2, 4, 4, 8, 8, 16, 16]
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51164759
tagged with: python
score: -1
tagged with: nested-lists
downvote count: 2
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/952914
duplicate of: http://stackoverflow.com/q/952914
answer count: 2
has answer: http://stackoverflow.com/a/51164756
has title: Unmaking a nested list
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51035899
downvote count: 0
score: 1
has body: The attributes of the EmailMessage class are assigned dynamically, like this*: class EmailMessage(_EmailMessageBase): def __init__(self, **kwargs): for name, value in kwargs.items(): setattr(self, name, value) Therefore, if attachments isn't passed to the constructor as a keyword argument, the instance has no attachments attribute, and you get an AttributeError if you try to reference it. As Jofre observes in their answer, you can still assign to attachments directly: message.attachments = [attachment1] after the attachments attribute has been created, you can also append to it: message.attachments.append(attachment2) * This is a simplified version; in the real class the assignment is done in a separate method, but in essentially the same way.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51035246

http://stackoverflow.com/a/78754807
answers question: http://stackoverflow.com/q/51121911
has body: Seeing the answers above - except the mostly voted one (which doesn't fully cover the request) - it was mainly division in a loop. Why not keep it more "programmatic", even if yet not that pythonic? Here is example based on original question (no division used): sample = "This is a string" n = 3 # I want to iterate over every third element i = 1 for x in sample: if n == i: i = 0 # do something with x else: # do something else with x i += 1 If you sill like to process with valid index: sample = "This is a string" n = 3 # I want to iterate over every third element # (!) here do something else with all elements within list/substring: sample[0:n-1] for i in range(n-1, len(sample), n): # (!) here do something with element: sample[i] # (!) here do something else with all elements within list/substring: sample[i+1:i+n] And now coming back to solution with division, but as a single line: sample = "This is a string" n = 3 # I want to iterate over every third element # you can call below your own correspondent functions (according to case) instead of print() ;-) _ = [print('Do something: ' + sample[i]) if 0 == ((1+i) % n) else print('Do something else: ' + sample[i]) for i in range(len(sample))]
type: Answer
score: 0

http://stackoverflow.com/comment/89297870
type: AnswerComment
comment on: http://stackoverflow.com/a/51153033
type: Comment
score: 1
has text: @xavor Very good! Actually the greater impact of using `np.frombuffer` is that it reduces time for data conversion from `bytes` to `np.array` by 4 orders of magnitude, basically removing this bottleneck. The approach in my answer is limited by conversion speed which is only ~ 5x faster than applying the function in the OP. With `np.frombuffer` the bottleneck is again bit-shifting and so the actual speed-up of using the `np.frombuffer` approach (compared to `np.fromiter`) is a factor of ~ 60x on my computer. So that approach really deserves its own answer.

http://stackoverflow.com/q/51022577
linked to: http://stackoverflow.com/q/40927057
tagged with: numpy
score: 2
answer count: 1
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/51048432
favorite count: 0
has title: Deleting consecutive RGB values from a numpy array
has comment: http://stackoverflow.com/comment/89067700
linked to: http://stackoverflow.com/q/37839928
linked to: http://stackoverflow.com/q/50743769
tagged with: python
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51048432
has comment: http://stackoverflow.com/comment/89066544
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89068550
type: Question
tagged with: python-imaging-library
has body: I initially created a subarray from the initial array for a greyscale image from this: Deleting consecutive numbers from a numpy array and Remove following duplicates in a numpy array But now I want to do the same for a coloured image and I'm really confused. I've been working on it for days and simply cannot make sense of how I can approach it. The problem is the squares are different sizes and I want a pixel for each square represented with the same colour. Coloured image: Coloured image My code for greyscale image: from PIL import Image import numpy as np name1 = raw_input("What is the name of the .png file you want to open? ") filename1 = "%s.png" % name1 img = Image.open(filename1).convert('L') # convert image to 8-bit grayscale WIDTH, HEIGHT = img.size a = list(img.getdata()) # convert image data to a list of integers # convert that to 2D list (list of lists of integers) a = np.array ([a[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]) print " " print "Intial array from image:" #print as array print " " print a rows_mask = np.insert(np.diff(a[:, 0]).astype(np.bool), 0, True) columns_mask = np.insert(np.diff(a[0]).astype(np.bool), 0, True) b = a[np.ix_(rows_mask, columns_mask)] print " " print "Subarray from Image:" #print as array print " " print b #img = Image.fromarray(b, mode='L') print " " print "Subarray from Image (clearer format):" #print as array print " " for row in b: #print as a table like format print(' '.join('{:3}'.format(value) for value in row)) #img.save("chocolate.png") #print np.mean(b) #finding mean For example for this image: Input array example: From a = list(img.getdata()), this is the input I get from the image. [(115, 45, 135), (115, 45, 135), (115, 45, 135), (115, 45, 135), (115, 45, 135), (245, 245, 35), (245, 245, 35), (245, 245, 35), (245, 245, 35), (245, 245, 35), (245, 245, 35), (115, 45, 135), (115, 45, 135), (115, 45, 135), (115, 45, 135), (115, 45, 135), (245, 245, 35), (245, 245, 35), (245, 245, 35), (245, 2…

http://stackoverflow.com/q/51129410
tagged with: web-scraping
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51129544
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has body: I'm going through Automate Boring Stuff with Python and I'm stuck at the chapter about downloading data from the internet. One of the tasks is download photos for a given keyword from Flickr. I have a massive problem with scraping this site. I've tried BeautifulSoup (which I think is not appropriate in this case as it uses Javascript) and Selenium. Looking at the html I think that I should locate 'overlay' class. However no matter which option I use (find_element_by_class_name, ...by_text, ...by_partial_text) I am not able to find these elements (I get: ". Could you please help me to clarify what I'm doing wrong? I'd be also grateful for any materials that could help me understadt such cases better. Thanks! Here's my simple code: import sys search_keywords = sys.argv[1] from selenium import webdriver browser = webdriver.Firefox() browser.get(f'https://www.flickr.com/search/?text={search_keywords}') elems = browser.find_element_by_class_name("overlay") print(elems) elems.click() Sample keywords I type in shell: "industrial design interior"
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51129544
has title: Scraping Flickr with Selenium/Beautiful soup in Python - ABSWP
score: 1
tagged with: selenium

http://stackoverflow.com/a/76148344
answers question: http://stackoverflow.com/q/51035992
score: 0
has body: coordinates of bounding box: import cv2 im = cv2.imread('your image.png') (h, w) = im.shape[:2] box = {'Height': 0.45597776770591736, 'Left': 0.16144350171089172, 'Top': 0.21130676567554474, 'Width': 0.5840455889701843} x,y,w,h = (box['Left'] * width, box['Top'] * height, box['Width'] * width, box['Height'] * height ) cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2) cv2.imshow('img',im) cv2.waitKey(0)
type: Answer

http://stackoverflow.com/comment/89320549
type: Comment
type: AnswerComment
has text: @amplifier I update my answer with two edits you need make. You can check and have a try. As for systemProperties in your code, you can remove them if you don't need. Feel free let me know if it doesn't work.
comment on: http://stackoverflow.com/a/51166935
score: 0

http://stackoverflow.com/a/51077658
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51077590
type: Answer
score: 2
downvote count: 0
has body: I think here is better pure python solution with Counter of joined all values to long string with split: from collections import Counter d = Counter(' '.join(df).split()) #if necessary convert to dict #d = dict(Counter(' '.join(df).split())) Or use split with stack first: d = df.str.split(expand=True).stack().value_counts().to_dict() print (d) {'Rockwell': 4, '4632': 4, 'Street,': 3, '773': 3, '60625': 3, 'N.': 3, 'N': 2, 'Rock': 2, 'Chicago': 2, 'Kedzie': 1, 'Grill': 1, 'Neighborhood': 1, '3658': 1, 'Lawren': 1, 'W': 1, '4748': 1, 'LA': 1, 'hood': 1, "Rockwell'": 1, 'Bdoy': 1}
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51077590

http://stackoverflow.com/comment/89281278
score: 0
type: Comment
has text: what is `a` supposed to be referring to? This looks like a good solution it's just annoying that I can't simply set the column names using the `column` parameter
comment on: http://stackoverflow.com/a/51146438
type: AnswerComment

http://stackoverflow.com/comment/89228036
score: 0
type: AnswerComment
type: Comment
has text: Thank you very much. :) I am a beginner OpenCV user.
comment on: http://stackoverflow.com/a/51121252

http://stackoverflow.com/a/51047710
upvote count: 3
has body: So there are two issues with function_details: The current frame is function_details so you need to go up one frame to get to the calling frame. To do this you pass 1 to sys._getframe. __file__ is the name of the current file for whatever module you happen to be in (if defined), this needs to be replaced with the co_filename attribute of the f_code object associated with the correct frame. Correcting both of these things, we redefine function_details as: def function_details(): code_obj = sys._getframe(1).f_code return " ".join([code_obj.co_name, os.path.basename(code_obj.co_filename)]) Which produces the desired result. In my opinion, the inspect module accomplishes this same thing far better than using sys._getframe directly. Here's the new function_details written using inspect: import inspect def function_details(): frame = inspect.getouterframes(inspect.currentframe())[1] return " ".join([frame[3], os.path.basename(frame[1])])
type: Answer
has comment: http://stackoverflow.com/comment/89095310
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/51045229
has comment: http://stackoverflow.com/comment/89095412
accepted answer of: http://stackoverflow.com/q/51045229
type: AcceptedAnswer

http://stackoverflow.com/q/51146452
downvote count: 2
answer count: 2
score: -2
has answer: http://stackoverflow.com/a/51146553
has answer: http://stackoverflow.com/a/51146545
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has body: I am scraping an html file, each page has a video on it, and in the html there is the video id. I want to print out the video id. I know that if i want to print a headline from a div class i would do this with open('yeehaw.html') as html_file: soup = BeautifulSoup(html_file, 'lxml') article = soup.find('div', class_='article') headline = article.h2.a.text print headline However the id for the video is found inside a data-id='qe67234' I dont know how to access this 'qe67234' and print it out. please help thank you!
tagged with: parsing
upvote count: 0
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python-requests
has title: Finding video id on html website using python
has comment: http://stackoverflow.com/comment/89277092
type: Question

http://stackoverflow.com/comment/89119488
comment on: http://stackoverflow.com/a/51055002
score: 0
type: AnswerComment
type: Comment
has text: Sorry, i put the code that worked, but i continue with the problem, it seems Tkinter Canvas reads only gif, pgm or ppm, in many places i read that ImageTk cold solve the problem, but nothing happens to me.

http://stackoverflow.com/comment/89185910
score: 0
has text: Correct, that's why I used Path.parent to get the directory.
type: AnswerComment
comment on: http://stackoverflow.com/a/51092853
type: Comment

http://stackoverflow.com/comment/89057466
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your warm help. I am confused about foreign key and primary key in Django. I have same column <maid> in two tables, and I want to use this ID to connect among tables. Please see my update in question, if you have time, please you give me more guide, thanks!
comment on: http://stackoverflow.com/a/51030215

http://stackoverflow.com/comment/89299155
type: Comment
type: QuestionComment
has text: Ahhh Windows. I always wonder why people use it.
score: 0
comment on: http://stackoverflow.com/q/51157679

http://stackoverflow.com/q/51032915
has comment: http://stackoverflow.com/comment/89058969
has comment: http://stackoverflow.com/comment/89058308
has comment: http://stackoverflow.com/comment/89059001
has comment: http://stackoverflow.com/comment/89059039
has body: I was trying to do a 'add member' function. Basically,when you click on the button 'add button', member names will show somewhere in this page.But I got this error: Here is part of HTML looks like: project_detail.html {% extends 'base.html' %} {% block content %} Project {{ project_id }} detail Edit Delete Members {% csrf_token %} {% for user in users %} {{ user.username }} {% endfor %} {% endblock %} {% block script %} var url = $( '#selection-button' ).attr( 'action' ); $("#selection-button").on('click', function(e) { e.preventDefault(); var value =$('#member_list').val(); $.ajax({ type:'POST', url:'add_member/'+value+'/', success:function (result) { $("#res").append(value); }, error:function (result) { alert('error'); } }); }); {% endblock %} urls.py urlpatterns = [ path('', views.project_index, name='project_index'), path('<int:project_id>/', views.project_detail, name='project_detail'), path('create/', views.project_create, name='project_create'), path('<int:project_id>/delete/', views.project_delete, name='project_delete'), path('<int:project_id>/delete_result/', TemplateView.as_view(template_name="project/delete_result.html"), name='delete_result'), path('<int:project_id>/edit/', views.project_edit, name='project_edit'), path('<int:project_id>/add_member/<int:user_id>', views.add_member, name='project_add_member'), path('<int:project_id>/task/', include('task_tracker.urls')), path('<int:project_id>/issue/', include('issue_tracker.urls',namespace='issue_tracker')), path('<int:project_id>/channel/', include('communication_channel.urls')), ] views.py def add_member(request,project_id): if request.method=='POST': members = User.objects.all() serializer = UserSerializer() return render(request,'project/project_add_member',{'project_id':project_id}) project_add_member.html {% extends 'base.html' %} {% block content %} success! {% endblock %} views.py @csrf_exempt def add_member(request,project_id,user_id): project = get_object_or_404(Project, id=project_id) user = …
answer count: 1
has comment: http://stackoverflow.com/comment/89058227
tagged with: python
has comment: http://stackoverflow.com/comment/89059177
score: 0
has title: Page 404 not found django
type: UnansweredQuestion
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/51032945
has comment: http://stackoverflow.com/comment/89058143

http://stackoverflow.com/comment/89148393
type: Comment
type: QuestionComment
has text: Every time you call your function, you reset `n` to `-1` before adding one (the first line of the function is `n= -1`). So `n` is always zero (which is the first array index)..
score: 0
comment on: http://stackoverflow.com/q/51079898

http://stackoverflow.com/a/51068032
answers question: http://stackoverflow.com/q/51067197
score: 0
type: Answer
has body: Lets say you already read the lists from the files and places them in lists variable: ResponseTweetsAug27 = [('beprep', 239), ('gear up', 164)] ImpactTweetsAug27 = [('get ready', 1350), ('falling', 1267)] lists = [ResponseTweetsAug27, ImpactTweetsAug27] key_terms = ['beprep', 'gear up', 'get ready'] for l in lists: for pair in l: if pair[0] in key_terms: print(pair[0], pair[1]) You can iterate through lists. Every item is a list. Then in every list (here it is called l) you iterate through every pair checking if the name/title, whatever you call it, exists in key_terms. If it does, you print it out, and the number of times they are mentioned. The result: &gt; python tuples.py beprep 239 gear up 164 get ready 1350

http://stackoverflow.com/q/51116967
has answer: http://stackoverflow.com/a/51117045
linked to: http://stackoverflow.com/q/1132941
has answer: http://stackoverflow.com/a/51117060
has body: The intended objective of function foo is to add the number provided as argument to the list and, in case it is 0, reset the list. First I wrote this program: def foo(n, bar = []): if n == 0: bar = [] print("list empty") else: bar.append(n) for y in bar: print(y, end=', ') print() foo(5) foo(3) foo(0) foo(6) output: 5, 5, 3, list empty 5, 3, 6, but it looks like bar = [] is ignored. Then I changed bar = [] with bar.clear() and it works as I thought: def foo(n, bar = []): if n == 0: bar.clear() print("list empty") else: bar.append(n) for y in bar: print(y, end=', ') print() foo(5) foo(3) foo(0) foo(6) output: 5, 5, 3, list empty 6, I haven't understood why bar.clear() works differntly from bar = [] since clear() should Remove all elements from the set. so the same thing bar = [] does. Edit: I don't think my question is a duplicate of “Least Astonishment” and the Mutable Default Argument, I'm aware that The default value is evaluated only once. (from the official tutorial) but what I am asking is, why bar = [] doesn't edit (in this case clear) the list, while append and clear does?
has comment: http://stackoverflow.com/comment/89220109
has comment: http://stackoverflow.com/comment/89220093
has comment: http://stackoverflow.com/comment/89220136
favorite count: 0
score: 8
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51117053
has answer: http://stackoverflow.com/a/51117023
has answer: http://stackoverflow.com/a/51117053
tagged with: python
has answer: http://stackoverflow.com/a/51117031
type: AnsweredQuestion
has title: How is list.clear() different from list = []?
has answer: http://stackoverflow.com/a/51117025
has comment: http://stackoverflow.com/comment/89220208
linked to: http://stackoverflow.com/q/986006
downvote count: 1
type: Question
upvote count: 9
accepted answer: http://stackoverflow.com/a/51117031
answer count: 6

http://stackoverflow.com/q/51141366
favorite count: 0
tagged with: moving-average
has comment: http://stackoverflow.com/comment/89267538
tagged with: pandas
score: 3
has answer: http://stackoverflow.com/a/51141603
accepted answer: http://stackoverflow.com/a/51141594
tagged with: python
has comment: http://stackoverflow.com/comment/89267560
has comment: http://stackoverflow.com/comment/89267157
possible better answer: http://stackoverflow.com/a/51141603
upvote count: 3
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/89267420
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51141594
has body: I have a weekly sales dataframe Sales weekNum 83 1 139 2 207 3 278 4 274 5 291 6 319 7 305 8 I want to compute the average of first 4 weeks and paste it in the index of week 5 to 8 And I want my output dataset to look like below Sales weekNum 4-PreviousWeekAverage 83 1 139 2 207 3 278 4 274 5 176.75 291 6 176.75 319 7 176.75 305 8 176.75 Similarly I also want to compute the 8 week average and paste it in the index of 5 to 8 I tried for i in [4, 8]: newColumnName1 = '%s-PreviousWeekAverage' % i df[newColumnName1] = np.nan for ix in df.index: if ix - i &gt;= 0: df.loc[ix, newColumnName1] = np.mean(sampledf.loc[ix-i:ix-1,'Sales']) However it returns me the moving average like below Sales weekNum 4-PreviousWeekAverage 83 1 139 2 207 3 278 4 274 5 176.75 291 6 224.5 319 7 262.5 305 8 290.5 I am having an issue in looping , no able to figure out the correct script. Hence will appreciate the help.
answer count: 2
has title: How to compute the average of n rows and paste the answer to next n rows of pandas column?
downvote count: 0
has comment: http://stackoverflow.com/comment/89267089

http://stackoverflow.com/q/51115611
has comment: http://stackoverflow.com/comment/89217512
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89217407
has comment: http://stackoverflow.com/comment/89217594
has body: Here is what i couldn't figure it out. Suppose I have a simple class like class Card(object): ...... pass and I want to create a class deck which inherits the Card class, like: class Deck(Card): ...... self.cards = [....list of 52 Cards...]#this line is my question so later I can access specific card from class deck , like: #index is referring to the shuffled deck d=deck() print(d.index(5)) print(d.index(35)) output: ('Jack','Diamond') ('5','Spade') So in nutshell, my question is How to create a list of base class inside the child class?
has title: How to create a list of base class inside the child class
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51115653
favorite count: 0
has comment: http://stackoverflow.com/comment/89217379
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89217380
tagged with: oop
score: 1

http://stackoverflow.com/comment/89337328
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51159266
has text: Can you add any details like: code used, error problem encountered? [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask), [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) Show the community what you have tried.

http://stackoverflow.com/q/51124738
favorite count: 0
tagged with: geometry
has comment: http://stackoverflow.com/comment/89237064
has title: Robust and automatable droplet fitting
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89235475
downvote count: 0
has body: I'm trying to perform image analysis on a set of grayscale images like the following image: The main goal is to be able to measure the dimensions of the elliptical droplets and to identify their center coordinates. I've tried Hough Circular Transform in openCV and scikit-image. All the examples I've seen so far for scikit-images run quite slowly compared to openCV. I've had moderate success with this code (taken from the example): img = read_img[600:,:] img = cv2.medianBlur(img,5) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,30, param1=45,param2=20,minRadius=1,maxRadius=45) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # draw the outer circle cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('detected circles',cimg) fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(20, 20)) ax.imshow(cimg) which detects the main droplets, but fails to catch the three smaller ones. The best threshold I was able to construct is with these parameters for openCV th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\cv2.THRESH_BINARY,15,5) however, I'm still unable to find the smaller droplets using the code above. I have a couple thousand images that I would want to process. I would need the algorithm to be able to automatically find the optimal parameters for the transforms or thresholding. So far I have no idea how to implement something like this. Any suggestions for proper implementation would be greatly appreciated!
score: 1
tagged with: scikit-image
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/89237037
upvote count: 1
has comment: http://stackoverflow.com/comment/89241911
answer count: 1
has answer: http://stackoverflow.com/a/51126063
accepted answer: http://stackoverflow.com/a/51126063

http://stackoverflow.com/a/77711351
has body: This means you have to have enough ETH in your account to be able to buy other coin. Let's say you are trying to buy BTCETH if your available ETH funds are not enough you will not be able to buy. Available balance means, balance after your open orders. Check your open orders first. Also debug your marketBuy function. Do the following print(json.dumps(params, indent=2)) PS. You will still need some funds for the commission
type: Answer
answers question: http://stackoverflow.com/q/51014226
score: 0

http://stackoverflow.com/q/51045539
type: Question
answer count: 1
score: 0
tagged with: qt-designer
has title: Pyqt gui with buttons and number indicators placed on background image
linked to: http://stackoverflow.com/q/43126721
has answer: http://stackoverflow.com/a/51124248
tagged with: python
tagged with: qtwidgets
accepted answer: http://stackoverflow.com/a/51124248
type: AnsweredQuestion
has body: I want to develop a frontend human interface for my python script that takes various temperature and DI/DOs from Raspberry pi using custom designed electronic circuits. I have managed the python end. Now i wish to put all the input values and buttons (for operating DOs) on a LCD screen that a user can see and operate. So far i have got the schematic of a particular application on a tab in a Qwidget using stylesheets. This was done through QT Designer, as i have no knowledge of QT. I can place buttons and indicators also, however they do not move when the widget is resized. In this first image, a test button is placed where i require. Button properly placed in QT Designer. But when i resize the window, the background image moves but the button remains. Button does not move when window resized. How can i make the button position and size relative to the widget window? thanks! EDIT: A similar question asked here. I read in various forums that some combination of resizeEvent() and move() has to be used. But i dont know where to add this to my code. My current code as converted from .ui file output of QT designer to .py: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TabWidget1(object): def setupUi(self, TabWidget1): TabWidget1.setObjectName("TabWidget1") TabWidget1.setEnabled(True) TabWidget1.resize(1092, 867) # TabWidget1.move(0, 0) self.tab1 = QtWidgets.QWidget() self.tab1.setAutoFillBackground(False) self.tab1.setStyleSheet("image:url(:/images/Jaggery Unit Frontend V0.11.png)") self.tab1.setObjectName("tab1") self.pushButton = QtWidgets.QPushButton(self.tab1) self.pushButton.setGeometry(QtCore.QRect(310, 220, 75, 23)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth()) self.pushButton.setSizePolicy(sizePolicy) self.pushButton.setContextMenuPolicy(QtCore.Qt.DefaultContex…
tagged with: pyqt5
linked to: http://stackoverflow.com/q/50864375

http://stackoverflow.com/comment/89329071
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51112201
has text: Can you please modify your answer to include the treatment of negative numbers?

http://stackoverflow.com/comment/89048549
score: 6
comment on: http://stackoverflow.com/q/51028091
has text: The list comprehension version builds a new list then invokes a function call; if you don't actually *need* the new list, it seems inevitable that a simpler loop will be faster.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51049879
accepted answer of: http://stackoverflow.com/q/51024950
answers question: http://stackoverflow.com/q/51024950
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: To verify that a torrent file is valid you need bencoder/decoder implementation to parse the file and then check whether the mandatory fields from BEP3 are present and in the expected form. libtorrent provides python bindings. Bittornado should contain a pure python implementation, although it is a bit dated.
score: 1
upvote count: 1

http://stackoverflow.com/q/51160246
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51165941
has body: My Selenium Python script is unable to click add to cart button. HTML code: &lt;input type="button" value="Add to cart" title="Add to cart" class="button-2 product-box-add-to-cart-button" onclick="AjaxCart.addproducttocart_catalog ('/addproducttocart/catalog/18/1/1');return false;"&gt; My script: inputElement = driver.find_element_by_xpath("/html/body/div[7]/div[4]/div[2]/div[1]/div/div[2]/div[4]/div/div[3]/div/div[2]/div[3]/div[2]/input[3]") inputElement.click() This is the error I get: File "C:\Users\Raghav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Element &lt;input type="button" value="Add to cart" title="Add to cart" class="button-2 product-box-add-to-cart-button" onclick="AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/18/1/1');return false;"&gt; is not clickable at point (1334, 635). Other element would receive the click: &lt;div class="page-loader" style="opacity: 0.924946;"&gt;...&lt;/div&gt;
score: 0
answer count: 3
tagged with: css-selectors
has answer: http://stackoverflow.com/a/51161249
has answer: http://stackoverflow.com/a/51160275
favorite count: 0
tagged with: xpath
type: UnansweredQuestion
has title: How to click add to cart button as per the given html?
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium

http://stackoverflow.com/q/51012350
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89030935
tagged with: pyqt
tagged with: pyqt4
has title: How to run two GUIs in Python in parallel?
has body: We are talking about python 2.7 and PyQt4. I'm working with an open-source program for the eeg analysis called PyCorder, that received data from a system electrodes-amplifier and plot them in a GUI; we can consider it as a black box for the purposes of this question. I implemented a simple interface with Qt designer. My aim is to run both the PyCorder and my interface at the same time in a way that they can exchange data between them. Here the lines of the code where my interface is launched: if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) I guess it's common to any interface done with Qt designer; Following, the PyCorder launching part: def main(args): print "Starting PyCorder, please wait ...\n" setpriority(priority=4) app = Qt.QApplication(args) try: win = None win = MainWindow() win.showMaximized() if ShowConfirmationDialog: accept = Qt.QMessageBox.warning(None, "PyCorder Disclaimer", ConfirmationText, "Accept", "Cancel", "", 1) if accept == 0: win.usageConfirmed = True app.exec_() else: win.close() else: win.usageConfirmed = True app.exec_() except Exception as e: tb = GetExceptionTraceBack()[0] Qt.QMessageBox.critical(None, "PyCorder", tb + " -&gt; " + str(e)) if win != None: win.close() # show the battery disconnection reminder if ShowBatteryReminder and win and win.usageConfirmed: DlgBatteryInfo().exec_() print "PyCorder terminated\n" if __name__ == '__main__': main(sys.argv) Is it sufficient to know just these two parts of the respective codes to answer my question? Is there any toolbox that can be useful to reach my goal?
has comment: http://stackoverflow.com/comment/89030573
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89017408
has comment: http://stackoverflow.com/comment/89019462
favorite count: 0
has answer: http://stackoverflow.com/a/51012543
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51014316
downvote count: 1
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/89019490
has comment: http://stackoverflow.com/comment/89031088

http://stackoverflow.com/q/51152108
downvote count: 0
answer count: 1
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51152186
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89287615
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Pandas add a series to dataframe column
has answer: http://stackoverflow.com/a/51152186
type: Question
has body: I'm trying to add a series as a new column in another data frame. But only 'NaN' is being added. Series: a_attack = df.merge(df_2,left_on = ['team_A','year'],right_on =['countries','year_list'],how = 'left')['attack'] type(a_attack) Out[4]: pandas.core.series.Series a_attack.tail(5) Out[5]: 38881 63.0 38882 80.0 38883 81.0 38884 59.0 38885 85.0 Name: attack, dtype: float64 Below is code that I'm using to add the series 'a_attack' to dataframe df. df['A_attack'] = a_attack But I'm getting NaN values only in the dataframe df['A_attack'].tail(5) Out[9]: 38881 NaN 38882 NaN 38883 NaN 38884 NaN 38885 NaN Name: A_attack, dtype: float64

http://stackoverflow.com/q/51058053
has answer: http://stackoverflow.com/a/51058825
tagged with: visualization
accepted answer: http://stackoverflow.com/a/51058825
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: histogram
score: 1
has body: I have a dataset that contains, among other columns, 3 columns titled Gender (either M or F), House (either A or B or C), and Indicator (either 0 or 1). I want to plot the histogram of House A colored by Gender. This is my code to do this: import pandas as pd df = pd.read_csv('dataset.csv', usecols=['House','Gender','Indicator') A = df[df['House']=='A'] A = pd.DataFrame(A, columns=['Indicator', 'Gender']) This imports the values of House A for the respective genders correctly, as shown by its contents: print(A) Indicator Gender 0 1 Male 1 1 Male 2 1 Male 4 1 Female 7 1 Male 8 1 Male 11 1 Male 14 1 Male 17 1 Male 18 1 Female 19 1 Female 20 1 Female 21 1 Male 24 1 Male 26 1 Female 27 1 Male ... ... ... Now when I want to plot the histogram of A colored by gender the way I did in MATLAB, it gives an error: import matplotlib.pyplot as plt plt.hist(A) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-130-81c3aef1748b&gt; in &lt;module&gt;() ----&gt; 1 plt.hist(A) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs) 3130 histtype=histtype, align=align, orientation=orientation, 3131 rwidth=rwidth, log=log, color=color, label=label, -&gt; 3132 stacked=stacked, normed=normed, data=data, **kwargs) 3133 finally: 3134 ax._hold = washold ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1853 "the Matplotlib list!)" % (label_namer, func.__name__), 1854 RuntimeWarning, stacklevel=2) -&gt; 1855 return func(ax, *args, **kwargs) 1856 1857 inner.__doc__ = _add_data_doc(inner.__doc__, ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***) 6512 for xi in x: 6513 if len(xi) &gt; 0: -&gt; 6514 xmin = min(…
favorite count: 0
has title: How to plot a histogram of one column colored by another in Python?
tagged with: data-visualization
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question

http://stackoverflow.com/q/51059406
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51116236
tagged with: python
has comment: http://stackoverflow.com/comment/89110528
tagged with: networkx
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51116236
possible better answer: http://stackoverflow.com/a/51067370
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51100335
has answer: http://stackoverflow.com/a/51067370
type: Question
downvote count: 0
answer count: 3
score: 2
has title: Cannot save graph made in Networkx and matplotlib
linked to: http://stackoverflow.com/q/8218608
has body: I am using NetworkX and matplotlib to draw graph with png images as nodes. Here is my code: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() #DRAWING EDGES ON AXIS G.add_edges_from(([1,2],[3,4],[5,6],[7,8])) pos = nx.circular_layout(G) fig = plt.figure(figsize=(20, 20)) ax = plt.axes([0, 0, 15, 15]) ax.set_aspect('equal') nx.draw_networkx_edges(G, pos, ax=ax, arrows=True) #TRANSFORMING COORDINATES trans = ax.transData.transform trans2 = fig.transFigure.inverted().transform #PUTTING IMAGE INSTEAD OF NODES size = 0.2 p2 = size / 2.0 for n in G: xx, yy = trans(pos[n]) xa, ya = trans2((xx, yy)) a = plt.axes([xa - p2, ya - p2, size, size]) a.set_aspect('equal') a.imshow(image, aspect='auto') a.axis('off') plt.savefig('save.png') plt.show() Jupyter notebook displays graph. However, when I use Pycharm it shows blank white figure. Saving by plt.savefig() also do not works. I tried to play with dpi in plt.savefig() but doesn't change anything. Will be very grateful for any clues.

http://stackoverflow.com/comment/89161112
type: Comment
score: 1
has text: With this format he would get leading zeros '%d/%m/%Y'
type: AnswerComment
comment on: http://stackoverflow.com/a/51086305

http://stackoverflow.com/q/51142844
has comment: http://stackoverflow.com/comment/89269961
favorite count: 0
has comment: http://stackoverflow.com/comment/89269916
has answer: http://stackoverflow.com/a/51142938
tagged with: matrix
has body: Right now I am using the numpy.linalg.solve to solve my matrix, but the fact that I am using it to solve a 5000*17956 matrix makes it really time consuming. It runs really slow and It have taken me more than an hour to solve. The running time for this is probably O(n^3) for solving matrix equation but I never thought it would be that slow. Is there any way to solve it faster in Python? My code is something like that, to solve a for the equation BT * UT = BT*B a, where m is the number of test cases (in my case over 5000), B is a data matrix m*17956, and u is 1*m. C = 0.005 # hyperparameter term for regulization I = np.identity(17956) # 17956*17956 identity matrix rhs = np.dot(B.T, U.T) # (17956*m) * (m*1) = 17956*1 lhs = np.dot(B.T, B)+C*I # (17956*m) * (m*17956) = 17956*17956 a = np.linalg.solve(lhs, rhs) # B.T u = B.T B a, solve for a (17956*1)
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51143668
has answer: http://stackoverflow.com/a/51143668
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51142938
tagged with: performance
has title: Efficient way to solve matrix equation in Python
score: 1
tagged with: numpy
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/89308342
score: 0
type: Comment
type: QuestionComment
has text: If it is correct, why the question? Why do you think it is wrong?
comment on: http://stackoverflow.com/q/51161935

http://stackoverflow.com/comment/89102914
type: Comment
score: 0
type: AnswerComment
has text: @HarshSharma - No problem, already change it. How working my solution?
comment on: http://stackoverflow.com/a/51055979

http://stackoverflow.com/q/51164591
has title: Why does it roll the dice even though I say "no" when it asks if I want to do it again?
answer count: 1
has answer: http://stackoverflow.com/a/51164642
has body: I was writing a Roll the dice game but when I get the question "Would you like to roll the dice again?" and I say "no" it rolls anyway. I'm guessing it has something to do with the answer variable. However, I would like it to print "maybe next time" instead. Can you help me? Here's my code: import random def response(): if answer == "yes" or answer == "Yes" : rolldice() else: print("Maybe next time!") def rolldice(): randomnumb = random.randrange(1,7) print("You got number " + str(randomnumb) + "!") answer = input("Would you like to roll the dice again? \n ") response() answer = input("Would you like to roll the dice? \n") response()
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89312475
accepted answer: http://stackoverflow.com/a/51164642
has comment: http://stackoverflow.com/comment/89312461
downvote count: 1
has comment: http://stackoverflow.com/comment/89312612
type: Question
tagged with: function
upvote count: 0
has comment: http://stackoverflow.com/comment/89312525
score: -1

http://stackoverflow.com/q/51089040
score: 1
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51089946
possible better answer: http://stackoverflow.com/a/51089915
tagged with: python
has answer: http://stackoverflow.com/a/51089915
upvote count: 1
tagged with: import
has comment: http://stackoverflow.com/comment/89167519
has title: Pass package name as a variable
has answer: http://stackoverflow.com/a/51089946
tagged with: conda
has body: I would like to pass package name as a variable in jupyter notebook and then install those packages by conda in jupyter. I have prepared the following code but it is not working. I think that "i" does not recognize as numpy in "!conda install --yes --prefix {sys.prefix} i". Any help would be greatly appreciated. import sys import importlib a=['numpy','itertools','wxPython'] for i in a: try: importlib.import_module(i) print('%s is imported'%i) except ImportError: !conda install --yes --prefix {sys.prefix} i importlib.import_module(i) print('%s was successfully imported'%i) This produces: Error: ------------ Solving environment: ...working... failed PackagesNotFoundError: The following packages are not available from current channels: - i ------------------------------------------ From my point of view, it wants to install a package called "i" and since such a package is not available, it returns the above error. I am wondering why it is not able to consider "i" equal to 'numpy' in the line "!conda install --yes --prefix {sys.prefix} i". The reason is that when I tried "!conda install --yes --prefix {sys.prefix} 'numpy' ", there was no error.
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/89113454
comment on: http://stackoverflow.com/q/51061850
type: Comment
type: QuestionComment
score: 0
has text: Can you please elaborate as to what your query is so that we might be able to help?

http://stackoverflow.com/q/51134155
type: UnansweredQuestion
tagged with: iis
has comment: http://stackoverflow.com/comment/89495623
has answer: http://stackoverflow.com/a/67129553
has title: Publish Flask API in sub-directory using IIS FastCGI
has comment: http://stackoverflow.com/comment/89394833
type: Question
has comment: http://stackoverflow.com/comment/89393170
answer count: 1
tagged with: fastcgi
linked to: http://stackoverflow.com/q/18967441
tagged with: flask
has body: I would like to host my Flask API in sub-directory on IIS. MYLAPTOP (IIS Server) | |____Sites | |____Default Web Site (Website) | |____service (Virtual Directory) | |____payrollapi (Application) The URL for the payrollapi is http://localhost/service/payrollapi/ I configured the wfastcgi and and FastCGI settings <?xml version="1.0" encoding="UTF-8"?> <system.webServer> <add name="FlaskHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\annaconda\envs\payroll\python.exe|c:\annaconda\envs\payroll\lib\site-packages\wfastcgi.py" resourceType="Unspecified" /> </system.webServer> <add key="WSGI_HANDLER" value="payroll.app" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\service\payrollapi" /> Flask API Script: from flask import Flask app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def notes_list(): return "Welcome to Payroll !" if __name__ == "__main__": app.run(debug=True) It returns the error code "HTTP Error 403.18 - Forbidden" while on trying to access the API method. I tried with URL Rewrite also but there is no use <system.webServer> <directoryBrowse enabled="true" /> <match url="^service/payrollapi/(.*)" /> <action type="Rewrite" url="http://localhost:5500/service/payrollapi/{R:1}" /> Kindly assist me how to deploy the Flask application in Sub-direcory / sub-application in a website.
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89395558
tagged with: python-3.x

http://stackoverflow.com/q/51155024
has body: I have a project and I have to use gitdb with python. When I search on google I just find gitdb Documents. And it doesn't have any basic example. I found just that code snipped which I don't understand about it clearly. #/usr/bin/python import os,sys,zlib,gitdb from gitdb.db import LooseObjectDB from gitdb.pack import PackEntity from gitdb.util import bin_to_hex,hex_to_bin ldb=LooseObjectDB(sys.argv[1]+'/.git/objects') PackEntity.create((ldb.stream(sha) for sha in ldb.sha_iter()),sys.argv[1]+'/.git/objects/pack',object_count=ldb.size(),zlib_compression=zlib.Z_BEST_COMPRESSION) Could anybody have any recommendation for me?
score: 0
has title: add and remove operation with gitdb
answer count: 1
tagged with: github
accepted answer: http://stackoverflow.com/a/51155839
tagged with: python
tagged with: git
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51155839

http://stackoverflow.com/comment/89219169
type: Comment
score: 1
has text: I have a question (perhaps unrelated, if you suggest I'll post it as a new question): if I define the further layers after `VGG16` in TensorFlow, including a loss and training op, then upon running the training op, will the whole model (including `VGG16`) be trained end-to-end?
type: AnswerComment
comment on: http://stackoverflow.com/a/51109026

http://stackoverflow.com/q/51038602
downvote count: 2
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/702834
tagged with: enumeration
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/36932
tagged with: python
type: AnsweredQuestion
has body: I understand that enum is a class I can inherit from to make my class iterable over the objects. But what does enum() function do, as shown in this code snippet below? enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums] for enum in enums: enum.start() for enum in enums: enum.join()
type: Question
tagged with: enumerate
tagged with: enums
score: -1
has comment: http://stackoverflow.com/comment/89068674
has answer: http://stackoverflow.com/a/51038685
accepted answer: http://stackoverflow.com/a/51038685
has title: What does enum() do in python?

http://stackoverflow.com/q/51139234
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89267100
has comment: http://stackoverflow.com/comment/89263907
has body: When I execute this line of code net = cv2.dnn.readNetFromTensorFlow(args["model"]) python3.6 x86 says AttributeError: module 'cv2.dnn' has no attribute 'readNetFromTensorFlow'
accepted answer: http://stackoverflow.com/a/51624765
has comment: http://stackoverflow.com/comment/89265807
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51624765
has comment: http://stackoverflow.com/comment/89267411
has comment: http://stackoverflow.com/comment/89267391
tagged with: tensorflow
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/89266745
has comment: http://stackoverflow.com/comment/89266295
has title: OpenCv and TensorFlow AttributeError: module 'cv2.dnn' has no attribute 'readNetFromTensorFlow'

http://stackoverflow.com/comment/89127541
type: Comment
comment on: http://stackoverflow.com/a/51065621
type: AnswerComment
has text: Thanks Pax for your sketch, It is really helpful!
score: 0

http://stackoverflow.com/a/51077068
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51076766
accepted answer of: http://stackoverflow.com/q/51076766
upvote count: 4
has body: Your problem here is that df.values is a column by row array. To get the form you want you need to transpose it. Fortunately, that is easy. Replace df.values by df.values.T! So in your code replace: plt.stackplot(df.index,df.values) with plt.stackplot(df.index,df.values.T)

http://stackoverflow.com/q/51054529
has answer: http://stackoverflow.com/a/77473780
upvote count: 4
answer count: 3
has title: manipulate linestyle in matplotlib legend
possible better answer: http://stackoverflow.com/a/77473780
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89102065
accepted answer: http://stackoverflow.com/a/51056739
tagged with: python
has answer: http://stackoverflow.com/a/65874494
score: 4
type: AnsweredQuestion
has body: I would like to include a legend in my plot, which shows all lines as solid line even if the corresponding curve uses linstyle '--'. Is there plt.plot(x, y, linestyle='--') plt.legend(loc=0) plt.show() So the legend for the plot above should show one solid line.
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51056739

math
tags question: http://stackoverflow.com/q/51110217
tags question: http://stackoverflow.com/q/51029920
tags question: http://stackoverflow.com/q/51155780
tags question: http://stackoverflow.com/q/51018876
tags question: http://stackoverflow.com/q/51091377
tags question: http://stackoverflow.com/q/51107011
type: Tag
tags question: http://stackoverflow.com/q/51156864
tags question: http://stackoverflow.com/q/51166859
tags question: http://stackoverflow.com/q/51074984
tags question: http://stackoverflow.com/q/51011601
tags question: http://stackoverflow.com/q/51076695
tags question: http://stackoverflow.com/q/51114512
tags question: http://stackoverflow.com/q/51119965
tags question: http://stackoverflow.com/q/51027813
tag name: math
tags question: http://stackoverflow.com/q/51031077

http://stackoverflow.com/comment/89016766
score: 0
type: Comment
type: QuestionComment
has text: yes only the date as the other data set begins at 2017-04-14 so i want to remove from this dataset 13/04 to begin from 14/04 so that it matches with the other dataset
comment on: http://stackoverflow.com/q/51011727

http://stackoverflow.com/a/51103558
has body: As discussed in the chat, it turns out that the environment where your Jupyter notebooks run and the one where you have installed the packages are different. Since pip reports both packages installed in your "main" environment (i.e. the one coming up when you simply open a Windows command prompt), what you should do is open Jupyter from the command prompt, as jupyter notebook and your packages will indeed be available for importing, as we confirmed indeed.
has comment: http://stackoverflow.com/comment/89194486
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51090389
answers question: http://stackoverflow.com/q/51090389
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51116308
has comment: http://stackoverflow.com/comment/89223437
answers question: http://stackoverflow.com/q/51115255
has comment: http://stackoverflow.com/comment/89219910
type: Answer
has comment: http://stackoverflow.com/comment/89220011
has comment: http://stackoverflow.com/comment/89223932
has body: You can implement a getitem method that will retrieve a value at an index, and a setitem method to update a node at an index. That way, a simple swap method can be written by reassigning the values: def check_index(f): def wrapper(cls, _val, *args): if cls._next is None and _val: raise IndexError(f'{_val} exceeds length of deque') return f(cls, _val, *args) return wrapper class Deque: def __init__(self, _val= None, _previous = None): self.value = _val self._next, self._previous = None, _previous @check_index def __getitem__(self, _index): return self.value if not _index else self._next[_index-1] @check_index def __setitem__(self, _index, _val): if not _index: self.value = _val else: self._next[_index-1] = _val def insert_val(self, _val, _trailing = None): if self.value is None: self.value = _val else: if self._next is None: self._next = Deque(_val, _trailing) else: self._next.insert_val(_val, self._next) def swap(self, _start, _finish): _temp = self[_start] self[_start] = self[_finish] self[_finish] = _temp def __str__(self): return f'{self.value}, {str(self._next)}' if self._next is not None else str(self.value) def __repr__(self): return f'Deque({str(self)})' d = Deque() for i in range(10): d.insert_val(i) &gt;&gt;&gt;d Deque(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) &gt;&gt;&gt;d.swap(2, 6) #swapping the third item with the 7th item &gt;&gt;&gt;d Deque(0, 1, 6, 3, 4, 5, 2, 7, 8, 9)
has comment: http://stackoverflow.com/comment/89223453
has comment: http://stackoverflow.com/comment/89223409
score: 0

http://stackoverflow.com/comment/89252057
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51036394
has text: @GordThompson I'm using Datagrip on Ubuntu to access the database. The column names are like "orderId", "UserId" and so on. They are English.
score: 0

http://stackoverflow.com/q/51015273
score: 0
has body: So i was trying to follow this tutorial https://www.youtube.com/watch?v=Lg4T9iJkwhE&amp;t=155s to achieve image detection with YOLO. and when trying to run this code to auto download images of cell phones but it didn't work import os import urllib.request as ulib from bs4 import BeautifulSoup as Soup import json url_a = 'https://www.google.com/search?ei=1m7NWePfFYaGmQG51q7IBg&amp;hl=en&amp;q={}' url_b = '\&amp;tbm=isch&amp;ved=0ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ&amp;start={}' url_c = '\&amp;yv=2&amp;vet=10ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ.1m7NWePfFYaGmQG51q7IBg' url_d = '\.i&amp;ijn=1&amp;asearch=ichunk&amp;async=_id:rg_s,_pms:s' url_base = ''.join((url_a, url_b, url_c, url_d)) headers = {'User-Agent': 'Chrome/41.0.2228.0 Safari/537.36'} def get_links(search_name): search_name = search_name.replace(' ', '+') url = url_base.format(search_name, 0) request = ulib.Request(url, None, headers) json_string = ulib.urlopen(request).read() page = json.loads(json_string) new_soup = Soup(page[1][1], 'lxml') images = new_soup.find_all('img') links = [image['src'] for image in images] return links def save_images(links, search_name): directory = search_name.replace(' ', '_') if not os.path.isdir(directory): os.mkdir(directory) for i, link in enumerate(links): savepath = os.path.join(directory, '{:06}.png'.format(i)) ulib.urlretrieve(link, savepath) if __name__ == '__main__': search_name = 'cell phones' links = get_links(search_name) save_images(links, search_name) I got bunch of errors like this : C:\Python36\python.exe "C:/dark/darkflow-master/new_model_data/part5 - get_images.py" Traceback (most recent call last): File "C:/dark/darkflow-master/new_model_data/part5 - get_images.py", line 39, in &lt;module&gt; links = get_links(search_name) File "C:/dark/darkflow-master/new_model_data/part5 - get_images.py", line 19, in get_links json_string = ulib.urlopen(request).read() File "C:\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data,…
has comment: http://stackoverflow.com/comment/89023551
has comment: http://stackoverflow.com/comment/89023418
type: UnansweredQuestion
tagged with: python
has title: Raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 400: Bad Request
tagged with: yolo
answer count: 0
has comment: http://stackoverflow.com/comment/89023592
type: Question
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89023482
has comment: http://stackoverflow.com/comment/89046158
has comment: http://stackoverflow.com/comment/89023578

http://stackoverflow.com/q/51148821
tagged with: pivot-table
type: UnansweredQuestion
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/51149577
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51148921
downvote count: 0
tagged with: dataframe
has body: I am still new to Python pandas' pivot_table and im trying to reshape the data to have a binary indicator if a value is in a certain observation. I have follow some previous codes and got some encouraging results, however instead of 1 and zeros as Is my ideal result I get a sum. Please see a small sample data set below ID SKILL NUM 1 A 1 1 A 1 1 B 1 2 C 1 3 C 1 3 C 1 3 E 1 The results I am aiming for is: ID A B C E 1 1 1 0 0 2 0 0 1 0 3 0 0 0 1 My code atm get the following result: ID A B C E 1 2 1 0 0 2 0 0 2 0 3 0 0 0 1 Should I remove the duplicates first?? The code I'm using atm is below; df_pivot = df2.pivot_table(index='Job_posting_ID', columns='SKILL', aggfunc=len, fill_value=0)
answer count: 3
has title: Reshaping into binary variables using pandas python
tagged with: pandas
linked to: http://stackoverflow.com/q/14262433
favorite count: 0
has answer: http://stackoverflow.com/a/51149485

http://stackoverflow.com/q/51162132
accepted answer: http://stackoverflow.com/a/51162165
tagged with: version
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51162165
tagged with: pip
upvote count: 1
type: Question
tagged with: tabula
has body: I need to use the tabula library version 0.9.2. When I type the following, everything works fine: python -m pip install tabula I need to use a specific version of tabula. When I type python -m pip install tabula==0.9.2, I get this error message: Collecting tabula==0.9.2 Could not find a version that satisfies the requirement tabula==0.9.2 (from ve rsions: 1.0.2, 1.0.3, 1.0.4, 1.0.5) No matching distribution found for tabula==0.9.2 So, I am now attempting to install the tabula library manually; however, I have never done this before. When I go here and download tabula-jar-0.9.2.zip these do not look like the files I normally have when I install a module using pip. Is there something that I need to know or do?
score: 1
has title: Manually Installing Python Libraries

http://stackoverflow.com/q/51154187
accepted answer: http://stackoverflow.com/a/51154294
type: Question
score: 5
has comment: http://stackoverflow.com/comment/89291529
answer count: 1
has comment: http://stackoverflow.com/comment/89291531
has answer: http://stackoverflow.com/a/51154294
upvote count: 5
linked to: http://stackoverflow.com/q/4836710
downvote count: 0
tagged with: sorting
has body: I'm creating pdf file from images but having problem with sorting the jpg files in numeric order I have 20 files from 1.jpg to 20.jpg I'm using below code to sort all files in order import os sorted(os.listdir('path/to/jpg/files')) but it will print 1.jpg, 11.jpg, 12.jpg and so on. Any ideas?
type: AnsweredQuestion
has title: How to sort files in python in numeric order?
tagged with: python
favorite count: 0

http://stackoverflow.com/a/51062189
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: You can take advantage of the fact that when comparing tuples, the comparison is based on the first element -- and for equal first elements, the second element is compared. With that in mind, you could first massage your list of lists into a list of tuples associating each 'x1' value with the respective 'y1' value, and then getting the sorted list: &gt;&gt;&gt; lst = [['x1','y1','x2','y2'],[1,1,0,80],[.95,1,.05,70],[.93,1,.1,65]] &gt;&gt;&gt; sorted((x1, y1) for x1, y1, x2, y2 in lst[1:]) [(0.93, 1), (0.95, 1), (1, 1)]
accepted answer of: http://stackoverflow.com/q/51061732
type: Answer
answers question: http://stackoverflow.com/q/51061732
score: 2

http://stackoverflow.com/q/51106329
tagged with: python
tagged with: deployment
has comment: http://stackoverflow.com/comment/89200377
answer count: 0
has comment: http://stackoverflow.com/comment/89200130
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89199782
tagged with: django
has comment: http://stackoverflow.com/comment/89199964
has comment: http://stackoverflow.com/comment/89200203
tagged with: django-views
downvote count: 0
has comment: http://stackoverflow.com/comment/89200316
score: 1
has comment: http://stackoverflow.com/comment/89199904
has comment: http://stackoverflow.com/comment/89199794
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/89200153
favorite count: 0
has body: This is the first time I've developed a web app using Django and one of my first major attempts at programming. I'm trying to deploy my project to the django test server- http://127.0.0.1:8000/ -but I get an error that says the connection is refused. I've looked through Django's documentation and and other websites about django deployment but I'm at a loss on how to troubleshoot this error. If someone can recommend a way for me to deploy django locally so I can test my web app using django test server or recommend another deployment service that is easy for new programmers to use that would be very appreciated. edit: After doing what Ojas Kale had suggested I still am at a loss on what the possible issue or issues that are causing this error. Davis Joseph.
has title: django test server error: connection refused. How to deploy apps locally to test?

http://stackoverflow.com/q/51146225
has title: Google has retired the QPX Express API
has body: Now that Google has retired the QPX Express API, is there a different way to pull flight data from their service? I'm hoping to build an app that can send me alerts and data when certain flights and prices change. Now I know Google flights does something like that already, but I'm wanting to build it my self to practice and add a few extra features to it. I'm working with Python and have a pretty base knowledge so any helpful tips would be great!
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: google-qpx-express-api
type: Question
score: 1
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51149550
answer count: 4
tagged with: list
has comment: http://stackoverflow.com/comment/89282797
has answer: http://stackoverflow.com/a/51149685
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51149630
tagged with: set
upvote count: 1
has answer: http://stackoverflow.com/a/51149766
downvote count: 1
has comment: http://stackoverflow.com/comment/89282960
has body: Hopefully this doesn't get downvoted on the title but couldn't think of a better way of explaining the issue. Based on suggestions I've seen on Stack, I am using Sets to ignore duplicate lines which works a treat until I get a use case where the line changes slightly but I still want to filter that line out as a duplicate. In my example, I cannot seem to be able to search a string for a certain keyword so in my example below, I exclude any new line where the firs column, which is the ID, already exists, in this case London. For example. London,Sold,2021-12-07,1000000,301909 London,Sold,2021-12-07,1000000,999999 So I wanted to know if it was possible to just check whether the ID London exists in my Set before adding the line or ignoring but I can't find any way to do this. I tried tuples but not sure that is my solution and I cannot create a set from list. My simple test case is as follows and the end result is I only get the line in my set, not the testline as is happening now. testline = 'London,Sold,2021-12-07,1000000,301909' id = 'London' j="testline2" seen = set() seen.add(testline) if id not in seen: seen.add(j) print seen
tagged with: duplicates
type: Question
score: 0
has title: How to check a Python Set for a string
tagged with: string
has answer: http://stackoverflow.com/a/51149653
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51057744
has comment: http://stackoverflow.com/comment/89106729
upvote count: 3
answers question: http://stackoverflow.com/q/51056256
type: Answer
score: 3
downvote count: 0
has body: This error message... AttributeError: 'str' object has no attribute 'click' ...implies that you script/program have attempted to invoke click() on a string object. What went wrong As per the line of code: elem.get_attribute("href").click() You have extracted the href attribute of the first element from the List elems. get_attribute() method returns a string. String data types can't invoke click() method. Hence you see the error. Solution Now, in all possibilities as you are extracting the href attributes and you want to open the Links and a viable solution will be to open the (href) links in the adjacent TABs as follows: elems = driver.find_elements_by_xpath("//a[@href]") for elem in elems: print(elem) my_href = elem.get_attribute("href") driver.execute_script("window.open('" + my_href +"');") # perform your tasks in the new window and switch back to the parent windown for the remaining hrefs

http://stackoverflow.com/a/51139316
upvote count: 16
has comment: http://stackoverflow.com/comment/89262983
has comment: http://stackoverflow.com/comment/125694823
has body: When you run spyder from the CMD/terminal, your operating system tries to find the spyder executable on your system's PATH. In this case, it will default back to the base environment's version of spyder, which runs Python 3.6. The best way I have found so far is to install spyder to the new environment; activate the environment, and then run spyder (which should fire up the version in the local environment). conda create --name py37 python=3.7 conda install --name py37 spyder -c conda-forge conda activate py37 spyder However, this requires the version of spyder to support python 3.7. Currently that is not available (as of 2 July 2018), but it should not be too long coming. EDIT: Spyder for Python 3.7 is available.
has comment: http://stackoverflow.com/comment/89262815
has comment: http://stackoverflow.com/comment/89263075
has comment: http://stackoverflow.com/comment/125757828
has comment: http://stackoverflow.com/comment/89262910
type: Answer
has comment: http://stackoverflow.com/comment/89961109
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/51139232
has comment: http://stackoverflow.com/comment/95342735

http://stackoverflow.com/comment/89094306
comment on: http://stackoverflow.com/q/51046752
has text: Yes, that's right.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89104770
type: AnswerComment
comment on: http://stackoverflow.com/a/51056871
score: 0
type: Comment
has text: Could you just let me know how to make variable store the essa function? I need to apply it here: https://gyazo.com/78b854cdd96b49850a8ff33c450d1d7c so for each game in player_2["all"] it makes one thread (up to 8 let's say) and keeps it in variable. THank you for help.

http://stackoverflow.com/q/51119808
downvote count: 0
has body: I want to convert all the non float type columns of my dataframe to float ,is there any way i can do it .It would be great if i can do it in One Go . Below is the type longitude - float64 latitude - float64 housing_median_age - float64 total_rooms - float64 total_bedrooms - object population - float64 households - float64 median_income - float64 rooms_per_household - float64 category_&lt;1H OCEAN - uint8 category_INLAND - uint8 category_ISLAND - uint8 category_NEAR BAY - uint8 category_NEAR OCEAN - uint8 Below is the snippet of my code import pandas as pd import numpy as np from sklearn.model_selection import KFold df = pd.DataFrame(housing) df['ocean_proximity'] = pd.Categorical(df['ocean_proximity']) #type casting dfDummies = pd.get_dummies(df['ocean_proximity'], prefix = 'category' ) df = pd.concat([df, dfDummies], axis=1) print df.head() housingdata = df hf = housingdata.drop(['median_house_value','ocean_proximity'], axis=1) hl = housingdata'median_house_value' hf.fillna(hf.mean,inplace = True) hl.fillna(hf.mean,inplace = True)
favorite count: 0
has answer: http://stackoverflow.com/a/67511545
accepted answer: http://stackoverflow.com/a/51119857
tagged with: python
duplicate of: http://stackoverflow.com/q/15891038
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51119857
score: 21
tagged with: machine-learning
type: Question
possible better answer: http://stackoverflow.com/a/67511545
answer count: 2
linked to: http://stackoverflow.com/q/15891038
has title: Convert dataframe columns of object type to float
has comment: http://stackoverflow.com/comment/89225334
tagged with: pandas
upvote count: 21

http://stackoverflow.com/q/51111323
has answer: http://stackoverflow.com/a/52921608
accepted answer: http://stackoverflow.com/a/51192756
has comment: http://stackoverflow.com/comment/97484432
has title: How to suppress CatBoost iteration results?
has body: I am trying to use CatBoost to fit a binary model. When I use the following code, I thought verbose=False can help to suppress the iteration logs. But it didn't. Is there a way to avoid print the iterations? model=CatBoostClassifier(iterations=300, depth=6, learning_rate=0.1, loss_function='Logloss', rsm = 0.95, border_count = 64, eval_metric = 'AUC', l2_leaf_reg= 3.5, one_hot_max_size=30, use_best_model = True, verbose=False, random_seed = 502) model.fit(X_train, y_train, eval_set=(X_test_filtered, y_test_num), verbose = False, plot=True)
tagged with: python
possible better answer: http://stackoverflow.com/a/52921608
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51192756
downvote count: 0
score: 29
has answer: http://stackoverflow.com/a/72739407
type: Question
tagged with: catboost
upvote count: 29
has comment: http://stackoverflow.com/comment/89230744
answer count: 3
has comment: http://stackoverflow.com/comment/89209698
favorite count: 0

http://stackoverflow.com/q/51031002
has answer: http://stackoverflow.com/a/57711918
has title: How to use atom-ide-debugger-python to debug python code incl. variable watch and breakpoints
tagged with: python
score: 2
upvote count: 3
downvote count: 1
tagged with: debugging
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/57711918
type: Question
tagged with: atom-editor
has body: I want to use atom-ide-debugger-python to debug python app incl. variable watch and breakpoints. The python app is a Flask server that I can start using python server.py. In Atom python-ide I can set breakpoints and open the debugger sidebar. I get the options to attach or launch debugger. How do debug my Flask app started by server.py? Thank you, Anton
answer count: 1
tagged with: flask
favorite count: 0
tagged with: breakpoints

http://stackoverflow.com/q/51116376
has comment: http://stackoverflow.com/comment/89219049
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89219216
upvote count: 1
tagged with: python
has title: How to automatically insert and parse xml elements using any script(python/shell)?
has comment: http://stackoverflow.com/comment/89220167
has answer: http://stackoverflow.com/a/51117582
score: 1
type: Question
has body: This is extension of question asked in link:- How to insert sub-elements of xml tag at specific position using python script? It is working fine if I use python 3 where I have Element Tree. If I don't have python 3(as current version i am using is 2.6, can't upgrade) how can i write to xml files with xml_declaration flag true? It seems xml flag is getting removed when parsing. Basically, I am getting error while parsing the xml:- org.xml.sax.SAXParseException; systemId: file:config.xml; lineNumber: 1; columnNumber: 1; file:config.xml&lt;Line 1, Column 1&gt;: XML-20108: (Fatal Error) Start of root element expected.[[ at oracle.xml.parser.v2.XMLError.flushErrorHandler(XMLError.java:425) at oracle.xml.parser.v2.XMLError.flushErrors1(XMLError.java:290) at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:476) at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:417) at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:287) at oracle.ossmgmt.common.util.xml.XMLUtilityParser.validate(XMLUtilityParser.java:141) at oracle.ossmgmt.common.util.xml.XMLUtilityParser.initParse(XMLUtilityParser.java:256) at oracle.ossmgmt.common.util.xml.XMLUtility.initParse(XMLUtility.java:381) I also tried using lxml :- from lxml import etree as ET param1='conf.xml' tree = ET.parse(param1) print(ET.getroot()) param2='Target' target = tree.find(param2) #print target.tag,target.attrib seq = 'Attribute NAME="EFG" VALUE="1234"' param3 = seq temp = ET.Element(param3) temp.tail = '\n' target.insert(4,temp) tree.write(param1, encoding='utf-8', xml_declaration=True) but here I am getting error as:- Traceback (most recent call last): File "b.py", line 10, in &lt;module&gt; temp = ET.Element(param3) File "lxml.etree.pyx", line 2346, in lxml.etree.Element (src/lxml/lxml.etree.c:46617) File "apihelpers.pxi", line 113, in lxml.etree._makeElement (src/lxml/lxml.etree.c:10475) File "apihelpers.pxi", line 1405, in lxml.etree._tagValidOrRaise (src…
has comment: http://stackoverflow.com/comment/89219588
answer count: 1
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/89219044
favorite count: 0

telegram
tags question: http://stackoverflow.com/q/51115038
tag name: telegram
type: Tag
tags question: http://stackoverflow.com/q/51124241
tags question: http://stackoverflow.com/q/51154258
tags question: http://stackoverflow.com/q/51125356
tags question: http://stackoverflow.com/q/51147279

http://stackoverflow.com/a/51128589
type: Answer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89242112
has comment: http://stackoverflow.com/comment/89242100
has body: Let me answer you all of your question one by one! 1.) What is the significance of the #!/usr/local/bin/python statement in this context? So, This is called Shebang that is used for specifying the interpreter here you are pointing to the python interpreter. You can prevent this but if you prevent this you have to specify interpreter while running your script. Similarly #!/bin/bash to point out bash interpreter. &amp; shebang necessarily to be the first line of script. 2) Is creating a shell file necessary to run Python/Scrapy scripts, et cetera? Nup you can directly enter commands in crontab. 3) Can you actually export PATH and execute other commands (i.e. cd ... &amp;&amp; scrapy crawl mycrawler) directly in crontab -e? If you will do so it will be a good practice and also it reduces the line because if you not use PATH then you have to specify every time the full path of a command to be executed like /usr/bin/find to just run find command. 4) What is the significance of the first path, /usr/local/bin/python? as i said earlier it is pointing to your interpreter. 5) In his answer, he states that &amp;&gt;&gt; /home/Desktop/log.txt is the file to which errors and other output will appended. Is that what the &amp;&gt;&gt; does? Is that universal for every single Linux distro? &amp;&gt;&gt; will apped output to the file that is stdout Yea it's common for all linux distro. 6) Is there a specific location on servers where shell scripts like this are commonly stored? Well It's up to you where you store your scripts. but it's recommended that you store your scripts at a safe place like in /opt/&lt;user&gt;/scripts folder. Optional https://crontab.guru/ - here you can understand more about crontab syntax and all other things are basic Linux things.
answers question: http://stackoverflow.com/q/51128406
score: 0

django-cms
tags question: http://stackoverflow.com/q/51114129
tags question: http://stackoverflow.com/q/51089355
tag name: django-cms
tags question: http://stackoverflow.com/q/51042086
type: Tag

http://stackoverflow.com/a/51078465
upvote count: 14
has body: Use unstack: print(df.unstack() .unstack(level=1) .reset_index(level=1, drop=True) .rename_axis('names') .reset_index()) names 1 2 0 a 10 10 1 a 10 10 2 a 10 10 3 b 20 20 4 b 20 20 5 b 20 20 6 c 40 40 7 c 40 40 8 c 40 40
score: 14
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51078388
downvote count: 0
answers question: http://stackoverflow.com/q/51078388
type: Answer

http://stackoverflow.com/q/51053092
has answer: http://stackoverflow.com/a/51053633
accepted answer: http://stackoverflow.com/a/51053633
possible better answer: http://stackoverflow.com/a/51053293
tagged with: http://stackoverflow.com/tag/csv
has title: Creating a Dict from CSV dataflow python
favorite count: 0
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51053293
downvote count: 0
type: Question
upvote count: 2
answer count: 2
has body: I am trying to make a dict from csv data in python, I do not want to use the traditional split(',') and then using renaming the rows to the heading I would like, as I will be recieving different csv files with different amounts of information, and I will not be able to consistently target the rows I want with that method. THE HEADER NAMES WILL BE CONSISTENT, just their maybe more headers in one file compared to another Instead, I have been trying to formulate a list from the CSV file, then zipping the first row into the rest of the rows to create a dictionary, then I can extract the exact contents I want. I can create a list of lists, by either using the csv.reader or : class Split(beam.DoFn): def process(self, element): rows = element.splitlines() data = [] for row in rows: data.append([row]) return data This returns: [u'FIRST_NAME,last_name,birthdate,voter_id,phone_number'] [u'hector,ABAD,6/15/1970,11*******,7*********'] [u'm,ABAL,6/16/1949,12********,'] [u'jorge,ABDALA,6/15/1962,21********,3********'] [u'karen,ABELLA,6/18/1988,33********,'] Although when I try to access the first row via: rows = element.splitlines() data = [] for row in rows: # f = pattern.findall(row) data.append([row]) return data[0] It returns: FIRST_NAME,last_name,birthdate,voter_id,phone_number hector,ABAD,6/15/1970,11*******,7********* m,ABAL,6/16/1949,109055849, jorge,ABDALA,6/15/1962,21********,3******** karen,ABELLA,6/18/1988,33********, I have also tried the beam_utils csv reader although this says that there is no module named 'sources' after I fix the fileio bug. If someone knows a better way or can point me towards what I'm doing wrong that would be great, also this is my pipeline: with beam.Pipeline(options=pipeline_options) as p: (p | 'Read' &gt;&gt; ReadFromText(known_args.input) | 'Split Values' &gt;&gt; beam.ParDo(Split()) | 'WriteToText' &gt;&gt; beam.io.WriteToText(known_args.output)) I am only reading from my google-cloud storage bucket for now, but in the future it will be f…
tagged with: google-cloud-dataflow

http://stackoverflow.com/comment/89316344
type: QuestionComment
has text: @Sraw I know, I had already changed the key data. :)
comment on: http://stackoverflow.com/q/51166611
score: 0
type: Comment

http://stackoverflow.com/comment/89288312
comment on: http://stackoverflow.com/q/51152430
has text: in what variable do you store the data?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51125676
upvote count: 1
has comment: http://stackoverflow.com/comment/89236321
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/89236298
has comment: http://stackoverflow.com/comment/89236325
has comment: http://stackoverflow.com/comment/89236350
score: 0
duplicate of: http://stackoverflow.com/q/588004
has title: Different answer with division and floor operator
has comment: http://stackoverflow.com/comment/89236389
has body: I'm taking a large integer and dividing it by 5. answer provided by that operation is correct. But when I'm using floor operator then it rounds off it's digit at units place. Rest all digits are same in both cases. Can someone tell what is happening here? Code: 1 import sys 2 3 def gcd(a, b): 4 5 if b &gt; a: 6 a, b = b, a 7 8 if b &gt; 0: 9 return (gcd(a%b, b)) 10 11 return a 12 13 def lcm(a, b): 14 return (a*(b//gcd(a, b))) #floor operator 15 16 def lcm2(a, b): 17 return (a*(b/gcd(a, b))) #division operator 18 19 a, b = 226553150, 1023473145 20 print (int(lcm(a, b))) 21 print (int(lcm2(a, b))) user@ubuntu:~/py$ python3 findlcm.py 46374212988031350 46374212988031352
tagged with: floor
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89236364
tagged with: python
tagged with: floor-division
tagged with: interpreter
has comment: http://stackoverflow.com/comment/89236336
answer count: 0
has comment: http://stackoverflow.com/comment/89236333

http://stackoverflow.com/q/51055193
has answer: http://stackoverflow.com/a/51055441
has body: I have seen many usage of that line of code in many tensorflow projects. What does the line do in tensorflow?
tagged with: tensorflow
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89101193
downvote count: 0
has answer: http://stackoverflow.com/a/51057408
upvote count: 8
possible better answer: http://stackoverflow.com/a/51057408
accepted answer: http://stackoverflow.com/a/51055441
favorite count: 0
score: 8
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has title: What does that code snippet signify "tf.logging.set_verbosity(tf.logging.INFO)" in tensorflow code?

http://stackoverflow.com/comment/117202988
type: AnswerComment
comment on: http://stackoverflow.com/a/64996071
type: Comment
has text: Thanks @ankit7540, this looks like the install powershell script failed to copy the xlOil.ini file to that location. It could be a permission error, possibly powershell execute permssion has not been granted. You can contact me at the obfuscated email [here](https://pypi.org/project/xlOil/) or raise an issue at [gitlab](https://gitlab.com/stevecu/xloil/-/issues) and I'll troubleshoot.
score: 1

http://stackoverflow.com/comment/89120675
has text: This is more appropriate for https://codereview.stackexchange.com.
type: QuestionComment
comment on: http://stackoverflow.com/q/51059924
score: 0
type: Comment

http://stackoverflow.com/a/51068466
type: Answer
has comment: http://stackoverflow.com/comment/89156661
has body: Since you note: The query runs in MS Access quite OK but not through Python. One possible reason for this is Access stored queries are more efficient than application layer called queries since the engine saves and caches best execution plan. In the application layer (Python, VBA, etc.) when processing a string SQL statement, the Jet/ACE engine does not have time to plan the best execution. Therefore, consider the following: Add any needed indexes to JOIN variables of respective tables. Save your UPDATE query as a stored query inside the database. Here, the saving process checks syntax, calculates and optimizes plan, and cache stats. Run Compact &amp; Repair in database to refresh stats. Then, run query in Python as a stored proc with CALL command: # SET AUTOCOMMIT PREFERENCE IN CONNECTION cnxn = pyodbc.connect(..., autocommit=True) ... crsr.execute("{CALL myUpdateQuery}")
has comment: http://stackoverflow.com/comment/89158581
has comment: http://stackoverflow.com/comment/89145935
score: 0
answers question: http://stackoverflow.com/q/51061082
has comment: http://stackoverflow.com/comment/89156895

http://stackoverflow.com/q/51124747
type: AnsweredQuestion
score: 3
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51124876
has body: I have a Data Frame with columns: Year and Min Delay. Sample rows as follows: 2014 0 2014 2 2014 0 2014 4 2015 4 2015 4 2015 2 2015 2 I want to group this dataframe by year and find the delay ratio per year (i.e. number of non-zero entries that year divided by total number of entries for that year). So if we consider the data frame above, what I am trying to get is: 2014 0.5 2015 1 (There are 2 delays in 2014, total 4, 4 delays in 2015 total 4. A delay is defined by Min Delay > 0) This is what I tried: def find_ratio(df): ratio = 1 - (len(df[df == 0]) / len(df)) return ratio print(df.groupby(["Year"])["Min Delay"].transform(find_ratio).unique()) which prints: [0.5 1] How can I get a data frame instead of an array?
favorite count: 0
tagged with: pandas
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/51124876
has comment: http://stackoverflow.com/comment/89234941
has title: Dataframe group by a specific column, aggerage ratio of some other column?

http://stackoverflow.com/q/51028076
linked to: http://stackoverflow.com/q/19213535
answer count: 2
has body: I am trying to replace two lists a text: text = "today is friday july 1 2018" days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] daysRegex = re.compile('|'.join(map(re.escape, days))) months = ['january', 'february', 'march', 'april', 'may', 'mai', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] monthsRegex = re.compile('|'.join(map(re.escape, months))) replaces = daysRegex.sub("&lt;day&gt;", text) and monthsRegex.sub("&lt;month&gt;", text) print(replaces) output: today is friday &lt; month> 1 2018 correct output: today is &lt; day> &lt; month> 1 2018 I'm not sure I'm using the and operator correctly. I'm just trying to put into practice what I studied about it (but I may have misunderstood)
favorite count: 0
has comment: http://stackoverflow.com/comment/89048702
tagged with: python
tagged with: regex
has title: Replace lists in text with python regex
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51028095
type: UnansweredQuestion
downvote count: 2
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51028141
score: -1

http://stackoverflow.com/a/51108097
type: Answer
has comment: http://stackoverflow.com/comment/89204653
has body: I'm not sure what problem you're trying to solve. Your question is too broad. Python compiles all code automatically, but it generates .pyc files with the python bytecode, then needs a VM to execute it, similar to other languages like C# and java. To integrate with C the usual approach is to make a C extension to python, then you can call it from the python code. If you want to generate a .exe from python code, the go-to method is to use something like pyinstaller, that bundles python, all libraries and your code in a single .exe file and unpacks it on execution. If you really want to convert a python code to machine-readable x86 code (why) then you can use something like cython (converts python-like code to C code); The results are probably not what you expect though.
score: 0
answers question: http://stackoverflow.com/q/51108008

download
tags question: http://stackoverflow.com/q/51078996
type: Tag
tag name: download

http://stackoverflow.com/comment/89093490
has text: @Zane just do some googling about how to read/write files with python.
comment on: http://stackoverflow.com/a/51050645
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89095227
score: 0
type: AnswerComment
has text: Not to mention the ability to iterate over the `dict` and calling every function instead of having to inspect what is actually a method of an object, should that need exist
type: Comment
comment on: http://stackoverflow.com/a/51051934

http://stackoverflow.com/comment/103252302
has text: no my friend in the questions he used useStripe it should be written usestripe 'User' object has no attribute 'userStripe' cause user has attribute name it userstripe not userStripe with camelcase
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/58456715

http://stackoverflow.com/q/51070679
accepted answer: http://stackoverflow.com/a/51070851
answer count: 1
has title: Python percentile of recent value vs window of previous values
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89131302
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51070851
type: Question
score: 3
has body: Apologies I am a noob looking to transition from R! Reproducible data example; df = pd.DataFrame(1.26 + np.random.rand(size)/100.0, index=pd.date_range('20160101 09:00:00', periods=size, freq='60s'), columns=['ATR20']) I would like to take a value in the column ATR20 and compute its current percentile against rolling window of the previous n values of column ATR20. Heres as far as I got: for n in range(1,len(df)): print(sum(df.ATR20[n:n+20] &gt; df.ATR20)) Which gives the following error: ValueError: Can only compare identically-labeled Series objects I am sure that there is an easier way to do this with neater syntax but my searches haven't found anything close enough. Thanks.
tagged with: percentile
tagged with: numpy
tagged with: pandas

http://stackoverflow.com/a/51057860
score: 7
has body: Use transform with first for return same length Series as original df: data['Time'] = data['Distance'] /data.groupby('ID')['Speed'].transform('first') Or use drop_duplicates with map: s = data.drop_duplicates('ID').set_index('ID')['Speed'] data['Time'] = data['Distance'] / data['ID'].map(s) print (data) ID Distance Speed Time 0 1 100 40 2.50 1 1 200 20 5.00 2 1 200 10 5.00 3 2 400 20 20.00 4 2 500 30 25.00 5 2 100 40 5.00 6 2 600 20 30.00 7 2 700 90 35.00 8 3 800 80 10.00 9 3 700 10 8.75 10 3 400 20 5.00
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51057822
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51057822
type: Answer

http://stackoverflow.com/a/64542169
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51114448
type: Answer
has body: Old question, but figured I'd post in case anyone else is trying to do this. I've done something similar like this below. import chardet # Sniff out encoding method with open(subtitle_input_path, 'rb') as f: rawdata = b''.join([f.readline() for _ in range(10)]) # Encoding method and method whitelist encoding_method = chardet.detect(rawdata)['encoding'] encoding_method_whitelist = ['utf8', 'ascii'] # If encoding method will cause issues, convert it to utf-8 if encoding_method not in encoding_method_whitelist: # Read the old file's content with open(subtitle_input_path, encoding=encoding_method) as subtitle_file: subtitle_text = subtitle_file.read() # Convert to utf-8 and write to file with open(subtitle_input_path,'w', encoding='utf8') as subtitle_file: subtitle_file.write(subtitle_text)

http://stackoverflow.com/a/51139266
score: 1
has comment: http://stackoverflow.com/comment/120460696
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/120505476
has comment: http://stackoverflow.com/comment/120483242
upvote count: 1
has comment: http://stackoverflow.com/comment/120478843
answers question: http://stackoverflow.com/q/51133162
has body: While you can keep training a Word2Vec model with newer examples, unless the old examples are also re-presented in an interleaved fashion, those new examples may not make the model any better – no matter how well you adjust the alpha. That's because while training on the new examples, the model is only being nudged to get better at predicting their words, in those new contexts. If there are words missing from the new texts, their word-vectors remain unadjusted as the rest of the model drifts. Even to the extent the same words repeat, their new contexts will presumably be different in some important ways – or else why keep training with new data? – which incrementally dilutes or obsoletes all influence of the older training. There's even a word for the tendency (but far from certainty) of neural-networks to worsen when presented new data: catastrophic forgetting. So, the most supportable policy is to re-train with all relevant data mixed-together, to be sure it all has equal influence. If you're improvising some other shortcuts, you're in experimental territory, and there's little reliable documentation or published work that can make strong suggestions about the relative balance of learning-rates/epoch-counts/etc. Any possible answers would also depend very heavily on the relative sizes of the corpuses and vocabularies both at first, and then on any subsequent updates, and also on how important your specific project are factors like vector-stability-over-time, or relative-quality-of-different-vectors. So there'd be no one answer – just what tends to work in your particular setup. (There's an experimental feature in gensim Word2Vec – some internal model properties that end _lockf. That stands for 'lock-factor'. They match 1-for-1 with the word-vectors, and for any slot where this lock-factor is set to 0.0, the word-vector ignores training updates. In this way, you can essentially 'freeze' some words – such as those you're confident won't be improved by more training …

merge
tags question: http://stackoverflow.com/q/51033050
tags question: http://stackoverflow.com/q/51057924
tags question: http://stackoverflow.com/q/51124604
tags question: http://stackoverflow.com/q/51025752
type: Tag
tags question: http://stackoverflow.com/q/51032452
tags question: http://stackoverflow.com/q/51088107
tag name: merge
tags question: http://stackoverflow.com/q/51115262

http://stackoverflow.com/comment/89175693
score: 0
type: Comment
has text: @KeithW you mean you want the IVOG label in the x_ticks labels? That is, on the x axis you want [(IVOG, APR-2018), (IVOG, MAY-2018), ... ] etc
comment on: http://stackoverflow.com/a/51093645
type: AnswerComment

http://stackoverflow.com/a/51159322
accepted answer of: http://stackoverflow.com/q/51159204
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51159204
has body: dtypes is an attribute of the pd.Series not a function. You can access the type by running values.dtypes

http://stackoverflow.com/comment/89185254
has text: @Batty 'cat logs.py | ssh admin@localhost python -' without the -p 61234 part
comment on: http://stackoverflow.com/q/51098764
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51156430
favorite count: 0
type: UnansweredQuestion
has title: Removing complete lines of text in a text file (on Python)
tagged with: python
tagged with: text
has answer: http://stackoverflow.com/a/51156609
score: 1
has answer: http://stackoverflow.com/a/51156751
tagged with: file
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89296361
has answer: http://stackoverflow.com/a/51156718
has body: I am working with an output log file that has 12 thousand lines of code, most of which include something that looks like this: "760.0132 EXP window1: blendMode = 'avg'" My goal is to entirely remove any line that has "EXP window1: blendMode = 'avg'". I can remove that text bit from all of the lines where it is found, but not the number. This is the code I have used to delete the text bits (borrowed from another stack overflow question/answer): infile = "01_Day1_run1.txt" outfile = "01_Day1_run1_cleaned.txt" delete_list = [" EXP window1: blendMode = 'avg'"] fin = open(infile) fout = open(outfile, "w+") for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close() I was hoping that I would be able to add something like delete_list = ["1**.**** EXP window1: blendMode = 'avg'"] in order to delete any number that includes all of the text, and also any number in that line, but it does not seem to work. Any advice on how to best clean up the log file would be greatly appreciated. Thanks very much, Simon
answer count: 3
has comment: http://stackoverflow.com/comment/89296312
downvote count: 0

http://stackoverflow.com/q/51068178
has comment: http://stackoverflow.com/comment/89127484
tagged with: regression
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89127105
has comment: http://stackoverflow.com/comment/89126933
type: Question
has answer: http://stackoverflow.com/a/51068950
accepted answer: http://stackoverflow.com/a/51068950
has comment: http://stackoverflow.com/comment/89127571
has comment: http://stackoverflow.com/comment/89127335
has body: I am using RidgeCV function from the library scikit learn to find the optimum regularization parameter in a given range in ridge regression.I have created true output and stored it in numpy array t[] by adding noise. I have input values in X[] which contains k elements. For each k element we generate L noise values which is normal distribution giving k*L instances of t. ridge=make_pipeline(PolynomialFeatures(i),RidgeCV(alphas = lambdas, fit_intercept=False)) ridge.fit(X[:, None], t) However I am getting the following error while executing this: Enter the Number k:8 Enter the Number L:1 C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:952: RuntimeWarning: divide by zero encountered in double_scalars w = ((v + alpha) ** -1) - (alpha ** -1) C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:953: RuntimeWarning: divide by zero encountered in double_scalars w[constant_column] = - (alpha ** -1) C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:955: RuntimeWarning: divide by zero encountered in double_scalars c = np.dot(U, self._diag_dot(w, UT_y)) + (alpha ** -1) * y C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:955: RuntimeWarning: invalid value encountered in add c = np.dot(U, self._diag_dot(w, UT_y)) + (alpha ** -1) * y C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:956: RuntimeWarning: divide by zero encountered in double_scalars G_diag = self._decomp_diag(w, U) + (alpha ** -1) C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-packages\sklearn\linear_model\ridge.py:956: RuntimeWarning: invalid value encountered in add G_diag = self._decomp_diag(w, U) + (alpha ** -1) Polynomial of degree 1 and lambda_optimum =0.0 is:[nan nan] C:\Users\Sankalp\PycharmProjects\MachineLearning\venv\lib\site-package…
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Find the optimal regularization parameter λ for each of the polynomials of degree 0, 1, 2, . . . , 10. Plot that graph. Do it in python
has comment: http://stackoverflow.com/comment/89126210
favorite count: 0

http://stackoverflow.com/comment/89309734
has text: Use the OpenShift group if want to have a better discussion about it. https://groups.google.com/forum/#!forum/openshift
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51132151

http://stackoverflow.com/comment/89088857
has text: have you seen the answers?
comment on: http://stackoverflow.com/q/51048189
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92435911
type: Comment
has text: @Sraw My understanding of the posting guidelines at SO is that questions must be asked precisely. This question is asked in a way that indicates it is about suppressing inspection, and there is a mechanism for it, as you wrote. But at the same time OP asks about a way that is Pycharm-independent, and your answer does not fit that aspect, that's why I downvoted. But since the question is not well-formulated, it's hard to guess what the OP actually wants. Maybe you can add the information that there is no IDE-independent way of doing this (to my knowledge at least).
type: AnswerComment
comment on: http://stackoverflow.com/a/51148355
score: 0

http://stackoverflow.com/q/51091331
tagged with: loops
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51095238
has answer: http://stackoverflow.com/a/51261144
tagged with: pandas-groupby
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/35274700
favorite count: 0
tagged with: python-3.x
has title: Creating new dataframes using groupby
type: UnansweredQuestion
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/51258769
upvote count: 6
has body: I read this (How to create multiple dataframes from pandas groupby object) however, I still do not understand how to create my dataframes for each person after I create my grouped_persons group with groupby. How to create multiple dataframes from pandas groupby object What should I change in this code? I think this is part of my problem: 'df_'+ name +'1' grouped_persons = df.groupby('Person') for name, group in grouped_persons 'df_'+ name +'1' = df.loc[(df.Person == name) &amp; (df.ExpNum == 1)] File "", line 2 for name, group in grouped_persons ^ SyntaxError: invalid syntax

http://stackoverflow.com/a/51057911
downvote count: 0
has comment: http://stackoverflow.com/comment/89106447
has comment: http://stackoverflow.com/comment/89115369
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51057852
has comment: http://stackoverflow.com/comment/89106717
has comment: http://stackoverflow.com/comment/89115628
score: 3
has comment: http://stackoverflow.com/comment/89114872
has comment: http://stackoverflow.com/comment/89114329
has body: Looks like you confused lte and gte. lte means less than, while gte is greater than. So you should use end date with lte condition and start date with gte: Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__gte=datetime.date(2018, 6, 27), hotel__checkout__lte=datetime.date(2018, 6, 29)) Also note you don't need to call save() after create() method. You can just use create(). UPD If you need to exclude hotels with specific period of checkin/checkout from queryset you can use exclude(): Hotel_Database.objects.filter(hotel_name__icontains='Hotel').exclude( hotel__checkin__gte=datetime.date(2018, 6, 27), hotel__checkout__lte=datetime.date(2018, 6, 29))

http://stackoverflow.com/comment/89127670
comment on: http://stackoverflow.com/q/51068199
score: 0
type: QuestionComment
has text: So it's the ordering that could be causing the problem?
type: Comment

http://stackoverflow.com/comment/89086969
comment on: http://stackoverflow.com/a/51046626
score: 0
type: AnswerComment
has text: I understand, but I don´t have a name. The name is always a different.
type: Comment

http://stackoverflow.com/comment/89289063
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51135724
type: Comment
has text: @jedwards because just ommiting the `[]` in `t.join() for t in threads` is not legal syntax and the other option is to make it two lines. I'm also not trying to optimize here, just show a point.

http://stackoverflow.com/a/51027600
has comment: http://stackoverflow.com/comment/89047710
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51027453
downvote count: 0
has body: Using collections.Counter + itertools.chain: from collections import Counter from itertools import chain c = Counter(chain.from_iterable(df['column_name'].str.split('|'))) res = pd.Series(c) print(res) book 3 campfire 1 fish 2 icecream 1 dtype: int64

http://stackoverflow.com/q/51048251
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: dataframe
has title: Why does query break when I add a second condition? - Query dataframe on values 2+ columns
type: Question
has comment: http://stackoverflow.com/comment/89125889
duplicate of: http://stackoverflow.com/q/36921951
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89171042
tagged with: python
duplicate of: http://stackoverflow.com/q/40577773
linked to: http://stackoverflow.com/q/36921951
favorite count: 0
has comment: http://stackoverflow.com/comment/89087615
has body: Explanation of why query breaks when I add a second condition? My query works as long as I only query in one column. It breaks when I try to add a query for the second column in my dataframe. I am using python3 and pandas. I get back all the rows with 'MTC' in my 'Person' column. However, when I add an 'and' to get narrow down those rows, it turns into a boolean condition and I get an error message. How can I pull out all the rows with 'MTC' in the 'Person' column, that also have 3 in the 'ExpNum' column? Works great: print(df.loc[df['Person'] == 'MTC']) OrigID Person Date Threshold RevNum WL RevPos ExpNum \ 5032 3027 MTC 5/24/2018 0 1 440 16.881222 3 5033 3032 MTC 5/24/2018 0 2 440 22.881222 3 5034 3059 MTC 5/24/2018 0 3 440 6.431222 3 5035 3064 MTC 5/24/2018 0 4 440 12.431222 3 5036 3070 MTC 5/24/2018 0 5 440 12.431222 3 5037 3072 MTC 5/24/2018 0 6 440 13.931222 3 5038 3118 MTC 5/24/2018 0 7 440 5.731222 3 5039 3119 MTC 5/24/2018 0 8 440 7.231222 3 5040 3130 MTC 5/24/2018 0 9 440 2.311222 3 5041 3131 MTC 5/24/2018 0 10 440 5.311222 3 5042 3132 MTC 5/24/2018 0 11 440 5.311222 3 5043 3133 MTC 5/24/2018 0 12 440 6.811222 3 5044 3023 MTC 5/24/2018 0 1 452 26.063219 3 5045 3026 MTC 5/24/2018 0 2 452 22.773219 3 5046 3039 MTC 5/24/2018 0 3 452 40.773219 3 5047 3127 MTC 5/24/2018 0 4 452 19.453219 3 5048 3128 MTC 5/24/2018 0 5 452 20.953219 3 5049 3135 MTC 5/24/2018 0 6 452 12.753219 3 5050 3136 MTC 5/24/2018 0 7 452 14.253219 3 5051 3137 MTC 5/24/2018 0 8 452 14.253219 3 5052 3139 MTC 5/24/2018 0 9 452 15.753219 3 5053 3140 MTC 5/24/2018 0 10 452 11.653219 3 5054 3141 MTC 5/24/2018 0 11 452 13.153219 3 5055 3142 MTC 5/24/2018 0 12 452 9.873219 3 5056 3029 MTC 5/24/2018 0 1 464 18.288780 3 5057 3034 MTC 5/24/2018 0 2 464 30.288780 3 5058 3053 MTC 5/24/2018 0 3 464 0.000000 3 5059 3057 MTC 5/24/2018 0 4 464 6.000000 3 5060 3058 MTC 5/24/2018 0 5 464 6.000000 3 5061 3061 MTC 5/24/2018 0 6 464 7.500000 3 ... ... ... ... ... ... ... ... ... 6413 3208 MTC 5/24/2018 1 7 464 -2…
answer count: 0

http://stackoverflow.com/q/51050571
has comment: http://stackoverflow.com/comment/89092143
has comment: http://stackoverflow.com/comment/89092159
type: Question
has body: I have a dict: book = { 'id': 2, 'author': 'J.R.R. Tolkien', 'pages': 332, 'title': 'Fellowship', } err_msg='No such key' a = book.get('signature'),err_msg print(a) Result is: (None, 'No such key') Why I receive the tuple as a result instead of 'No such key'? In the documentation: get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
downvote count: 5
upvote count: 0
score: -5
answer count: 1
has answer: http://stackoverflow.com/a/51050599
favorite count: 0
tagged with: python-3.x
has title: Why dict.get return a tuple with None?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89286238
type: AnswerComment
has text: Can I add this as a solution here?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51150822

http://stackoverflow.com/q/51042058
tagged with: sqlite
tagged with: python
type: UnansweredQuestion
has body: import feedparser import re import smtplib import sqlite3 import time from datetime import date db = sqlite3.connect('nvd.db') c = db.cursor() def read_from_db(): read_from_db_list = [] c.execute('SELECT product_name FROM product') for row in c.fetchall(): read_from_db_list.append(row[0]) return read_from_db_list if 'windows' in read_from_db(): print('i have windows') When I run this I get nothing returned to me. But if in the function read_from_db() I add print(read_from_db_list) and just paste the function at the bottom of the script it will print me all of the objects in the list. I just want to be able to query the DB and check if certain keywords are in there. note: There are 7 'windows' matches in the db. edit: in the function, I've tried read_from_db_list.append((row)) and read_from_db_list.append(row) aswell here is what my DB looks like: https://s8.postimg.cc/u73jx3cet/image.png
has answer: http://stackoverflow.com/a/51042286
has answer: http://stackoverflow.com/a/51042300
type: Question
answer count: 2
has title: How to query SQLite 3 in python that is in a list
score: 0

http://stackoverflow.com/comment/89175685
comment on: http://stackoverflow.com/q/51093754
has text: Why do you need `requests` module to do this? `requests` is for making HTTP calls. You can easily randomize an IP-address using `random.randint`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51158537
linked to: http://stackoverflow.com/q/38830308
has body: I have below code to write a list items as csv file. But while doing that, I see special character Â is occurring in the output csv file. For testing in the local, I have defined a list with character '\xao' included in the list items and tested various ways to remove that and replace with space. But, I still get the special character in the csv output. Can anyone help? import csv from flask import make_response import StringIO csv_list = [['hfhf\xa0 fsdg','dsf'],['fsdgs fsdfs','fsdfsd'],['dsf\xa0 sf','asfg']] def download_csv_summary(csv_list): si = StringIO.StringIO() cw = csv.writer(si) filename = 'Test' cw.writerows(csv_list) output = make_response(si.getvalue()) output.headers['Content-Disposition'] = \ 'attachment; filename={filename}.csv'.format(filename=filename) output.headers['Content-Type'] = 'text/csv' return output
has answer: http://stackoverflow.com/a/51159159
has comment: http://stackoverflow.com/comment/89301375
tagged with: python
has title: remove \xa0 while writing csv file
has comment: http://stackoverflow.com/comment/89301122
has comment: http://stackoverflow.com/comment/89301382
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89301258
has comment: http://stackoverflow.com/comment/89300851
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/89301442
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89301334
has comment: http://stackoverflow.com/comment/89301034
favorite count: 0

http://stackoverflow.com/comment/89327046
has text: Definitely. The tautonyms are just an illustration though. Per your advice I'm going to try to separate the individual words in the categorical value column and one hot encode them. I was hoping to work in something like the Levenstein distance metric, but I cant think of how to add it as an input column. Here is what that colution may look like: https://stackoverflow.com/questions/38720283/python-string-clustering-with-scikit-learns-dbscan-using-levenshtein-distance
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51161782

http://stackoverflow.com/comment/89372930
has text: Hmmm, sounds interesting and rumor has it that it is better maintained than luigi now, I'll probably look at it next round (or next job I have) but I'm kind of full steam ahead with luigi by now :/
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51046942
type: QuestionComment

http://stackoverflow.com/q/51033773
has answer: http://stackoverflow.com/a/51033980
type: Question
score: -1
has body: I have a whole program that has a previous dictionary in a different function that gives me a list of departure and arrival cities for planes. I am trying to write a function that determines which keys have the most outgoing flights and I am unable to figure out how to find which keys have the most values. My dictionary is named flights which has the departure city as the keys and the arrivals as values. def outgoing(flights): length = 0 for i in (flights): if (len(flights[i]) > length): length = (len(flights[i])) break else: continue for i in flights: if (len(flights[i]) == length): pop = (len(flights[i])) print ("the most outgoing flight is: " , [i]) this code is suppose to work but for some reason it isn't giving me the correct max output from the file. Any ideas as to why?
tagged with: python-3.6
answer count: 2
downvote count: 1
tagged with: key
favorite count: 0
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51033829
upvote count: 0
has title: how to tell which key has the most value stored in a dictionary
type: UnansweredQuestion

http://stackoverflow.com/comment/123468798
has text: Hyperbole much? Trivial one-liners like `Test.name = Test._name` are hardly "much trouble." Although noxious boilerplate, that's still *much* less boilerplate than you'd inflict on yourself with the equivalent normal class (i.e., non-`@dataclass`).
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/61480946

http://stackoverflow.com/q/51028320
score: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89049166
favorite count: 0
has title: Unable to install Python 3.6 - version already exists
tagged with: installation
has body: I recently was given a new work laptop for a summer internship and am having some troubles installing Python 3.6. Whenever I go to install the file, I receive this error: After going to the control panel to try to uninstall whatever version is currently there, I find a 3.6 version listed in a (now deleted) Anaconda3 folder. When I try to uninstall that version, I receive this error: I'm stuck in a bit of an endless loop here, any idea how to fix it? Thanks in advance. Also, if this question is in the wrong section, apologies. This is the first installation question I've ever had.
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89049080
tagged with: anaconda

http://stackoverflow.com/q/51133448
type: AnsweredQuestion
downvote count: 1
type: Question
tagged with: arcpy
accepted answer: http://stackoverflow.com/a/51133522
score: -1
tagged with: arcmap
upvote count: 0
has body: The error is in the last line of code with the error saying SyntaxError: invalid syntax # Step 10 - DISSOLVE RDiffIntersect using FID_RDiffBuffer and FID_"AreaFileName" arcpy.Dissolve_management(in_features="RDiff_AreaIntersect", out_feature_class="C:/Users/User/Desktop/claudio.gdb/RDiff_AreaIntersect_Dissolve", dissolve_field="FID_RDiffBuffer", ORIG_FID, statistics_fields="OBJECTID_1 FIRST;FID_RDiffBuffer FIRST;gps_latitu FIRST;gps_longit FIRST", ORIG_FID FIRST, multi_part="MULTI_PART", unsplit_lines="DISSOLVE_LINES")
answer count: 1
favorite count: 0
has title: Syntax Errors in my Python code but I don't see where?
has answer: http://stackoverflow.com/a/51133522
tagged with: python

http://stackoverflow.com/q/51110108
type: UnansweredQuestion
tagged with: tatsu
tagged with: python
tagged with: keyword
type: Question
has title: Parsing code with caseless keyword with Tatsu / grako
has answer: http://stackoverflow.com/a/51311425
has body: I try to parse Fortran code with keyword which are caseless with Tatsu h! Is there a smarter way to define the keyword caseless than these : @@ keyword :: integer INTEGER etc... Thanks
score: 0
answer count: 1
tagged with: parsing

db2
tags question: http://stackoverflow.com/q/51098540
tags question: http://stackoverflow.com/q/51024921
tag name: db2
type: Tag

http://stackoverflow.com/q/51154931
answer count: 1
tagged with: tkinter-entry
favorite count: 0
has comment: http://stackoverflow.com/comment/89294870
has answer: http://stackoverflow.com/a/51156300
tagged with: tkinter
has body: I made a login panel, but i don't know, how to attach code to files, for example, if i run a .exe file, it runs my code first, and if the entries are filled correctly, the .exe file runs. My code: from tkinter import * import tkinter.messagebox import os` username = 'Zsolti' password = 'zsoltika2005' def WindowVariables(): global UsernameE global PasswordE def CheckLogin(): if UsernameE.get() == username and PasswordE.get() == password: tkinter.messagebox.showinfo('Login', 'Successfully logged in as: Zsolti') else: tkinter.messagebox.showinfo('Login', 'Login failed') window = Tk() MainFrame = Frame(width=110, height=40) MainFrame.grid() window.title('Login Panel') UsernameL = Label(window, text='Enter username') UsernameL.grid(row=0, column=0, sticky='e') PasswordL = Label(window, text='Enter password') PasswordL.grid(row=1, column=0, sticky='e') UsernameE = Entry(window, textvariable=username) UsernameE.grid(row=0, column=1, sticky='w') PasswordE = Entry(window, show='*', textvariable=password) PasswordE.grid(row=1, column=1, sticky='w') LoginButton = Button(window, text='Login!', command=CheckLogin) LoginButton.grid(row=2, columnspan=2) window.mainloop()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89295265
tagged with: python
downvote count: 0
score: 1
has title: How to attach Python code to exe file
has comment: http://stackoverflow.com/comment/89293750
type: Question
upvote count: 1

http://stackoverflow.com/a/51104390
score: 0
answers question: http://stackoverflow.com/q/51098303
type: Answer
has body: If you run this dummy example, do you get the layout that you want? import pandas as pd import numpy as np df=pd.DataFrame({'A':np.random.rand(2)-1,'B':np.random.rand(2)},index=['val1','val2'] ) ax = df.plot(kind='bar', color=['r','b'])

http://stackoverflow.com/q/51164849
accepted answer: http://stackoverflow.com/a/51164913
favorite count: 0
tagged with: python
score: 11
upvote count: 11
type: AnsweredQuestion
has body: This is the following sql query I want to execute and works perfectly on the command line: select * from table1 join table2 using (col1, col2) I am cannot figure out how to make this execute using SQLAlchemy and any help would be appreciated. There are no foreign keys between the tables. The table rows can only be paired up by values matching in multiple columns. Thank you!
has title: SQLAlchemy join syntax using multiple column names
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/51164913
downvote count: 0
tagged with: sql
tagged with: sqlite
answer count: 1

http://stackoverflow.com/comment/89123655
has text: What's wrong with `collections.Counter`? And `collections.defaultdict`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51066851
score: 2

http://stackoverflow.com/comment/89125849
has text: Try `re.sub(r'\b(\w{4,})(?:e?s|[ex])\b', r'\1', s)`
comment on: http://stackoverflow.com/q/51067741
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51028176
type: Answer
answers question: http://stackoverflow.com/q/51028091
score: 1
upvote count: 1
downvote count: 0
has body: In the first function, there is an extra step. It first creates a list, then sums it all together with sum. The second function simply iterates over them and adds it to a total.
has comment: http://stackoverflow.com/comment/89049600

http://stackoverflow.com/comment/89178409
score: 0
type: Comment
has text: Make the other python script add '1' to a txt when it's done, and then put a while loop in the original, and once it detects the '1', then end the program
type: QuestionComment
comment on: http://stackoverflow.com/q/51095139

http://stackoverflow.com/a/51154975
upvote count: 2
downvote count: 0
type: Answer
has body: As the error message states, you can only pass either the Arn or the Name parameter in the IamInstanceProfile dictionary. Unfortunately the Boto3 docs are a bit misleading here and lead to the impression that both can (or even have to be) passed in the call.
answers question: http://stackoverflow.com/q/51149832
score: 2

http://stackoverflow.com/a/51686647
score: 41
answers question: http://stackoverflow.com/q/51118815
has comment: http://stackoverflow.com/comment/93865558
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51118815
upvote count: 41
type: AcceptedAnswer
has body: A higher version of psycopg2 fixed the issue for me, update your requirements.txt to: ... psycopg2==2.7.5 ...
type: Answer
has comment: http://stackoverflow.com/comment/90336230

http://stackoverflow.com/comment/89091685
has text: The issue is that the db variable you are creating is a string. You want it to be the dataframe you are referencing, but it is being set as a string with the same name as the dataframe.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51050298

http://stackoverflow.com/comment/89275326
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51145212
has text: this is also an interesting way to see lambda function. The other answer was more aligned but I thank you for sharing this knowledge with me

http://stackoverflow.com/q/51032411
accepted answer: http://stackoverflow.com/a/51048255
has comment: http://stackoverflow.com/comment/89058567
has comment: http://stackoverflow.com/comment/89057293
tagged with: excel
has title: How can I programmatically return the location (row and column) of a keyword
has body: I am trying to use python to automate the analysis of hundreds of excel files. Currently I can open, write, and save files but I need to insert calculations in cells that contain keywords. I am using python 2.7, here is a snipet from my code where I am struggling: def run_analysis(): excel = Dispatch('Excel.Application') excel.DisplayAlerts = False keyword = "Total Traffic" x = 0 t = data_file_location_list while x &lt; len(t): #for files in data_file_location_list: wb = excel.Workbooks.Open(t[x].root_dir + "\\" + t[x].file_name) ws = wb.Sheets('Bandwidth Over Time') keyword_range = #here is where I am stuck ws.Range(keyword_range).Value = 'write something' wb.SaveAs(Filename=str(t[x].root_dir + "\\" + t[x].file_name)) wb.Close() excel.Quit() print x x += 1
type: Question
has comment: http://stackoverflow.com/comment/89057629
has comment: http://stackoverflow.com/comment/89057841
score: 0
has answer: http://stackoverflow.com/a/51048255
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89126607
type: Comment
has text: Thank you for the answer but have you timed this approach? It seems to be quite slower than mine.
comment on: http://stackoverflow.com/a/51068256
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89130421
comment on: http://stackoverflow.com/q/51069095
has text: @roganjosh good catch, but it looks like no matter what version I install it doesn't run correctly
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/51108722
tags question: http://stackoverflow.com/q/51019212
tags question: http://stackoverflow.com/q/51090798
tags question: http://stackoverflow.com/q/51137108
tags question: http://stackoverflow.com/q/51046731
tags question: http://stackoverflow.com/q/51043043
tags question: http://stackoverflow.com/q/51029908
tags question: http://stackoverflow.com/q/51167024
tags question: http://stackoverflow.com/q/51156674
tags question: http://stackoverflow.com/q/51124667
tag name: r
tags question: http://stackoverflow.com/q/51032452
tags question: http://stackoverflow.com/q/51155627
tags question: http://stackoverflow.com/q/51166806
tags question: http://stackoverflow.com/q/51145058
tags question: http://stackoverflow.com/q/51105485
type: Tag
tags question: http://stackoverflow.com/q/51048334
tags question: http://stackoverflow.com/q/51047722
tags question: http://stackoverflow.com/q/51022337
tags question: http://stackoverflow.com/q/51076218
tags question: http://stackoverflow.com/q/51117956
tags question: http://stackoverflow.com/q/51147176
tags question: http://stackoverflow.com/q/51064746
tags question: http://stackoverflow.com/q/51159010
tags question: http://stackoverflow.com/q/51030958
tags question: http://stackoverflow.com/q/51069236

http://stackoverflow.com/q/51126376
has answer: http://stackoverflow.com/a/51126407
score: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89237735
tagged with: if-statement
has body: Problem statement : IP addresses of the following forms are considered special local addresses: 10. * . * . * and 192.168. * . * . The stars can stand for any values from 0 to 255. Write a program that asks the user to enter an IP address and prints out whether it is in one of these two forms My code : s=input('Enter the IP address :') if s[0]==1 and s[1]==0 and s[2]=='.': print('It is a special IP address') elif s[0]==1 and s[1]==9 and s[2]==2 and s[3]=='.' and s[4]==1 and s[5]==6 and s[6]==8: print('It is a special IP address') else: print('It is an ordinary IP address') startwith() is a good option to solve this problem. However, i am unable to figure out why the above code always gives the output as 'It is an ordinary IP address' regardless of what the input is. Line(5) => and s[6]==8 is just and extension of elif statement.
upvote count: 1
downvote count: 1
type: Question
has title: multiple conditions in if statement using 'and'

http://stackoverflow.com/q/51067724
tagged with: array-broadcasting
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
downvote count: 0
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51068256
has body: I need to improve the performance of an operation performed on arrays of different shapes/sizes. The array pos has a shape of (2, 500) and the xa, xb, ya, yb arrays have shapes of (30,). The operation shown in the MVCE below combines each of the two dimensions of pos with xa, xb and ya, yb. Can this be done applying numpy broadcasting? import numpy as np # Some random data N = 30 xa, xb = np.random.uniform(0., 1., N), np.random.uniform(0., 1., N) ya, yb = np.random.uniform(0., 1., N), np.random.uniform(0., 1., N) # Grid M = 500 ext = [xa.min(), xa.max(), ya.min(), ya.max()] x, y = np.mgrid[ext[0]:ext[1]:complex(0, M), ext[2]:ext[3]:complex(0, M)] pos = np.vstack([x.ravel(), y.ravel()]) # Apply broadcasting on the operation performed by this 'for' block? vals = [] for p in zip(*pos): vals.append(np.sum(np.exp(-0.5 * ( ((p[0] - xa) / xb)**2 + ((p[1] - ya) / yb)**2)) / (xb * yb)))
type: AnsweredQuestion
tagged with: performance
has title: Broadcast operation on array of smaller size
has answer: http://stackoverflow.com/a/51068256
tagged with: numpy

http://stackoverflow.com/a/51039740
downvote count: 0
score: 1
type: Answer
has body: This is a general solution df.loc[df.country == country_to_update, values_to_update.keys()] = values_to_update.values() Out[]: country variable_1 variable_2 variable_3 0 Norway 7.537 1.6 2.9 1 Denmark 7.522 1.2 3.1 2 Switzerland 7.494 1.5 2.8 3 Finland 7.469 1.6 2.9 4 Netherlands 7.377 1.5 3
answers question: http://stackoverflow.com/q/51039505
upvote count: 1

http://stackoverflow.com/comment/89210976
has text: i edit my question and add function **checkPath()** that includes the **elif statement**
type: Comment
comment on: http://stackoverflow.com/a/51098418
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89044998
type: AnswerComment
has text: I see there is an `ipython` here, I am not sure you are using the same python environment here and where you installed pyserial, you should post the commands you type and the files you are running.
type: Comment
comment on: http://stackoverflow.com/a/51026235
score: 0

http://stackoverflow.com/a/65597293
score: 14
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/125080267
upvote count: 14
has body: single line solution df.isnull().mean().round(4).mul(100).sort_values(ascending=False)
answers question: http://stackoverflow.com/q/51070985

http://stackoverflow.com/a/59466218
has body: The directory for that tutorial is minus the pycache and .vscode. According to the tutorial, FLASK_APP=fua.py or microblog.py in your case. I am assuming that you did flask run in the C:\xampp\htdocs\FUA App\app&gt; directory since I faced a similar error when running that command from that directory. I solved the problem by running the command from the C:\xampp\htdocs\FUA App.
answers question: http://stackoverflow.com/q/51148947
type: Answer
score: 0

http://stackoverflow.com/q/51143187
score: 1
tagged with: dataframe
has body: I have a DataFrame that looks something like this: import numpy as np import pandas as pd df=pd.DataFrame([['vt 40462',5,6],[5,6,6],[5,5,8],[4,3,1],['vl 6450',5,6],[5,6,7], [1,2,3],['vt 40462',5,6],[5,5,8],['vl 658',6,7],[5,5,8],[4,3,1],['vt 40461',5,6],[5,5,8], [7,8,5]],columns=['A','B','C']) df A B C 0 vt 40462 5 6 1 5 6 6 2 5 5 8 3 4 3 1 4 vl 6450 5 6 5 5 6 7 6 1 2 3 7 vt 40462 5 6 8 5 5 8 9 vl 658 6 7 10 5 5 8 11 4 3 1 12 vt 40461 5 6 13 5 5 8 14 7 8 5 I want to give indexes the values that are between vt and vl in column A and create a new columns as : A B C D 0 vt 40462 5 6 vt 40462 1 5 6 6 vt 40462 2 5 5 8 vt 40462 3 4 3 1 vt 40462 4 vl 6450 5 6 vl 6450 5 5 6 7 vl 6450 6 1 2 3 vl 6450 7 vt 40462 5 6 vt 40462 8 5 5 8 vt 40462 9 vl 658 6 7 vl 658 10 5 5 8 vl 658 11 4 3 1 vl 658 12 vt 40461 5 6 vt 40461 13 5 5 8 vt 40461 14 7 8 5 vt 40461
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/51143326
favorite count: 0
has title: Create new column depending on values from other column
tagged with: pandas
has answer: http://stackoverflow.com/a/51143276
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51143276
upvote count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51143326
type: Question

http://stackoverflow.com/comment/89205853
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51109244
type: AnswerComment
has text: Yes, This is useful, is there way to further speed up ? I think the time limiting step is the for loop after groupby. I am working with large datasets that have several millions entry

http://stackoverflow.com/comment/89059688
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51033594
type: Comment
has text: Oh, so if you did something like instance = Foo() then self.name and self.description would basically be the same as instance.name or instance.description?

http://stackoverflow.com/comment/89101721
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51055277
has text: @YashGhorpade this is the complete code.
score: 0

http://stackoverflow.com/comment/89361052
has text: And before that name was suggested, they were called progmods (coined by tchrist?)
score: 1
comment on: http://stackoverflow.com/a/51165931
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51078349
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/93800066
has comment: http://stackoverflow.com/comment/89199732
has body: I don't think this is possible. The count_sort and distance_sort options only apply to the descendant nodes. Imagine your example with the labels 1 and 2 switched. In this case it would be impossible to have the nodes in order as node 1 would need to be forced between the paired nodes 0 and 1. This demonstrates that any process for ordering all the nodes is unscalable.
answers question: http://stackoverflow.com/q/51077293

http://stackoverflow.com/q/51053992
has title: Django - No add button for TabularInline
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89100750
linked to: http://stackoverflow.com/q/26310368
has comment: http://stackoverflow.com/comment/89135048
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51111628
upvote count: 3
has comment: http://stackoverflow.com/comment/89099509
type: Question
has comment: http://stackoverflow.com/comment/89210179
has body: I'm using Django 2.0.9 and I'm creating a simple TabularInline ModelAdmin, as follows: class AnswerInline(admin.TabularInline): model = Answer This is then used in a ModelAdmin object, like so: inlines = [AnswerInline]. The ModelAdmin is registered with the admin site. Everything works as expected, except that I do not see the ability to add further inline models. Here's what I mean: I've seen other inlines where there is such a button, which would dynamically add more fields that I can populate. I've tried overriding things on the TabularInline, like setting has_add_permission to return true and setting max_num to 1000, but I still cannot get the button to show up. Would appreciate some outside input here. Thanks!
tagged with: django-admin
has comment: http://stackoverflow.com/comment/89137722
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89099204
accepted answer: http://stackoverflow.com/a/51111628
tagged with: django-2.0

http://stackoverflow.com/q/51049923
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Python Plotly xaxis hover text disappears when hoverinfo is set in a trace
tagged with: plotly
type: Question
has body: I am plotting multiple (2) lines from a timeseries with plotly (v 2.7) in Jupyter notebook. I would like that, on hover, the axis label to appear, and a formatted text for one of the lines. First, I had data = [] name = 'houses' data.append( go.Scatter( x=df.index, y=df[name], name=name, ) ) name = 'vazamento' scale = 50 data.append( go.Scatter( x=df.index, y=df[name]*scale, name='leaks' + ' (ratio {0}:1)'.format(scale), ) ) fig = go.Figure(data=data) iplot(fig) which gave me Now, trying to show text on hover: name = 'vazamento' scale = 50 data.append( go.Scatter( x=df.index, y=df[name]*scale, name='leaks' + ' (ratio {0}:1)'.format(scale), # Added the two lines below text=df[name].apply(lambda x: "{0:.0f}".format(x)+" - ")+str('leaks'), hoverinfo='text', ) ) which results in the chart below, making the x axis info on hover disappear. I have tried editing the xaxis in the chart layout attribute, but had no success. How can I keep showing the X axis info on hover, just like it appears in the first chart?
has answer: http://stackoverflow.com/a/51050025
accepted answer: http://stackoverflow.com/a/51050025
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/101478699
type: Comment
comment on: http://stackoverflow.com/a/56749404
score: 0
has text: make sure to save xml above into a file named: 'Jenkinsfile.xml' and restart pycharm (make sure no open pycharm windows are forgotten)
type: AnswerComment

http://stackoverflow.com/q/51062069
has body: so here is my Code form.py: from django import forms from .models import Category class CategoryForm(forms.Form): # class Meta: # model = Category # fields = ('title',) title = forms.CharField(label = 'title', max_length=100) here is My view.py : def CategoryForm(request): if request.method == 'POST': form = CategroyForm(request.POST) if form.is_valid(): # category = form.save(commit = False) # category.title = post # category.save() return redirect('posts/create_blog.html') else: form = CategoryForm() template = 'posts/create_blog.html' context = {'form':form} return render(request,template,context) and here is my view.py : {% csrf_token %} {{ form.as_p }} I dont really understand whats th eproblenm inputs are not appear my model.py : class Category(models.Model): title = models.CharField(max_length=255) def __str__(self): self.title
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89113861
has comment: http://stackoverflow.com/comment/89114949
answer count: 0
has comment: http://stackoverflow.com/comment/89114835
type: Question
has title: Input Field Doesnot Appear
has comment: http://stackoverflow.com/comment/89113883
score: 0
has comment: http://stackoverflow.com/comment/89114082
has comment: http://stackoverflow.com/comment/89113953
has comment: http://stackoverflow.com/comment/89114146

http://stackoverflow.com/comment/89274178
has text: This addressed my question and it's a valuable lesson. Your answer it is greatly appreciated @BenG-TW. The only problem that I ran into was AssertionError X columns passed, passed data had N columns. If anyone has the same problem, I managed to solve it by using itertools: `pd.DataFrame.from_records((_ for _ in itertools.zip_longest(*data)), columns=labels)`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51141223

http://stackoverflow.com/q/51126737
linked to: http://stackoverflow.com/q/24322927
downvote count: 0
has comment: http://stackoverflow.com/comment/89238694
has title: Conditionally mapped module import
has body: I'm currently working on a abstract set of modules for Python 2.7, that I will ship as a python package: myabstractpkg - abstract - core - logging - ... - nodes - ... The modules will then be implemented in a totally different set of packages: myimppkg - implementation - core - logging - ... - nodes - ... At runtime however, I want to be able to do always imports like this in my tools that use the implemented modules: from myabstractpkg.api import nodes from myabstractpkg.api.core.logging import Logger This way the developer always imports from the "virtual" api module which would then decide where to actually point the importer. I know I might somehow be able to hack it together by modifying the modules dict: from myimppkg import implementation sys.modules["myabstractpkg.api"] = implementation or doing a clever import for everything in __init__.py of myabstractpackage.api, but this feels a bit fragile to me. I wonder if you guys have some input on what the best approach to do this is. I might be on a really ugly track with this whole remapping modules thing, so if you guys have any smarter, more pythonic solutions, for my API abstraction, implementation, usage approach, I would love to hear them.
has answer: http://stackoverflow.com/a/51127044
accepted answer: http://stackoverflow.com/a/51127044
has comment: http://stackoverflow.com/comment/89238408
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89238676
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/89238730
upvote count: 1
has comment: http://stackoverflow.com/comment/89238549
answer count: 1
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89238541
has comment: http://stackoverflow.com/comment/89238525
tagged with: python
has comment: http://stackoverflow.com/comment/89238468
has comment: http://stackoverflow.com/comment/89238606

glob
tags question: http://stackoverflow.com/q/51108256
tags question: http://stackoverflow.com/q/51097773
tag name: glob
type: Tag

http://stackoverflow.com/comment/89292476
type: AnswerComment
comment on: http://stackoverflow.com/a/51120715
has text: Thank you for your explanations. I will definitely use `Word (alphas, alphanums)` + special characters. Explanation of `#` and logic of pyparsing is very useful fo me. I used @Jappy's solution and changed my code, you can also see my **Edit 1** and say something about this?
score: 0
type: Comment

http://stackoverflow.com/comment/89171781
comment on: http://stackoverflow.com/a/51091718
score: 0
type: AnswerComment
has text: @Jade make sure you're careful about naming your variables! :). `user_Name` is different than `user_name`
type: Comment

http://stackoverflow.com/q/51161843
favorite count: 0
accepted answer: http://stackoverflow.com/a/51162299
tagged with: multithreading
upvote count: 1
tagged with: python
answer count: 1
tagged with: isr
tagged with: robotics
has answer: http://stackoverflow.com/a/51162299
downvote count: 0
has body: My school has a robotic arm (UR-10) that's hooked up to some buttons and I wanted to program it so the arm could move left and right smoothly when those buttons are clicked. Currently, I'm finding the arm just moves then stops then moves and stops in a jerking fashion. I wanted to implement an interrupt that could sense while a button is pressed down then the arm would continuously move by iterating through the loop fast enough so the arm would move without stopping. That is until the button is released. If there is an easier way to implement this I would love to hear it. Thanks! Below is my code. import urx #UR-10 library from threading import Thread class UR10(object): def __init__(self): # Establishes connection to UR-10 via IP address print("establishing connection") Robot = urx.Robot("192.168.100.82") self.r = Robot print("Robot object is available as robot or r") CheckingDigital_Inputs = Thread(target=self.ThreadChecker) CheckingDigital_Inputs.setDaemon(True) CheckingDigital_Inputs.start() MoveThread = Thread(target = self.MoveThread) MoveThread.setDaemon(True) MoveThread.start() def ThreadChecker(self): while True: self.TestingInputs() def TestingInputs(self): #Values = self.r.get_digital_in() self.In_1 = self.r.get_digital_in(1) self.In_2 = self.r.get_digital_in(2) #print("Digital Input 1 is {}, Digital Input 2 is {}".format(Values1, Values2)) def MoveThread(self): while True: self.LinearMovement() def LinearMovement(self): #print("linear move") #need to run at 125khz while self.In_1: print("move right linear") l = 0.05 v = 0.05 a = 0.05 pose = self.r.getl() print(pose) pose[0] += .01 self.r.movel(pose, acc=a, vel=v)
type: Question
type: AnsweredQuestion
score: 1
has title: Create interrupt (ISR) to create smooth robotic arm motion

http://stackoverflow.com/comment/89076163
comment on: http://stackoverflow.com/q/51041562
has text: Do you use virtualenv? And by the way, your imports are strange. I would always `from flask import Flask`, your code f.e doesn't work for me
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/89234029
type: AnswerComment
type: Comment
has text: Put several lines of the log in pastebin somewhere and I'll take a look.
comment on: http://stackoverflow.com/a/51124437
score: 0

http://stackoverflow.com/comment/89141996
has text: I copied the code and pasted it as text @GMB. Thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51076415

http://stackoverflow.com/q/51048266
has comment: http://stackoverflow.com/comment/89088444
has title: Python PIL can't open PDFs for some reason
favorite count: 0
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
upvote count: 13
has comment: http://stackoverflow.com/comment/89088384
has body: So my program is able to open PNGs but not PDFs, so I made this just to test, and it still isn't able to open even a simple PDF. And I don't know why. from PIL import Image with Image.open(r"Adams, K\a.pdf") as file: print file Traceback (most recent call last): File "C:\Users\Hayden\Desktop\Scans\test4.py", line 3, in &lt;module&gt; with Image.open(r"Adams, K\a.pdf") as file: File "C:\Python27\lib\site-packages\PIL\Image.py", line 2590, in open % (filename if filename else fp)) IOError: cannot identify image file 'Adams, K\\a.pdf' After trying PyPDF2 as suggested (Thanks for the link by the way), I am getting this error with my code. import PyPDF2 pdf_file= open(r"Adams, K (6).pdf", "rb") read_pdf= PyPDF2.PdfFileReader(pdf_file) number_of_pages = read_pdf.getNumPages() print number_of_pages Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/68640660
type: Question
has answer: http://stackoverflow.com/a/51048322
tagged with: python-imaging-library
score: 12
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/a/51163695
downvote count: 0
has body: Try defining it as: def fullname(self): [...] The self argument is implicitly passed in to method calls. It represents a reference to the object on which the method was invoked.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51163680

tf-idf
tags question: http://stackoverflow.com/q/51120323
tags question: http://stackoverflow.com/q/51011474
type: Tag
tag name: tf-idf

http://stackoverflow.com/q/51135289
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51135320
tagged with: dataframe
downvote count: 1
type: Question
upvote count: 0
score: -1
has title: How to take an average of three rows in a dataframe, and assign the index of the first row to the mean?
tagged with: pandas
has body: I have a dataframe that has 5-minute timestamps as the index and I would like to switch to 15-minute periods. So I would like to take the mean of 3 5-minute periods, and then assign the index value of the first period to that mean, building another dataframe. df1= variable_1 (Settlement_Date,) 2018-06-30 20:30:00 4.5 2018-06-30 20:35:00 3.8 2018-06-30 20:40:00 4.2 2018-06-30 20:45:00 4.1 2018-06-30 20:50:00 6.0 2018-06-30 20:55:00 3.3 2018-06-30 21:00:00 1.9 2018-06-30 21:05:00 2.8 2018-06-30 21:10:00 3.1 ... ... I want this dataframe to become some thing like this df1= variable_1 (Settlement_Date,) 2018-06-30 20:30:00 4.2 2018-06-30 20:45:00 4.5 2018-06-30 21:00:00 2.6 ... ... I have tried to use a 'for loop', but am having issues getting the date back into the dataframe mean_list = [] date_list = [] for i in range(len(df1)-3): mean_holding = df1[:i+3].mean() date_holding = df1.iloc[i+3] mean_list.append(mean_holding) date_list.append(date_holding)
answer count: 1

http://stackoverflow.com/q/51068938
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89128161
accepted answer: http://stackoverflow.com/a/51069004
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/89128186
downvote count: 1
type: Question
has body: I'm having an issue getting a response from an rest API into a json format with Pandas. Here's my code: import pandas as pd import numpy as np import requests import json headers = { 'Authorization': 'Token token="mytoken"', 'Content-Type': 'application/json', 'Cache-Control': 'no-cache--url', } response = requests.get('https://www.someurl.com/api/path', headers=headers) data = response.json() This is my issue: Whenever I check the data type that I get in response, it is in a dictionary format, like so: In[2]: type(data) Out[2]: dict Because it returns text that's in a JSON format, but it comes into my code as a dictionary, I cannot use panda's .read_json() command because it appears that it's expecting a JSON datatype. Whenever I try to do that, it returns this: In[3]: pd.read_json(data) Out[3]: ValueError: Invalid file path or buffer object type: &lt;class 'dict'&gt; I think the main issue is that my response returns in the form of a dictionary instead of pure JSON, and not because of the syntax within the JSON data itself, but by no means am I an expert in this subject. Let me know what you guys think. Here's the documentation to the API I'm using: https://documentation.joinhandshake.com/v1.0/reference#introduction Any help would be greatly appreciated.
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51069004
has title: Response from API is in a dictionary format
tagged with: pandas
tagged with: api
has comment: http://stackoverflow.com/comment/89127861
answer count: 1
has comment: http://stackoverflow.com/comment/89127879
favorite count: 0

http://stackoverflow.com/a/51139339
has body: there will be many values that satisfy the condition. eg take an example where H is identity matrix and y is for example 5, then x can be c(1,2) or (2,1) or (1.656615, 1.501874) or (2.2184971, 0.2797686) etc etc.. So all this form an elipse at which the sol is 5: thus we can do: optim(c(0,1.9),function(x,H,y)abs(c(crossprod(x,solve(H,x)))-y),H=diag(2),y=5) You can test the solutions given from the above code and you will see that they actually give 5. choose any starting values: s=function(w,u)optim(c(w,u),function(x,H,y)abs(c(crossprod(x,solve(H,x)))-y),H=diag(2),y=5)$par a=1:4 r=t(mapply(s,a,rep(a,each=length(a)))) cbind(r,rowSums(r^2)) [,1] [,2] [,3] [1,] 1.2216786 1.8728325 5 [2,] 2.0000000 1.0000000 5 [3,] 1.1964828 1.8890286 5 [4,] 0.2209853 2.2251215 5 [5,] 1.0000000 2.0000000 5 [6,] 1.6566155 1.5018739 5 [7,] 0.1675176 2.2297843 5 [8,] 1.2257806 1.8701503 5 [9,] 1.8890286 1.1964828 5 [10,] 2.2297843 0.1675176 5 [11,] 1.6043461 1.5575857 5 [12,] 1.2658540 1.8432617 5 [13,] 2.2251215 0.2209853 5 [14,] 1.8701503 1.2257806 5 [15,] 1.8432617 1.2658540 5 [16,] 1.6636298 1.4941003 5 You see that all of them give you 5.
has comment: http://stackoverflow.com/comment/89431133
has comment: http://stackoverflow.com/comment/89283307
type: Answer
has comment: http://stackoverflow.com/comment/89437525
score: 1
has comment: http://stackoverflow.com/comment/89284097
has comment: http://stackoverflow.com/comment/89284271
upvote count: 1
answers question: http://stackoverflow.com/q/51137108
accepted answer of: http://stackoverflow.com/q/51137108
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89146483
has text: It worked!!! Thanks a lot!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51069106
type: QuestionComment

http://stackoverflow.com/comment/89037791
comment on: http://stackoverflow.com/a/51022553
type: AnswerComment
score: 0
type: Comment
has text: I'm asking, because with a preallocated list the results of `code_for` are the same as without putting elements to a list at all. `append()` is slower, of course.

http://stackoverflow.com/comment/92222776
type: AnswerComment
score: 0
has text: You can use `CustomRatesUpdate()` (link: https://www.mql5.com/en/docs/customsymbols/customratesupdate) to add `MqlRates` instead of `MqlTick`. Also you need to feed MqlRates using close,max,min,open,volume,from values as shown with MqlTick
type: Comment
comment on: http://stackoverflow.com/a/51199962

http://stackoverflow.com/comment/89207743
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51110281
type: AnswerComment
has text: This does not work when there is a repeated element in one of the sub-lists. I.e. `[[1,1,2,3], [1,2,3]]`

http://stackoverflow.com/comment/89292398
type: AnswerComment
has text: I haven’t modify the output.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51153356

http://stackoverflow.com/comment/89058167
type: AnswerComment
type: Comment
has text: I ended up getting it to work by using the command: ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password' Your answer helped lead me to the right way so thank you.
comment on: http://stackoverflow.com/a/51030424
score: 1

django
tags question: http://stackoverflow.com/q/51052244
tags question: http://stackoverflow.com/q/51089173
tags question: http://stackoverflow.com/q/51107962
tags question: http://stackoverflow.com/q/51019330
tags question: http://stackoverflow.com/q/51147291
tags question: http://stackoverflow.com/q/51105710
tags question: http://stackoverflow.com/q/51142123
tags question: http://stackoverflow.com/q/51078402
tags question: http://stackoverflow.com/q/51110020
tags question: http://stackoverflow.com/q/51099201
tags question: http://stackoverflow.com/q/51127473
tags question: http://stackoverflow.com/q/51157308
tags question: http://stackoverflow.com/q/51049173
tags question: http://stackoverflow.com/q/51028444
tags question: http://stackoverflow.com/q/51111591
tags question: http://stackoverflow.com/q/51027868
tags question: http://stackoverflow.com/q/51022942
tags question: http://stackoverflow.com/q/51034526
tags question: http://stackoverflow.com/q/51164247
tags question: http://stackoverflow.com/q/51110222
tags question: http://stackoverflow.com/q/51148142
tags question: http://stackoverflow.com/q/51117355
tags question: http://stackoverflow.com/q/51081572
tags question: http://stackoverflow.com/q/51113358
tags question: http://stackoverflow.com/q/51043744
tags question: http://stackoverflow.com/q/51047718
tags question: http://stackoverflow.com/q/51037568
tags question: http://stackoverflow.com/q/51036397
tags question: http://stackoverflow.com/q/51033849
tags question: http://stackoverflow.com/q/51055970
tags question: http://stackoverflow.com/q/51122141
tags question: http://stackoverflow.com/q/51092139
tags question: http://stackoverflow.com/q/51108247
tags question: http://stackoverflow.com/q/51103910
tags question: http://stackoverflow.com/q/51117217
tags question: http://stackoverflow.com/q/51153111
tags question: http://stackoverflow.com/q/51080392
tags question: http://stackoverflow.com/q/51029368
tags question: http://stackoverflow.com/q/51127563
tags question: http://stackoverflow.com/q/51143201
tags question: http://stackoverflow.com/q/51135849
type: Tag
tags question: http://stackoverflow.com/q/51056816
tags question: http://stackoverflow.com/q/51071206
tags question: http://stackoverflow.com/q/51126846
tags question: http://stackoverflow.com/q/51121460
tags question: http://stackoverflow.com/q/51098111
tags question: http://stackoverflow.com/q/51062069
tags question: http://stackoverflow.com/q/51083887
tags question: http://stackoverflow.com/q/51134016
tags question: http://stackoverflow.com/q/51157698
tags question: http://stackoverflow.com/q/51144702
tags question: http://stackoverflow.com/q/51091856
tags question: http://stackoverflow.com/q/51062823
tags question: http://stackoverflow.com/q/51164130
tags question: http://stackoverflow.com/q/51062760
tags question: http://stackoverflow.com/q/51163017
tags question: http://stackoverflow.com/q/51071923
tags question: http://stackoverflow.com/q/51045241
tags question: http://stackoverflow.com/q/51072426
tags question: http://stackoverflow.com/q/51163088
tags question: http://stackoverflow.com/q/51134570
tags question: http://stackoverflow.com/q/51084582
tags question: http://stackoverflow.com/q/51127052
tags question: http://stackoverflow.com/q/51117503
tags question: http://stackoverflow.com/q/51120313
tags question: http://stackoverflow.com/q/51045572
tags question: http://stackoverflow.com/q/51117208
tags question: http://stackoverflow.com/q/51050018
tags question: http://stackoverflow.com/q/51129427
tags question: http://stackoverflow.com/q/51030164
tags question: http://stackoverflow.com/q/51068159
tags question: http://stackoverflow.com/q/51117915
tags question: http://stackoverflow.com/q/51057852
tags question: http://stackoverflow.com/q/51116923
tags question: http://stackoverflow.com/q/51058756
tags question: http://stackoverflow.com/q/51097943
tags question: http://stackoverflow.com/q/51133829
tags question: http://stackoverflow.com/q/51159184
tags question: http://stackoverflow.com/q/51144565

http://stackoverflow.com/a/51100779
downvote count: 0
upvote count: 2
has body: You can use delimiter='\n' with csv.writer.writerow (notice, not writerows). In addition, newline='' is not required as an argument to open. import sys import os import csv L = ['name1@domain.com', 'name2@domain.com', 'name3@domain.com'] def write_to_csv(list_of_emails): with open('emails.csv', 'w') as csvfile: writer = csv.writer(csvfile, delimiter='\n') writer.writerow(list_of_emails) write_to_csv(L)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51100680

http://stackoverflow.com/comment/89193077
comment on: http://stackoverflow.com/q/51102758
has text: @RedEyed Just tried. Was still able to do equality check. `TypeError` on < or >.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89307314
type: AnswerComment
type: Comment
has text: Sorry Sorry i been testing in local bot so it not worked. i will add server ID now.
comment on: http://stackoverflow.com/a/51161260
score: 0

http://stackoverflow.com/q/51153010
has body: I am getting an exception as I try to slice with a logical expression my Pandas dataframe. My data have the following form: df GDP_norm SP500_Index_deflated_norm Year 1980 2.121190 0.769400 1981 2.176224 0.843933 1982 2.134638 0.700833 1983 2.233525 0.829402 1984 2.395658 0.923654 1985 2.497204 0.922986 1986 2.584896 1.09770 df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 38 entries, 1980 to 2017 Data columns (total 2 columns): GDP_norm 38 non-null float64 SP500_Index_deflated_norm 38 non-null float64 dtypes: float64(2) memory usage: 912.0 bytes The command is the following: df[((df['GDP_norm'] &gt;=3.5 &amp; df['GDP_norm'] &lt;= 4.5) &amp; (df['SP500_Index_deflated_norm'] &gt; 3)) | ( (df['GDP_norm'] &gt;= 4.0 &amp; df['GDP_norm'] &lt;= 5.0) &amp; (df['SP500_Index_deflated_norm'] &lt; 3.5))] The error message is the following: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
favorite count: 0
has answer: http://stackoverflow.com/a/51153053
has title: Slicing with a logical (boolean) expression a Pandas Dataframe
type: AnsweredQuestion
upvote count: 5
tagged with: slice
has answer: http://stackoverflow.com/a/51153151
accepted answer: http://stackoverflow.com/a/51153053
type: Question
tagged with: logical-operators
answer count: 2
score: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/51153151
tagged with: pandas
tagged with: boolean-expression
tagged with: python

bokeh
tags question: http://stackoverflow.com/q/51078709
tags question: http://stackoverflow.com/q/51019712
tags question: http://stackoverflow.com/q/51090223
type: Tag
tags question: http://stackoverflow.com/q/51102348
tags question: http://stackoverflow.com/q/51093056
tags question: http://stackoverflow.com/q/51116689
tags question: http://stackoverflow.com/q/51015662
tags question: http://stackoverflow.com/q/51031137
tags question: http://stackoverflow.com/q/51067175
tags question: http://stackoverflow.com/q/51144743
tags question: http://stackoverflow.com/q/51113004
tags question: http://stackoverflow.com/q/51161586
tags question: http://stackoverflow.com/q/51051625
tag name: bokeh
tags question: http://stackoverflow.com/q/51054559

http://stackoverflow.com/q/51154729
answer count: 3
has body: I am getting an Error using pytesseract. I installed it via pip install. Code: import pytesseract from PIL import Image img = Image.open('frame_0000.png') x = pytesseract.image_to_string(Image.open('frame_0000.png')) The Error occurs in the last line. (x = ...) Result: Traceback (most recent call last): File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 194, in run_and_get_output run_tesseract(**kwargs) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 165, in run_tesseract proc = subprocess.Popen(command, **subprocess_args()) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in init restore_signals, start_new_session) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 990, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 6, in x = pytesseract.image_to_string(Image.open('frame_0000.png')) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 286, in image_to_string return run_and_get_output(image, 'txt', lang, config, nice) File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 201, in run_and_get_output raise TesseractNotFoundError() pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path I am trying to get a workaround running but my inexperience prevents me from implementing this correctly: tessdata_dir_config = '--tessdata-dir "&lt;replace_with_your_tessdata_dir_path&gt;"' # Example config: '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"' # It's important to include double qu…
possible better answer: http://stackoverflow.com/a/52006894
downvote count: 0
accepted answer: http://stackoverflow.com/a/51156863
has answer: http://stackoverflow.com/a/52006894
has comment: http://stackoverflow.com/comment/89294297
favorite count: 0
has comment: http://stackoverflow.com/comment/89296806
has comment: http://stackoverflow.com/comment/89297010
tagged with: python
has answer: http://stackoverflow.com/a/51583595
has comment: http://stackoverflow.com/comment/89293452
has title: Pytesseract TesseractNotFoundError [Python 3]
score: 1
has comment: http://stackoverflow.com/comment/89296856
upvote count: 1
has answer: http://stackoverflow.com/a/51156863
tagged with: tesseract
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89292773
has comment: http://stackoverflow.com/comment/89296777
type: Question

http://stackoverflow.com/a/51069893
score: 4
has body: With pip3 you are installing module for python 3, It can b that you have both versions of python 2 and 3 and you your environment is pointing default to python 2 Check python version or install wget for python 2 python -V pip install wget
type: Answer
answers question: http://stackoverflow.com/q/51069716
has comment: http://stackoverflow.com/comment/89131103
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89309279
type: QuestionComment
has text: How will you ever get out of the `while True:` loop?
type: Comment
comment on: http://stackoverflow.com/q/51160350
score: 0

http://stackoverflow.com/q/51065490
type: Question
has title: How to show original feature names in the feature importance plot?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51066195
has body: I created XGBoost model as follows: y = XY.DELAY_MIN X = standardized_df train_X, test_X, train_y, test_y = train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25) my_imputer = preprocessing.Imputer() train_X = my_imputer.fit_transform(train_X) test_X = my_imputer.transform(test_X) xgb_model = XGBRegressor() # Add silent=True to avoid printing out updates with each cycle xgb_model = XGBRegressor(n_estimators=1000, learning_rate=0.05) xgb_model.fit(train_X, train_y, early_stopping_rounds=5, eval_set=[(test_X, test_y)], verbose=False) When I create the feature importance plot, the feature names are shown as "f1", "f2", etc. How can I show original feature names? fig, ax = plt.subplots(figsize=(12,18)) xgb.plot_importance(xgb_model, max_num_features=30, height=0.8, ax=ax) plt.show()
answer count: 1
downvote count: 0
tagged with: xgboost
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51066195
upvote count: 1
has comment: http://stackoverflow.com/comment/138379330

http://stackoverflow.com/a/51036265
has body: Try using response.content Ex: &gt;&gt;&gt; import requests &gt;&gt;&gt; from readability import Document &gt;&gt;&gt; &gt;&gt;&gt; response = requests.get('http://www.gamersky.com/news/201806/1064930.shtml') &gt;&gt;&gt; doc = Document(response.content) &gt;&gt;&gt; print doc.title()
downvote count: 0
answers question: http://stackoverflow.com/q/51036156
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/89160520
type: Comment
has text: I'm receiving a Traceback (most recent call last): File "bad_cams.py", line 25, in <module> new_list = [it for it in last_updated_list if it[0][1].date() != today] File "bad_cams.py", line 25, in <listcomp> new_list = [it for it in last_updated_list if it[0][1].date() != today] IndexError: list index out of range
score: 0
comment on: http://stackoverflow.com/a/51085915
type: AnswerComment

http://stackoverflow.com/comment/89111719
type: Comment
type: QuestionComment
has text: I think --add-data is right, not --add-date.
score: 0
comment on: http://stackoverflow.com/q/51060894

http://stackoverflow.com/comment/95493974
comment on: http://stackoverflow.com/a/54338006
type: AnswerComment
score: 0
type: Comment
has text: Okay thanks. To conclude. Is it best to not do variable assignment in the debugger? Sounds like using the `interact` feature is the way to go for that. (Incidentally: `[i for i in range(x)]` does *not* raise the error!)

http://stackoverflow.com/comment/89084673
comment on: http://stackoverflow.com/a/51045925
has text: by wide format i mean having day,start,end all in a single column and values kept in rows next to them like day 0 1 2 3 4 5 6 and similarly for other like start 1100 2200 1100 2200....
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51117737
type: Answer
score: 1
has body: By calling print(a) in mydef1, python is looking for a local (or global, as you discovered) variable "a". That is, a variable not directly related to MyClass1 in any way, but such a variable has not been defined yet. If you're trying to access the class variable "a" (i.e. a is a member of the class itself, not any instance of it), you must use MyClass1.a. Alternatively, because there is no instance variable named "a", you can also use self.a to the same effect. However, as soon as self.a is explicitly defined, self.a == MyClass1.a may not be true. For example: &gt;&gt;&gt;class MyClass1: ... a = 25 ... &gt;&gt;&gt;my_obj = MyClass1() &gt;&gt;&gt;MyClass1.a 25 &gt;&gt;&gt;my_obj.a 25 &gt;&gt;&gt;MyClass1.a += 1 &gt;&gt;&gt;MyClass1.a 26 &gt;&gt;&gt;my_obj.a 26 &gt;&gt;&gt;my_obj.a = 5 # explicitly define "a" for this instance; my_obj.a not longer synonymous with MyClass1.a &gt;&gt;&gt;MyClass1.a += 1 &gt;&gt;&gt;MyClass1.a 27 &gt;&gt;&gt;my_obj.a 5
upvote count: 1
has comment: http://stackoverflow.com/comment/120185738
answers question: http://stackoverflow.com/q/51117397
downvote count: 0

http://stackoverflow.com/a/51087238
upvote count: 1
has comment: http://stackoverflow.com/comment/89460355
downvote count: 0
has comment: http://stackoverflow.com/comment/89213781
answers question: http://stackoverflow.com/q/51086289
has comment: http://stackoverflow.com/comment/89441408
type: AcceptedAnswer
has body: import requests from bs4 import BeautifulSoup r = requests.get('https://www.bbc.co.uk/news/uk-44496876') soup = BeautifulSoup(r.content, "html.parser") article_soup = [s.get_text() for s in soup.find_all('p', {'dir': 'ltr'})] tweets = '\n'.join(article_soup) print(tweets) If you also want to get the author of the tweets it's a bit tricky since you don't have a tag for the author. So I used a python code to remove all the tags in between the author like this: import requests from bs4 import BeautifulSoup r = requests.get('https://www.bbc.co.uk/news/uk-44496876') soup = BeautifulSoup(r.content, "html.parser") articles_soup = [s for s in soup.find_all('blockquote', {'class': 'twitter-tweet'})] tweets = [] for article_soup in articles_soup: tweet = article_soup.find('p').get_text() # The last &lt;a href='...'&gt;&lt;/a&gt; is the date, others are part of the tweet date = article_soup.find_all('a')[-1].get_text() tweet_author = article_soup.get_text()[len(tweet):-len(date)].strip() tweets.append((tweet_author, tweet)) print(tweets) Note1: if you want to get only parts of the tweet_author you can easily take the tuple first element and tweek it to get the object that you want. Note2: the question code example does not always return tweets, the issue is with the html page since from time to time several elements do not return. The fast solution is to run the requests.get method once more - I suggest you look into this issue. Once I got the tweets with the original question, I found the tags and I got the tweets that you expected to get, each tweet in a different line in my code.
has comment: http://stackoverflow.com/comment/89409475
has comment: http://stackoverflow.com/comment/89188246
type: Answer
has comment: http://stackoverflow.com/comment/89230396
score: 1
accepted answer of: http://stackoverflow.com/q/51086289
has comment: http://stackoverflow.com/comment/89462979

http://stackoverflow.com/comment/89049928
type: AnswerComment
score: 0
type: Comment
has text: Will this also apply to the paragraph further down, below and including the heading TECHNICAL FIELD?
comment on: http://stackoverflow.com/a/51028512

http://stackoverflow.com/comment/89301212
type: AnswerComment
comment on: http://stackoverflow.com/a/51158982
has text: In this case also `num_list` can itself be expressed as `range(1, 5)`, simplifying your construct some.
type: Comment
score: 1

http://stackoverflow.com/comment/109051429
type: Comment
has text: I made some good experience with the `ff` package.
type: QuestionComment
comment on: http://stackoverflow.com/q/51069236
score: 0

http://stackoverflow.com/q/51103125
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51103197
type: Question
tagged with: data-visualization
has comment: http://stackoverflow.com/comment/89193770
upvote count: 1
tagged with: python
answer count: 1
tagged with: heatmap
has title: Build a heatmap in Pandas
has body: The DataFrame below includes information about launchung of a program. week day number of launchings 2016-12-19 - 2016-12-25 Mon 70 2016-12-19 - 2016-12-25 Tue 91 2016-12-19 - 2016-12-25 Wed 117 2016-12-19 - 2016-12-25 Thu 57 2016-12-19 - 2016-12-25 Fri 33 2016-12-19 - 2016-12-25 Sat 38 2016-12-19 - 2016-12-25 Sun 27 2016-12-26 - 2017-01-01 Mon 52 2016-12-26 - 2017-01-01 Tue 52 2016-12-26 - 2017-01-01 Wed 41 2016-12-26 - 2017-01-01 Thu 60 2016-12-26 - 2017-01-01 Fri 25 2016-12-26 - 2017-01-01 Sat 12 2016-12-26 - 2017-01-01 Sun 51 ... I need to get a heatmap with the next structure:
has comment: http://stackoverflow.com/comment/89193710
has comment: http://stackoverflow.com/comment/89193482
has answer: http://stackoverflow.com/a/51103197
tagged with: pandas
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/89117402
comment on: http://stackoverflow.com/a/51063655
type: AnswerComment
score: 0
type: Comment
has text: It will automatically returns the `serializer.data` which is taken from `request.data`.

http://stackoverflow.com/a/51072315
upvote count: 2
answers question: http://stackoverflow.com/q/51072262
has body: Convert your time series to timedelta, then use groupby + diff: df['Time'] = pd.to_timedelta(df['Time']+':00') df['Diff'] = df.groupby('Category')['Time'].diff().fillna(0) print(df) Time Category Diff 0 12:37:00 'one' 00:00:00 1 12:39:00 'two' 00:00:00 2 12:41:00 'two' 00:02:00 3 12:45:00 'one' 00:08:00 4 12:46:00 'one' 00:01:00 If string formatting is important to you: df['Diff'] = df['Diff'].apply(lambda x: f'{int(x.seconds/60)} min') print(df) Time Category Diff 0 12:37:00 'one' 0 min 1 12:39:00 'two' 0 min 2 12:41:00 'two' 2 min 3 12:45:00 'one' 8 min 4 12:46:00 'one' 1 min
score: 2
downvote count: 0
type: Answer

ironpython
tags question: http://stackoverflow.com/q/51114987
tags question: http://stackoverflow.com/q/51114132
tags question: http://stackoverflow.com/q/51121693
tag name: ironpython
tags question: http://stackoverflow.com/q/51084028
type: Tag

http://stackoverflow.com/comment/89332417
has text: If I do that, only one vehicle will visit it. So I imagine that I have to create one for each vehicle with no cost / no penalty so it is visited only when required ? If many refuel are required, then the number of required refuel is not predictable but bound. I'll try that, thank you !
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51153760
type: Comment

http://stackoverflow.com/a/51167329
answers question: http://stackoverflow.com/q/51166586
has comment: http://stackoverflow.com/comment/89360553
type: Answer
score: 2
upvote count: 2
has body: Here is a method that uses mostly functionality from the standard library: from collections import Counter from itertools import combinations, chain raw_pairs = ['BCH/BTC', 'BCH/ETH', 'DASH/USD', 'BTC/USDT', 'ETH/BTC'] def parse_pair(raw_pair): return raw_pair.split('/') def is_trair(trair_candidate): # assuming that all currencies appear twice means we have a trair currency_counts = Counter(chain.from_iterable(trair_candidate)) return set(currency_counts.values()) == {2} pairs = map(parse_pair, raw_pairs) trair_candidates = combinations(pairs, r=3) # filter the actual trairs from all trair_candidates trairs = filter(is_trair, trair_candidates) print(list(trairs)) Will give: [(['BCH', 'BTC'], ['BCH', 'ETH'], ['ETH', 'BTC'])]
downvote count: 0

http://stackoverflow.com/comment/89100319
score: 0
has text: I need the values with an underscore..thread_name (not threadName)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51042109

http://stackoverflow.com/comment/89320046
has text: NVM I found out: it works with `browser.find_element_by_xpath("//input[@type='submit' and @value='OK']").click()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51157815

http://stackoverflow.com/q/51164460
downvote count: 0
has title: TypeError: 'float' object is not iterable; occurs when calling class from another file
type: Question
score: 1
has body: This is my first time posting on stackoverflow so thanks for the help. I am relatively new to python and this is my first time working on a personal project involving coding. The ultimate point of the file is to create a class to plot motor curves based on inputs. My main file currently is: import motor import plot if __name__ == '__main__': try: x = motor.motor(6.5,0.275,0.0343,1047,6) print(x.Imax,x.Imin,x.Tmax,x.Wmax,x.V,x.Kv(),x.Kt()) a = map(1047,0.0343,x.kt,0.275,6) #a.plot() except KeyboardInterrupt: print('Quitting') motor.py is working as expected. When the code gets to a = map(1047,0.343,x.kt,0.275,6) I get the error : TypeError :'float' object is not iterable. map is a class that I created and is provided by plot.py. The current code is as follows: class map: def __init__(self,Wmax,Tmax,kt,Imin,V): #Defines Inputs self.Wmax = Wmax self.Tmax = Tmax self.kt = kt self.Imin = Imin self.V = V #Defines motor opperating range self.Wrange = np.arange(0,int(self.Wmax),1) #Defines Torque as a function of angular velocity #self.T_function = self.Tmax*(1-self.Wrange/self.Wmax) #Defines mechanical power as a functionof angular velocity #self.Pmech_function = self.Tmax*(1-self.Wrange/self.Wmax)\ #*self.Wrange #Defines electrical power as a function of Torque #self.Pelec_function =((self.Tmax*(1-self.Wrange/self.Wmax\ #))/self.kt+self.Imin)*self.V #Defines efficiency as a function of pmech and pelec #self.eff_function = (self.Tmax*(1-self.Wrange/self.Wmax)*\ #self.Wrange)/(((self.Tmax*(1-self.Wrange/self.Wmax))/self\ #.kt+self.Imin)*self.V) #self.Wlabel = 'Angular Velocity (rad/sec)' #self.Tlabel = 'Torque (N-m)' #self.Pmech_label = 'Mechanical Power (Watts)' #self.Pelec_label = 'Electrical Power (Watts)' #self.eff_label ='Efficiency (%)' """ def plot(self): #Creates main window fig = plt.figure() #Creates four y-axis ax = fig.add_subplot(111) ax2 = ax.twinx() ax3 = ax.twinx() ax4 = ax.twinx() #Plots the above functions against Wrange ax.plot(self.Wrange,self.T_function…
tagged with: numpy
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89312677
accepted answer: http://stackoverflow.com/a/51164526
has comment: http://stackoverflow.com/comment/89312683
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51164526
type: AnsweredQuestion

http://stackoverflow.com/q/51074511
has body: Say I ran this code in Python: while True: try: anything that doesn't break loop except: pass How would I ever get it to stop? (Note: I suspect this isn't one of those times where I should learn by testing). Of course in reality I would use a break statement. This is a theoretical question; how could one break this loop if even a KeyboardInterrupt is passed?
favorite count: 0
has answer: http://stackoverflow.com/a/51074604
type: Question
tagged with: exception
has comment: http://stackoverflow.com/comment/89138441
has comment: http://stackoverflow.com/comment/89138377
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89172973
has title: How to stop execution of infinite loop with exception handling?
upvote count: 2
tagged with: loops
tagged with: infinite-loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51074562
score: 2
downvote count: 0

micropython
tags question: http://stackoverflow.com/q/51029111
tags question: http://stackoverflow.com/q/51160692
type: Tag
tags question: http://stackoverflow.com/q/51072268
tag name: micropython

http://stackoverflow.com/comment/89626887
type: Comment
comment on: http://stackoverflow.com/q/51065320
has text: Once the filter has identified the ions with the stop position of 4.125, I then use the ion number to extract from the raw data file ions which match these ion numbers. As you can see in the question above the desired csv file contains only one instance of each ion rather than two (as they appear in the raw data). I hope I have explained this well. Please let me know if you need further clarification.
score: 0
type: QuestionComment

for-loop
tags question: http://stackoverflow.com/q/51013621
tags question: http://stackoverflow.com/q/51091336
tags question: http://stackoverflow.com/q/51032717
tags question: http://stackoverflow.com/q/51092842
tags question: http://stackoverflow.com/q/51046266
tags question: http://stackoverflow.com/q/51097699
tags question: http://stackoverflow.com/q/51067654
tags question: http://stackoverflow.com/q/51028241
tags question: http://stackoverflow.com/q/51024384
tags question: http://stackoverflow.com/q/51025894
tags question: http://stackoverflow.com/q/51013615
tags question: http://stackoverflow.com/q/51013059
tags question: http://stackoverflow.com/q/51158872
tags question: http://stackoverflow.com/q/51156919
tags question: http://stackoverflow.com/q/51014163
tag name: for-loop
tags question: http://stackoverflow.com/q/51068194
tags question: http://stackoverflow.com/q/51115093
tags question: http://stackoverflow.com/q/51130933
tags question: http://stackoverflow.com/q/51084074
tags question: http://stackoverflow.com/q/51045519
tags question: http://stackoverflow.com/q/51119584
type: Tag
tags question: http://stackoverflow.com/q/51069334
tags question: http://stackoverflow.com/q/51137946
tags question: http://stackoverflow.com/q/51047179
tags question: http://stackoverflow.com/q/51148214
tags question: http://stackoverflow.com/q/51091885

http://stackoverflow.com/a/51035702
has comment: http://stackoverflow.com/comment/89065262
has comment: http://stackoverflow.com/comment/89063364
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89066086
answers question: http://stackoverflow.com/q/51035654
has comment: http://stackoverflow.com/comment/89063188
has comment: http://stackoverflow.com/comment/89065889
type: Answer
has comment: http://stackoverflow.com/comment/89066146
has comment: http://stackoverflow.com/comment/89065720
score: 2
has comment: http://stackoverflow.com/comment/89065236
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51035654
upvote count: 3
has body: You can use set.difference within a dict comprehension: In [29]: Result_one_two = {k: set(Dict_one[k]).difference(Dict_two[k]) for k in Dict_one} In [30]: Result_one_two Out[30]: {'A': {'a2', 'a3'}, 'B': set(), 'C': {'c4'}} In [31]: Result_two_one = {k: set(Dict_two[k]).difference(Dict_one[k]) for k in Dict_one} In [32]: Result_two_one Out[32]: {'A': set(), 'B': set(), 'C': {'c5'}} It's better to preserve the values as set at the first place tho. In that case you won't need to call the set for each value. Also note that if you're using Python-3.6+ since dictionaries in these versions are insertion ordered the output will be as expected, otherwise you should use an OrderedDict to keep track of orders. But if the performance is not an issue here and/or you're dealing with a short data set you can just use a list comprehension as is explained in other answers. Also, as mentioned in comments, if the order of values is important for you in order to take advantage of set operations and yet keep the order you can use a custom ordered set like what's proposed here https://stackoverflow.com/a/10006674/2867928 by Raymond Hettinger.

http://stackoverflow.com/q/51103944
has comment: http://stackoverflow.com/comment/89196444
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89198134
has answer: http://stackoverflow.com/a/51105615
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/63173137
has title: Display list of Python PIL.Image.Image as grid of images in Jupyter Notebook
has comment: http://stackoverflow.com/comment/89196452
answer count: 2
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
linked to: http://stackoverflow.com/q/47508168
has body: I have a Python list of PIL.Image.Image objects called all_images like so: [&lt;PIL.Image.Image image mode=RGB size=192x256 at 0x10855CF8&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x1053AE10&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x106445C0&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x10644E48&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x10644BE0&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x10644C18&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x106447F0&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x146D32B0&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x146D37F0&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x146D3EB8&gt;, &lt;PIL.Image.Image image mode=RGB size=192x256 at 0x146D3668&gt;] I would like to display them all in a nice-looking grid as in this tutorial. In the tutorial he just saves the images to disk; I would like to display them in a Jupyter Notebook. When I do Image.open(all_images[0]) it's opening up in Photoshop for some reason. I also tried from IPython.display import Image Image(all_images[0]) but PIL.Image.Image is an invalid input.
type: UnansweredQuestion
score: 5
tagged with: python

http://stackoverflow.com/q/51118939
has answer: http://stackoverflow.com/a/51122331
has body: I'm playing with pygame and I'm making a memory game. In my memory game I need to have a small Menu on the middle-bottom of the screen and the player list on top of the screen. The game manager will output the message in the upper left corner of the screen. The playable board where the cards will be situated should be in the center of the screen with a small margin on the right and the left and about 200px from the top and the bottom.(e.g. if the screen width and height are 1200 x 800, the playable board should be from 2 to 1998 width and 200 to 600 height. I've made a screenshot of the idea I have: I've put up the idea of the scrollable board with the cards, although it's hardcoded for now, I mostly need the idea not the code since I just have a hard time figuring out how it should work. The playable board (game board on the screenshot), should be moved through the keyboard(so up, right, down, left arrows). The thing I want to do is to allow more cards than 4 in each column and 12 in each row, in a way that when there are more cards than the 12 x 4, the gameboard could be moved, but without exiting the red square marked on the screenshot(so it's a scrollable surface). I want to limit the scrollable area to a width of 1200 and height of 400 px's, but in a way that the area is scrollable only inside the red area. If that can't work or is planned otherwise, is there any way to register clicks differently? Let's say when I move the keys in a way that the Menu area is above the game board and the menu is clicked, I don't want the card under the Menu to be clicked as well. Is there any way to lock the content under the Menu? Adding the code sample below: from pygame import * import sys init() screen_width = 1200 screen_height = 800 screen = display.set_mode((screen_width, screen_height)) board_width = 2000 board_height = 1000 playable_board = Surface((board_width, board_height)) playable_board = playable_board.convert() screen.fill((255, 255, 255)) #draw.rect(playable_bo…
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/51122331
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: pygame-surface
has title: Pygame - locking the scroll of a surface area to a limited amount

http://stackoverflow.com/comment/89121326
type: Comment
type: QuestionComment
has text: It depends what do you mean by *turn the sql into a db*. If *.sql is an export copy of a database i.e. list of SQL commands required to create copy of that database, then what you have to do is to run SQLite prompt, execute all commands from that copy and save database in SQLite format. Then you can connect to this newly created file using python sqlite lib. On the other hand, just changing the extension of file is definatelly not enough.
score: 0
comment on: http://stackoverflow.com/q/51065457

http://stackoverflow.com/comment/89076602
comment on: http://stackoverflow.com/q/51041562
score: 0
has text: After fixing imports I have the exact same behaviour @kristaps described
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51134570
type: Question
answer count: 1
tagged with: python-2.7
score: 0
has title: Add Model Attribute to an instance if it doesn't have one
tagged with: model
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51146861
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89259562
has body: i've recently added a optional costs Model option to Estimate creation(finance). Now that, when i'm trying to edit statement, the statements created after the optional costs updation, updates successfully. but the previous statements that doesn't have the optional costs model attribute fails on updating. this is what i've tried if hasattr(instance,"optional_amount"): optional_estimate_amounts = optional_estimate_amounts_formset.save(commit=False) for f in optional_estimate_amounts: f.estimate = instance f.save() for obj in optional_estimate_amounts_formset.deleted_objects: obj.delete() else: for optional_estimate_amounts in optional_estimate_amounts_formset: optional_amount_description = optional_estimate_amounts[ 'optional_amount_description'] optional_amount = optional_estimate_amounts['optional_amount'] OptionalEstimateAmounts( estimate=data, optional_amount_description=optional_amount_description, optional_amount=optional_amount ).save() currently it throws type error. I'm wondering how to create a new optional amount model attribute to an existing estimate instance if it doesn't have one when trying to edit estimate?
has answer: http://stackoverflow.com/a/51146861

http://stackoverflow.com/a/51306836
score: 4
type: AcceptedAnswer
has body: As already pointed, Trumbowyg doesn't send the URL to backend if the user uploads the image using a URL. But if you really want to host the images on your own server, there's a way you can do that. When the user submits the form, you'll receive the content of the textarea in your backend. You can then read the content and look for &lt;img src="..."&gt; tag. At that point, you can check if the src value doesn't start with your S3 bucket hostname, you can download that image using urllib or requests library, save it to your bucket and replace the src value. Since the submitted data will be in HTML format, check out the excellent Beautiful Soup. It will make parsing HTML easy.
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51165569
accepted answer of: http://stackoverflow.com/q/51165569

http://stackoverflow.com/a/51018520
accepted answer of: http://stackoverflow.com/q/51018446
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: Campaigns data is dict type. format reference: line 36: data = { "recipients": object* { "list_id": string* }, "settings": object* { "subject_line": string*, "from_name": string*, "reply_to": string* }, "variate_settings": object* (Required if type is "variate") { "winner_criteria": string* (Must be one of "opens", "clicks", "total_revenue", or "manual") }, "rss_opts": object* (Required if type is "rss") { "feed_url": string*, "frequency": string* (Must be one of "daily", "weekly", or "monthly") }, "type": string* (Must be one of "regular", "plaintext", "rss", "variate", or "absplit") }
answers question: http://stackoverflow.com/q/51018446

http://stackoverflow.com/comment/89299509
type: QuestionComment
comment on: http://stackoverflow.com/q/51157776
type: Comment
score: 0
has text: mmh Honestly no. Can I use markdown in the description of the function like I posted? I don't want to make great changes...

http://stackoverflow.com/comment/89234621
score: 0
type: AnswerComment
has text: Remove the `$` within the group, and `?` are not nieeded. The correct expression would be: `^.*\[scrapy\.statscollectors] INFO: Dumping Scrapy stats: (\{.+\}).*$`
type: Comment
comment on: http://stackoverflow.com/a/51124437

http://stackoverflow.com/a/51097384
has body: Debugging and logging in an application are two different things. You should use the debugger when developing an application and resolving bugs (using breakpoints to see the state of the app, executing code step by step). Logging should be used throughout the app to see what the app is doing (if an error occured catching an exception and logging it, etc.). This helps you when you are not debugging it and you solved most of the bugs, but errors can always occur. When they do you can look at the logs and see the exceptions and behaviour of the app at the time of the crash.
answers question: http://stackoverflow.com/q/51097328
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/89183240
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51097328
has comment: http://stackoverflow.com/comment/89182993

http://stackoverflow.com/q/51063631
accepted answer: http://stackoverflow.com/a/51064466
tagged with: python
has body: I would want to create a neural network with Python and I have some problems with the estimator. First, I read some documentation about estimators specification, and I think I created my estimators type correctly: estimate_train = tf.estimator.EstimatorSpec(mode=tf.estimator.ModeKeys.TRAIN, loss=loss, train_op=train_op) estimate_test = tf.estimator.EstimatorSpec(mode=tf.estimator.ModeKeys.EVAL, loss=loss) But when I want to create the estimator that will be used to train my network: estimator_ = tf.estimator.Estimator(model_fn= estimate_train, model_dir="Path") There is the following error: TypeError Traceback (most recent call last) /usr/lib/python3.5/inspect.py in getfullargspec(func) 1088 skip_bound_arg=False, -&gt; 1089 sigcls=Signature) 1090 except Exception as ex: /usr/lib/python3.5/inspect.py in _signature_from_callable(obj, follow_wrapper_chains, skip_bound_arg, sigcls) 2155 if not callable(obj): -&gt; 2156 raise TypeError('{!r} is not a callable object'.format(obj)) 2157 TypeError: EstimatorSpec(mode='eval', predictions={}, loss=&lt;tf.Tensor 'mean_squared_error/value:0' shape=() dtype=float32&gt;, train_op=None, eval_metric_ops={}, export_outputs=None, training_chief_hooks=(), training_hooks=(), scaffold=&lt;tensorflow.python.training.monitored_session.Scaffold object at 0x7f9ddc083748&gt;, evaluation_hooks=(), prediction_hooks=()) is not a callable object The above exception was the direct cause of the following exception: TypeError Traceback (most recent call last) &lt;ipython-input-2-c86a69b4da46&gt; in &lt;module&gt;() 39 40 ---&gt; 41 estimatorn = tf.estimator.Estimator(model_fn= estimate_test, model_dir="/home/jabou/Bureau") /usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator.py in __init__(self, model_fn, model_dir, config, params, warm_start_from) 221 if model_fn is None: 222 raise ValueError('model_fn must be provided to Estimator.') --&gt; 223 _verify_model_fn_args(model_fn, params) 224 self._model_fn = model_fn 225 self.…
score: 0
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51064466
has title: How to create correctly an estimator with TensorFlow
type: AnsweredQuestion
tagged with: tensorflow-estimator
type: Question

http://stackoverflow.com/comment/89219732
comment on: http://stackoverflow.com/a/51114891
score: 0
type: AnswerComment
has text: What's the etiquette here? Do I edit my original post to show the code I ended up using?
type: Comment

http://stackoverflow.com/a/51154739
answers question: http://stackoverflow.com/q/51154062
score: 0
has comment: http://stackoverflow.com/comment/89300119
type: AcceptedAnswer
has body: According to the comments, this is the right way to go? def func(df): df = np.atleast_2d(df) cum_cf = df.cumsum(axis=1) ny = np.argmax(cum_cf &gt; 0, axis=1)-1 rows = np.arange(df.shape[0]) n = cum_cf[rows, ny] p = cum_cf[rows, ny+1] value = 1 + ny - (n/p) return value
type: Answer
accepted answer of: http://stackoverflow.com/q/51154062

http://stackoverflow.com/comment/89156781
has text: This [article](https://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/) is very useful
comment on: http://stackoverflow.com/q/51084036
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51065443
has body: I'm trying to use Networkx 2.1 and Plotly 2.7.0 to generate a graph of a minimum spanning tree using a distance matrix as input. I am using Python 2.7. The problem is that the edges of the nodes shown in the Plotly graph do not match the edgelist of the Networkx minimum spanning tree. The distance matrix (csv file) has this format: ST0_1,0,0,1109,1109,1091,1091,1125,1126,1126,1125,1127,1126,1127,1127,1125,1125,1125,1126,1126,1127,1127,1127,1127,1122,1130,1126,1127 ST0_2,0,0,1109,1109,1091,1091,1125,1126,1126,1125,1127,1126,1127,1127,1125,1125,1125,1126,1126,1127,1127,1127,1127,1122,1130,1126,1127 ST1_3,1109,1109,0,0,1107,1107,1047,1048,1048,1047,1049,1048,1049,1049,1049,1049,1049,1047,1049,1049,1047,1047,1047,1050,1050,1049,1049 ST1_4,1109,1109,0,0,1107,1107,1047,1048,1048,1047,1049,1048,1049,1049,1049,1049,1049,1047,1049,1049,1047,1047,1047,1050,1050,1049,1049 ST22_5,1091,1091,1107,1107,0,0,1100,1101,1101,1100,1102,1101,1102,1102,1101,1101,1101,1101,1100,1102,1101,1101,1102,1099,1103,1102,1102 ST22_6,1091,1091,1107,1107,0,0,1100,1101,1101,1100,1102,1101,1102,1102,1101,1101,1101,1101,1100,1102,1101,1101,1102,1099,1103,1102,1102 ST2,1125,1125,1047,1047,1100,1100,0,5,6,8,8,9,8,10,7,7,8,11,16,12,8,7,11,72,43,11,17 ST7,1126,1126,1048,1048,1101,1101,5,0,1,7,3,4,3,5,6,6,7,10,15,13,7,6,10,72,43,6,16 ST9,1126,1126,1048,1048,1101,1101,6,1,0,8,2,3,2,4,7,7,8,11,16,14,8,7,11,73,44,5,17 ST5,1125,1125,1047,1047,1100,1100,8,7,8,0,10,11,10,12,7,7,8,7,16,16,10,9,13,73,44,13,17 ST13,1127,1127,1049,1049,1102,1102,8,3,2,10,0,3,2,4,9,9,10,13,18,16,10,9,13,75,46,7,19 ST11,1126,1126,1048,1048,1101,1101,9,4,3,11,3,0,3,1,10,10,11,14,19,17,11,10,14,76,47,8,20 ST10,1127,1127,1049,1049,1102,1102,8,3,2,10,2,3,0,4,9,9,10,13,18,16,10,9,13,75,46,7,19 ST12,1127,1127,1049,1049,1102,1102,10,5,4,12,4,1,4,0,11,11,12,15,20,18,12,11,15,77,48,9,21 ST16_7,1125,1125,1049,1049,1101,1101,7,6,7,7,9,10,9,11,0,0,3,10,15,15,9,8,12,72,43,12,16 ST16_8,1125,1125,1049,1049,1101,1101,7,6,7,7,9,10,9,11,0,0,3,10,15,15,9…
has comment: http://stackoverflow.com/comment/89121725
has comment: http://stackoverflow.com/comment/89121515
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51073679
has comment: http://stackoverflow.com/comment/89121488
tagged with: plotly
has title: Networkx and Plotly edges do not match
tagged with: networkx
type: Question
has comment: http://stackoverflow.com/comment/89121944
score: 0
linked to: http://stackoverflow.com/q/45701184
answer count: 1

http://stackoverflow.com/comment/89221730
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51106463
has text: @Vic13 How do you want to assign them, because I can't seem to understand why and on what basis you're going to assign values to them, if you tell me, I will extend my code.

http://stackoverflow.com/comment/89141664
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51073909
has text: I cannot reproduce that specific issue. When I try with those values, I actually get a division by zero error. After throwing eval in a try-except block, it proceeds to produce ((6*6)+6), giving 42. I've updated the answer to contain cleaner code that handles those exceptions and can support an arbitrary number of inputs. I can only hope that it somehow fixes the issue since I can't reproduce it. Please let me know if it still does not work.
type: AnswerComment

http://stackoverflow.com/q/51127473
has title: Serializing a non django model with Django Rest Frame
downvote count: 0
answer count: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: serialization
accepted answer: http://stackoverflow.com/a/51128776
tagged with: django
tagged with: python
has body: I am trying to build a django model with DRF that either sends a object state payload after creation, or an error payload. When I try to do something similar, then I get the following error message: File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in &lt;listcomp&gt; self.child.to_representation(item) for item in iterable File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 510, in to_representation fields = self._readable_fields File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 376, in _readable_fields field for field in self.fields.values() File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/Users/user/projects/bowling-game/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 997, in get_fields serializer_class=self.__class__.__name__ AssertionError: Class ErrorSerializer missing "Meta" attribute My models are given below: class BaseModel(models.Model, object): # Encapsulates all error objects. errors= [] def add_error(self, error_object): """Appends the error to the list of errors.""" self.errors.append(error_object) class Meta: abstract = True app_label = 'game' class GameRegistration(BaseModel):…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51128776
score: 1
type: Question
upvote count: 1

http://stackoverflow.com/comment/89167673
type: Comment
type: QuestionComment
score: 1
has text: Is there a reason not to do: `@deprecates(A)` or conversely: `@deprecated_by(B)`
comment on: http://stackoverflow.com/q/51089327

http://stackoverflow.com/a/51141766
type: Answer
has body: The info you are trying to fetch seems to be populated dynamically using javascript and that's probably why you are not able to fetch it. So in order to get around this you can use selenium webdriver to fetch the dynamic content. This is how the code looks: import csv from bs4 import BeautifulSoup from selenium import webdriver output_file = open('bse.csv', 'w') with open("bselist.csv") as f: for row in csv.reader(f): for stock in row: url = "https://www.bseindia.com/stock-share-price/{}".format(stock) driver = webdriver.Chrome('/path/to/chromedriver') driver.get(url) html = driver.page_source soup = BeautifulSoup(html, "html.parser") div = soup.find_all('div', {"class": "newscripcotent5"})[0] outer_table = div.find_all('table')[0] inner_table = outer_table.findChildren("table")[0] rows = inner_table.findChildren("tr") for row in rows: cols = row.findChildren("td") if len(cols) < 2: continue output_file.write(stock + "," + cols[0].getText() + "," + cols[1].getText() + "\n") print(stock + " " + cols[0].getText() + " " + cols[1].getText()) f.close() Be sure to replace /path/to/chromedriver with the appropriate path to chromedriver. So assuming your bselist.csv contains: avanti-feeds-ltd/avanti/512573/ You'll get the following output: avanti-feeds-ltd/avanti/512573/ 52 Week High (adjusted) 999.00(13/11/2017) avanti-feeds-ltd/avanti/512573/ 52 Week Low (adjusted) 410.26(05/06/2018) avanti-feeds-ltd/avanti/512573/ 52 Week High (Unadjusted) 3,000.00(13/11/2017) avanti-feeds-ltd/avanti/512573/ 52 Week Low (Unadjusted) 507.00(02/07/2018) avanti-feeds-ltd/avanti/512573/ Month H/L 659.34/410.26 avanti-feeds-ltd/avanti/512573/ Week H/L 615.00/507.00 If you don't already have selenium and chromedriver, you'll need to install it first. I installed these like this on my mac os: sudo easy_install selenium sudo easy_install chromedriver You might find the following posts helpful: How to retrieve the values of dynamic html content using Python Python, error with web driver (Selenium…
has comment: http://stackoverflow.com/comment/89341958
has comment: http://stackoverflow.com/comment/89338912
has comment: http://stackoverflow.com/comment/89351360
has comment: http://stackoverflow.com/comment/89341915
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51108227
answers question: http://stackoverflow.com/q/51108227

http://stackoverflow.com/comment/89295596
comment on: http://stackoverflow.com/q/51155780
type: QuestionComment
score: 0
has text: would you help me and tell me what is the `position` input ? is that the `"position"` key in your json ? and could you tell me what is the expected output to debug this.
type: Comment

http://stackoverflow.com/q/51014954
score: 5
tagged with: nonetype
upvote count: 5
has comment: http://stackoverflow.com/comment/89022689
tagged with: typeerror
answer count: 2
has answer: http://stackoverflow.com/a/51017696
downvote count: 0
has title: Python: Concurrent.Futures Error [TypeError: 'NoneType' object is not callable]
favorite count: 0
accepted answer: http://stackoverflow.com/a/51017696
has answer: http://stackoverflow.com/a/72253440
tagged with: python-asyncio
has body: So I managed to get asyncio / the Google CSE API to work together.... When I run my code on PyCharm, I am able to print my results out. However, at the very end of the printed stuff is the error "TypeError: 'NoneType' object is not callable". I suspect it has something to do with my list and maybe the loop trying to search for another term even though I'm at the end of the list... Also.. this is my first question post so feel free to offer suggestions on how to ask questions better as well Thoughts? searchterms = ['cheese', 'hippos', 'whales', 'beluga'] async def sendQueries(queries, deposit=list()): with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( executor, searching(queries) ) ] for response in await asyncio.gather(*futures): deposit.append(response.json()) return deposit def running(): loop = asyncio.get_event_loop() loop.run_until_complete(loop.create_task(sendQueries(searchterms))) loop.close() print(running()) print(str(time.time() - x)) My error can be traced back to "for response in await asyncio.gather(*futures):" For your reference, searching(queries) is simply the function for my Google CSE API call.
tagged with: python
possible better answer: http://stackoverflow.com/a/72253440
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89050206
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51027966
has text: What data type does sum() produce? what data type does hex() expect for an input?

http://stackoverflow.com/comment/89073007
comment on: http://stackoverflow.com/q/51040899
score: 0
type: QuestionComment
type: Comment
has text: Why do you need a singleton? Just pass the object where it's needed. [Explicit is better than implicit](https://www.python.org/dev/peps/pep-0020/).

http://stackoverflow.com/q/51100921
type: Question
has answer: http://stackoverflow.com/a/51101212
has comment: http://stackoverflow.com/comment/89189895
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89189635
has comment: http://stackoverflow.com/comment/89189796
score: 0
tagged with: max
accepted answer: http://stackoverflow.com/a/51100964
has body: I wondered how to solve the following problem in pandas: I have a dataframe with a number of rows that have different values and would like to find out how often the highest value occurs per row. I have used df2 ['MAX_Value']=df2.max(axis=1) to get the highest value per row. This is an example of my dataframe: Col1 Col2 Col3 Col4 Col5 Col6 MAX_Value 0 5 6 6 6 3 6 Thank you!
answer count: 3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51101055
type: AnsweredQuestion
has title: How to find out how many times a max value occurs in pandas?
possible better answer: http://stackoverflow.com/a/51101055
has comment: http://stackoverflow.com/comment/89189825
has answer: http://stackoverflow.com/a/51100964

http://stackoverflow.com/comment/89257263
score: 0
type: Comment
type: QuestionComment
has text: did you calculate this with the second set of parameters or the first?
comment on: http://stackoverflow.com/q/51040853

http://stackoverflow.com/comment/89210562
type: AnswerComment
type: Comment
has text: Please explain what the error is and what you did to fix it in words. SO is a site not for fixing OP's immediate needs as much as for helping future visitors with similar problems.
comment on: http://stackoverflow.com/a/51111825
score: 0

http://stackoverflow.com/comment/89268852
score: 3
type: Comment
type: QuestionComment
has text: Randomly reading bytes will indeed not make things UTF-8. What is your actual goal, that you're trying to do that? If you want to step forward or backward some n code points, you'll probably need to scan the full bytes anyway (there might be a package doing that for you).
comment on: http://stackoverflow.com/q/51142314

http://stackoverflow.com/q/51044957
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89081174
accepted answer: http://stackoverflow.com/a/51045051
has comment: http://stackoverflow.com/comment/89081122
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/89081114
upvote count: 0
tagged with: arrays
answer count: 1
has title: python None object
has comment: http://stackoverflow.com/comment/89081150
favorite count: 0
has answer: http://stackoverflow.com/a/51045051
has body: could you please explain what do I get in python with this lines? What does this code creates? NP = 2 NB = 2 ND = 2 N = NP*NB*ND M = 2*N + NP*NB res = [[None] * 3] * (M) Thanks in advance!
score: -4

http://stackoverflow.com/a/51159990
type: Answer
has body: Just for fun, here's a one-liner using some of Python's functional tools. The key ingredients are functools.partial, itertools.chain.from_iterable, and operator.not_, all of which come from the Functional Programming Modules section of Python's standard library documentation. &gt;&gt;&gt; import functools, itertools, operator &gt;&gt;&gt; board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2] &gt;&gt;&gt; list(itertools.chain.from_iterable(map(functools.partial(sorted, key=operator.not_), zip(*[iter(board)]*4)))) [2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0] Most of the work here is in turning the linear representation of the board into a nested list-of-lists representation, and then turning it back again. Here it is step-by-step. First, turning the flat representation into a nested one: &gt;&gt;&gt; nested = list(zip(*[iter(board)]*4)) &gt;&gt;&gt; nested [(2, 4, 0, 2), (8, 4, 4, 8), (0, 2, 0, 0), (4, 0, 2, 2)] I've added that extra outer list call just to show the contents of the zip iterable. It's not necessary once all the steps are put together. Now sort each row with a suitable key to move the zeros to the right: &gt;&gt;&gt; sorted_nested = list(map(functools.partial(sorted, key=operator.not_), nested)) &gt;&gt;&gt; sorted_nested [[2, 4, 2, 0], [8, 4, 4, 8], [2, 0, 0, 0], [4, 2, 2, 0]] Again, the outer list call is unnecessary, and we'll lose it when we put everything together. A key point here is that Python's sorted function provides a stable sort, so the nonzero elements stay in the same order with respect to each other. Finally, flatten back into a list: &gt;&gt;&gt; list(itertools.chain.from_iterable(sorted_nested)) [2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0] Putting this all together, and removing the unnecessary inner conversions to list, you get the one liner at the top of this post. &gt;&gt;&gt; list(itertools.chain.from_iterable(map(functools.partial(sorted, key=operator.not_), zip(*[iter(board)]*4)))) [2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, …
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51159518

http://stackoverflow.com/comment/89028896
comment on: http://stackoverflow.com/a/51017434
has text: I have defined this path in settings but how can i use this in serializers.py?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51156014
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51153144
accepted answer of: http://stackoverflow.com/q/51153144
upvote count: 2
has body: When you use the auth API directly, the token issued comes in the X-Subject-Token header. Thus, to retrieve in your python example, you could access the response.headers dict like this: token = r.headers['X-Subject-Token'] More info about authentication in the Keystone v3 docs

http://stackoverflow.com/a/51035916
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51035431
downvote count: 0
type: Answer
has body: user308827, The code in your question seems to confuse keys and values and ignore the fact that your values are tuples. Here's a one liner using std libs and a dict comprehension that works in python 2,3: from collections import OrderedDict import math od = OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0)), (43, ('A4', float('Nan')))]) no_nans = OrderedDict({k:v for k, v in od.items() if not math.isnan(v[1])}) # OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0))])

http://stackoverflow.com/a/51135096
answers question: http://stackoverflow.com/q/51131821
has body: Like you say, the documentation does not seem to specify it clearly. Looking at the source of the 2D convolution kernel (conv_ops.cc), a comment explains: // Total padding on rows and cols is // Pr = (R' - 1) * S + (Kr - 1) * Dr + 1 - R // Pc = (C' - 1) * S + (Kc - 1) * Dc + 1 - C // where (R', C') are output dimensions, (R, C) are input dimensions, S // is stride, (Dr, Dc) are dilations, (Kr, Kc) are filter dimensions. // We pad Pr/2 on the left and Pr - Pr/2 on the right, Pc/2 on the top // and Pc - Pc/2 on the bottom. When Pr or Pc is odd, this means // we pad more on the right and bottom than on the top and left. So it seems you would get one extra padding at the right column and bottom row with even-sized kernels. We can look at one example: import tensorflow as tf input_ = tf.ones((1, 10, 10, 1), dtype=tf.float32) kernel = tf.ones((6, 6, 1, 1), dtype=tf.float32) conv = tf.nn.conv2d(input_, kernel, [1, 1, 1, 1], 'SAME') with tf.Session() as sess: print(sess.run(conv)[0, :, :, 0]) Output: [[16. 20. 24. 24. 24. 24. 24. 20. 16. 12.] [20. 25. 30. 30. 30. 30. 30. 25. 20. 15.] [24. 30. 36. 36. 36. 36. 36. 30. 24. 18.] [24. 30. 36. 36. 36. 36. 36. 30. 24. 18.] [24. 30. 36. 36. 36. 36. 36. 30. 24. 18.] [24. 30. 36. 36. 36. 36. 36. 30. 24. 18.] [24. 30. 36. 36. 36. 36. 36. 30. 24. 18.] [20. 25. 30. 30. 30. 30. 30. 25. 20. 15.] [16. 20. 24. 24. 24. 24. 24. 20. 16. 12.] [12. 15. 18. 18. 18. 18. 18. 15. 12. 9.]] Indeed, it does look like extra zeros are added to the right and bottom sides.
upvote count: 7
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51131821
score: 7

http://stackoverflow.com/comment/89303080
comment on: http://stackoverflow.com/q/51154228
has text: Could you kindly share what `prob._data[name]` and `prob._result[name]` look like for your data? (I'm familiar with xarray but not pyomo.)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51139683
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51136760
type: Answer
accepted answer of: http://stackoverflow.com/q/51136760
has body: I think that what you want, is to force it to Layout() on a RESIZE event. However, remember that these items will have a minimum size. Try this: import wx class MainTab(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.hardware = [] box = wx.StaticBox(self, wx.ID_ANY, "Appareil") lc = wx.ListCtrl(self, wx.ID_ANY, style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_VRULES) lc.InsertColumn(1, "Appareil de mesure") lc.InsertColumn(2, "Connecte") lc.InsertColumn(3, "ID") lc.InsertColumn(4, "Type") sizerleft = wx.StaticBoxSizer(box,wx.HORIZONTAL) sizerleft.Add(lc, 1, wx.ALL|wx.EXPAND, 5) box = wx.StaticBox(self, wx.ID_ANY, "Mesures") cb = wx.Choicebook(self, wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="") sizerright = wx.StaticBoxSizer(box,wx.HORIZONTAL) sizerright.Add(cb, 1, wx.ALL|wx.EXPAND, 5) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(sizerleft, 1, wx.ALL|wx.EXPAND, 5) sizer.Add(sizerright, 1, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer) self.Bind(wx.EVT_SIZE, self.ReSize) def ReSize(self,event): self.Layout() if __name__ == '__main__': app = wx.App() frame = MainTab() frame.Show(True) app.MainLoop() I have had to hack it together as your code is in complete.

http://stackoverflow.com/comment/89293826
score: 1
comment on: http://stackoverflow.com/q/51155248
has text: look into `get_form_kwargs`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89317941
score: 0
type: AnswerComment
type: Comment
has text: This is awesome, well done. It works great! Do you happen to know how I would find the longest number of elements in my data so that I can automate the creation of column names? Ex. I would search all lists in all dicts and return 3. (If not I can always create a new question). Thanks again!
comment on: http://stackoverflow.com/a/51167257

http://stackoverflow.com/comment/89194086
comment on: http://stackoverflow.com/q/51098037
type: Comment
type: QuestionComment
has text: @Alasdair i tried it with no luck.
score: 0

http://stackoverflow.com/q/51068798
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/51069028
answer count: 4
downvote count: 4
linked to: http://stackoverflow.com/q/1247486
tagged with: list
linked to: http://stackoverflow.com/q/40307848
has comment: http://stackoverflow.com/comment/90553299
has comment: http://stackoverflow.com/comment/89127468
type: Question
has comment: http://stackoverflow.com/comment/89127478
has body: I have the following list in python a = ['[', '1', ',', ' ', '0', ',', ' ', '0', ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', '0', ',', ' ', '1', ',', ' ', '1', ',', ' ', '0', ']']. I want to extract integers form this, so that I can get a new list [1,0,0,0,0,1,0,1,1,0]. I am using python 3.x and I have tried the solution given in the link How to extract numbers from a list of strings? but unfortunately I am getting an empty list []. Can somebody help me?
has answer: http://stackoverflow.com/a/51071015
has title: Extracting integers from a list of special characters
has answer: http://stackoverflow.com/a/51068827
upvote count: 1
has answer: http://stackoverflow.com/a/51069584
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51023842
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89040725
has title: Understanding Python Multiprocessing Documentation
tagged with: multiprocessing
type: Question
has body: Trying to understand Python multiprocessing documents. I would put this on meta but I'm not sure whether it might be valuable to searchers later. I need some guidance as to how these examples relate to multiprocessing. Am I correct in thinking that multiprocessing is using multiple processes (and thus CPUs) in order to break down an iterable task and thus shorten its duration? from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() We are starting one process; but how do I start multiple to complete my task? Do I iterate through Process + start() lines? Yet there are no examples later in the documentation of for example: for x in range(5): p[x]=Process(target=f, args=('bob',)) p[x].start() p.join() Would that be the 'real life' implementation? Here is the 'Queue Example': from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get()) # prints "[42, None, 'hello']" p.join() But again, how is this multiprocessing? This is just starting a process and having it run objects in a queue? How do I make multiple processes start and run the objects in the queue? Finally for pool: from multiprocessing import Pool import time def f(x): return x*x if __name__ == '__main__': with Pool(processes=4) as pool: # start 4 worker processes result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow Are four processes doing 10x10 at once and it waits until all four come back or does just the one do this because we only gave the pool one argument? If the former: Wouldn't that be slower than just having one do it in the first place? What about memory? Do we hold process 1's result until process 4 returns in RAM or does it get printed? print(pool.map(f, range(10))) # prints "…
tagged with: documentation
score: 0
has comment: http://stackoverflow.com/comment/89042254
tagged with: python
has comment: http://stackoverflow.com/comment/89042829

http://stackoverflow.com/comment/89203188
type: QuestionComment
has text: updated the problem statement with df and expected df
comment on: http://stackoverflow.com/q/51107533
score: 0
type: Comment

http://stackoverflow.com/a/51171014
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51050948
has comment: http://stackoverflow.com/comment/111060754
score: 4
has body: The installation was set up according to Google recommendations and it contained no visible errors. The problem could not be reproduced on external environment (a similar Django setup worked fine), so we just came to a workaround, see it below (set PYTHONPATH). GAE requests installing third-party libraries into the lib/ directory, making it a poor man's virtual environment. Then lib/ is being added to a module search path by calling vendor.add('lib') in the appengine_config.py. That worked correctly in the author's setup, so GAE managed to import Django from lib/django/. Then this working config failed misteriously for importing MySQLdb, which was surely installed into the same lib/. During the investigation we have checked the idea if PYTHONPATH environment variable could affect anything. It did not, but setting it fixed the issue: export PYTHONPATH=/Users/username/Repositories/projectname/lib/ Note: avoid using relative directories in PATH-like environment variables (./lib in Erik's comment), that creates a security flaw.
answers question: http://stackoverflow.com/q/51050948
has comment: http://stackoverflow.com/comment/110820515
type: Answer
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89044261
comment on: http://stackoverflow.com/q/51025661
has text: A MongoDB document with several fields as "_id" or "orgId"
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/51016662
has body: The two sections you mention are different in that the first is about continuation lines that are followed by a block (such as a multiline def or if statement) while the second is about closing braces and parentheses on assignment and function calls. When starting a block, you wouldn't want to put the closing parenthesis at the beginning of the next line because going back to the original indentation conveys the end of the block. A few examples that clearly look odd: def long_function_foo( var_one, var_two, var_three, var_four ): print('This code really looks out of place') def long_function_bar( var_one, var_two ): print('and so does this one') PEP8 allows what they call vertical alignment, and many examples in various PEPs use this convention which has become an automated feature of Python IDEs: def long_function_name(var_one, var_two, var_three, var_four, var_five): """Documentation would go here, which makes it look better.""" print(var_one + var_two + var_three) But I personally avoid it. This is an opinion-based topic, but I don't like relying on alignment through a specific number of spaces. It's tedious to maintain and relies too much on IDE smart indents. I prefer this notation, which is allowed by PEP8 but doesn't seem as popular. Note the double-indent used for distinction from the function body: def long_function_name( alpha, bravo, charlie, delta, echo, foxtrot, hotel, indiana): """Documentation would go here.""" print(var_one + var_two + var_three) When it comes to function calls and assignments, PEP8 doesn't have a clear answer. One might indent the closing parenthesis, as a way to mimic how blocks end when the next instruction is less indented. foo = bar( 1, 2, 3 ) Vertical alignment is very popular and I'll admit it looks good, but again I don't want to force indentation size on future readers of my code so I avoid this: foo = bar(1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) Or one can also put the closing brace/parenthesis aligned to the left: foo =…
type: Answer
accepted answer of: http://stackoverflow.com/q/51016397
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/51016397
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51125808
has title: python.logging: Why does my non-basicConfig setting not work?
tagged with: python
answer count: 1
tagged with: logging
accepted answer: http://stackoverflow.com/a/51126605
upvote count: 3
has comment: http://stackoverflow.com/comment/89238061
linked to: http://stackoverflow.com/q/47422689
has body: I want to log to a single log file from main and all sub modules. The log messages send from a main file, where I define the logger, work as expected. But the ones send from a call to an imported function are missing. It is working if I use logging.basicConfig as in Example 1 below. But the second example which allows for more custom settings does not work. Any ideas why? # in the submodule I have this code import logging logger = logging.getLogger(__name__) EXAMPLE 1 - Working Here I create two handlers and just pass them to basicConfig: # definition of root looger in main module formatter = logging.Formatter(fmt="%(asctime)s %(name)s.%(levelname)s: %(message)s", datefmt="%Y.%m.%d %H:%M:%S") handler = logging.FileHandler('logger.log') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) handler2 = logging.StreamHandler(stream=None) handler2.setFormatter(formatter) handler2.setLevel(logging.DEBUG) logging.basicConfig(handlers=[handler, handler2], level=logging.DEBUG) logger = logging.getLogger(__name__) EXAMPLE 2 - Not working Here I create two handlers and addHandler() them to the root logger: # definition of root looger in main module logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.FileHandler('logger.log') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) #handler.setLevel(logging.ERROR) logger.addHandler(handler) handler = logging.StreamHandler(stream=None) handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.addHandler(handler)
has comment: http://stackoverflow.com/comment/89237394
has comment: http://stackoverflow.com/comment/89238025
tagged with: python-logging
has comment: http://stackoverflow.com/comment/89237767
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89238074
has answer: http://stackoverflow.com/a/51126605
downvote count: 0
has comment: http://stackoverflow.com/comment/89237813
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89237773
type: Question

http://stackoverflow.com/comment/89236364
has text: One, this is following Python 3 rules, not Python 2 (unless you're using `from __future__ import division` and not telling us). In any event, the main issue you're encountering is that using `/ 5` means the operands are converted to `float`, and your numerator is 58 bits of data. Python's `float` is based on C's `double`, which is typically IEE-754 binary64 floating point; binary64 floating point only has 52-53 bits worth of precision, so converting a 58 bit number to `float` is likely to lose precision.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51125676
type: QuestionComment

http://stackoverflow.com/q/51013308
has answer: http://stackoverflow.com/a/51013963
tagged with: selenium
has body: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from bs4 import BeautifulSoup import time url = "https://www.bungol.ca/" driver = webdriver.Firefox(executable_path ='/usr/local/bin/geckodriver') driver.get(url) #Select toronto by default driver.find_element_by_xpath("""/html/body/section/div[2]/div/div[1]/form/div/select/optgroup[1]/option[1]""").click() time.sleep(1) driver.find_element_by_xpath("""/html/body/section/div[2]/div/div[1]/form/div/button""").click() driver.find_element_by_xpath("""/html/body/nav/div[1]/ul[1]/li[3]/select/option[8]""").click() #select last 2 years driver.find_element_by_xpath("""//*[@id="activeListings"]""").click() #opening sold listing in that area driver.find_element_by_xpath("""/html/body/div[5]/i""").click() #closes property type slide driver.find_element_by_xpath("""//*[@id="navbarDropdown"]""").click() driver.find_element_by_xpath("""//*[@id="listViewToggle"]""").click() def data_collector(): hidden_next = driver.find_element_by_class_name("nextPaginate") #inputs in textbox inputElement = driver.find_element_by_id('navbarSearchAddressInput') inputElement.send_keys('M3B2B6') time.sleep(1) #inputElement.send_keys(Keys.ENTER) row_count = 3 table = driver.find_elements_by_css_selector("""#listViewTableBody""") while hidden_next.is_displayed(): #while there is a next page button to be pressed time.sleep(3) #delay for table refresh #row_count = len(driver.find_elements_by_css_selector("""html body#body div#listView.table-responsive table#listViewTable.table.table-hover.mb-0 tbody#listViewTableBody tr.mb-2""")) for row in range(row_count): #loop through the rows found #alternate row by changing the tr index driver.find_element_by_xpath("""/html/body/div[8]/table/tbody/tr[""" + str(row + 1) + """]/td[1]""").click() time.sleep(2) print(driver.find_element_by_css_selector("""#listingStatus""").text) #sold price #closes the pop up after getting the data…
type: Question
answer count: 2
score: 0
has title: Python Selenium: how to click on table content when changing table page
tagged with: python
has answer: http://stackoverflow.com/a/51015479
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/51036738
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51035444
answers question: http://stackoverflow.com/q/51035444
has body: According to this reference, IP address regex is \b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b. You want to avoid matching IP addresses that start with 10, 192.168 and a specific range of addresses that start with 172. Use \b(?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b See the regex demo Details \b - word boundary (?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.) - a negative lookahead that fails the match if RFC1918 addresses "markers" appear next: 10\. - 10. 192\.168\. - 192.168. 172\.(?:1[6-9]|2[0-9]|3[01])\. - 172., then 16 to 31 and . (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) - an octet regex (note the non-capturing group, you may use this pattern with re.findall in a convenient way to return all matches, no need to iterate the matches with re.finditer) (?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3} - 3 repetitions of a dot followed with an octet \b - word boundary Python demo: import re octet = r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' pattern=re.compile(r"\b(?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.){0}(?:\.{0}){{3}}\b".format(octet)) text = "10.11.0.0 and here are 192.168.0.0 and 192.168.0.2 145.12.24.45" print(pattern.findall(text)) # =&gt; ['145.12.24.45']
score: 5

http://stackoverflow.com/a/51120153
upvote count: 1
has body: As follows: if num % 2 == 0 and num &gt; 2: can be restated as - if your number is an even number and the number is greater than 2 it cannot be a prime number. The num % 2 returns the remainder of the expression. So 5 % 2 => 1 whereas 4 % 2 => 0. All even numbers will be divisible by 2 and therefore not prime - any number divisible by 2 that is less than 2 is not prime. for i in range(3, int(math.sqrt(num)) +1, 2): can be restated as picking number in a range that starts with 3 (the first integer >2), ending with the square root of the number your checking to see if it is a prime number (num) and stepping by 2. The stepping by 2 means that it will skip all even numbers when starting at 3. As a note (reference), any i that is more than the square root of num WILL have a factor that is between 3 and the square root of your number - so you can stop generating numbers at that point. if num % i == 0: can be restated similar to testing for even numbers. This will take the numbers from the range (the number i) and divide it into your number being tested. If it can go into the number with no remainder, then the number isn't prime. For both the if statements - if the number is evenly divided (results in a modulus of 0) then the code will return False meaning the number isn't prime. If the number is not dividable by an even number and is not dividable by an odd number between 3 and the square root of the number then the code will return True - - meaning the number is prime.
answers question: http://stackoverflow.com/q/51119965
downvote count: 0
has comment: http://stackoverflow.com/comment/89225937
type: Answer
has comment: http://stackoverflow.com/comment/89225918
score: 1

http://stackoverflow.com/q/51074466
has answer: http://stackoverflow.com/a/51074531
tagged with: pandas
has answer: http://stackoverflow.com/a/51074512
accepted answer: http://stackoverflow.com/a/51074512
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/51074531
downvote count: 0
tagged with: dataframe
has title: Set order of mulitindexed columns in pandas dataframe
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/41968732
has body: Is there a way to reorder specific levels within the columns index in a Pandas dataframe based on my personal preference (e.g., by an ordered list)? In [130]: frame = pd.DataFrame({ ...: ('TWO','thing1'):[1,2,3,4], ...: ('TWO','thing4'):[1,2,3,4], ...: ('DARK','thing1'):[0.1,0.2,1,2], ...: ('ANTS','thing3'):['a','e','i','o'], ...: ('ANTS','thing1'):['a','e','i','o']}) In [131]: frame Out[131]: ANTS DARK TWO thing1 thing3 thing1 thing1 thing4 0 a a 0.1 1 1 1 e e 0.2 2 2 2 i i 1.0 3 3 3 o o 2.0 4 4 My list is then based on a separately generated list. Important to note that I don't know either level 0 or level 1 index labels - they are variables. In [132]: sort_list = ['DARK', 'ANTS', 'TWO'] If I then try and pass this list in the context of frame = frame[sort_list] or .reindex(columns=sort_list) it throws Expected tuple, got str for obvious reasons. Here are the solutions that worked on a single level index. What I'd like to do is only sort on the top level and leave the second level as is. The final dataframe looking like this... DARK ANTS TWO thing1 thing1 thing3 thing1 thing4 0.1 a a 1 1 0.2 e e 2 2 1.0 i i 3 3 2.0 o o 4 4
upvote count: 2

http://stackoverflow.com/comment/89022146
score: 0
has text: Given on the way you've set up your class, replacing your `set` with a `dict` would work (and changing `add`, etc.), but the general approach still seems a bit odd.
comment on: http://stackoverflow.com/q/51014668
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51019490
tagged with: pyspark
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51019749
tagged with: apache-spark
linked to: http://stackoverflow.com/q/35258506
score: -2
has body: I need to convert the following scala statement to python: scala&gt; a.join(b, a("key") === b("key"), "left").select(a.columns.map(a(_)) : _*).show Having trouble with the : and _* I'm not familiar with Scala. I need to implement the solution in this answer in python: https://stackoverflow.com/a/43340781/2453657
tagged with: scala
downvote count: 2
tagged with: python
has title: Convert Spark Scala join statement to Python
accepted answer: http://stackoverflow.com/a/51019749
type: AnsweredQuestion
type: Question
tagged with: apache-spark-sql
upvote count: 0

http://stackoverflow.com/comment/89214482
type: Comment
comment on: http://stackoverflow.com/a/51113637
has text: That's perfect! I had earlier tried using a combination of annotate with Max, but that was definitely the wrong choice.This worked brilliantly. Thanks for the help!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89310403
type: QuestionComment
comment on: http://stackoverflow.com/q/51162060
score: 0
has text: An answer was provided below; you should give feedback on whether this solved your issue.
type: Comment

http://stackoverflow.com/comment/89163322
type: Comment
comment on: http://stackoverflow.com/a/51087383
score: 0
has text: Just tried it. I'm still getting a *exists* with the url *'www.isdfugpdohsiughsdopiughdsfoiguf.com*
type: AnswerComment

http://stackoverflow.com/comment/89167271
comment on: http://stackoverflow.com/a/51089402
has text: Thanks this is exactly what I'm looking for, but sadly when I ran it I got a _tkinter.TclError: couldn't recognize image data error.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89082412
type: QuestionComment
comment on: http://stackoverflow.com/q/51045578
has text: It's really not clear what "buffer" you refer to. Sure you can open eg. a file or network connection in Java and not close it to keep writing into it if that's what you mean.
score: 0
type: Comment

http://stackoverflow.com/q/51020916
has comment: http://stackoverflow.com/comment/89034495
has answer: http://stackoverflow.com/a/51021208
answer count: 1
has comment: http://stackoverflow.com/comment/89034519
favorite count: 0
downvote count: 1
tagged with: python
tagged with: discord
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89034846
has comment: http://stackoverflow.com/comment/89034841
type: Question
has comment: http://stackoverflow.com/comment/89040915
linked to: http://stackoverflow.com/q/919680
score: -1
has body: I am making a discord bot using python. I have a function def search(userName): # ... but the userName MAY contain spaces Eg. Enter userName: Me Head and I want the function to read bot arguments given and join them together so it forms "MeHead" Currently if I try to run my search(userName) function with two inputs it will just take the first input so Enter userName: Me Head will just run search("Me") and ignore anything after that first input
has title: Python function with variable number of arguments

http://stackoverflow.com/a/51160697
has comment: http://stackoverflow.com/comment/89305289
has comment: http://stackoverflow.com/comment/89305244
has comment: http://stackoverflow.com/comment/89305047
has comment: http://stackoverflow.com/comment/89305446
type: Answer
has comment: http://stackoverflow.com/comment/89305302
answers question: http://stackoverflow.com/q/51160386
has comment: http://stackoverflow.com/comment/89326941
has comment: http://stackoverflow.com/comment/89304885
has comment: http://stackoverflow.com/comment/89326969
has body: torch.tensor() expects a sequence or array_like to create a tensor whereas torch.Tensor() class can create a tensor with just shape information. Here's the signature of torch.tensor(): Docstring: tensor(data, dtype=None, device=None, requires_grad=False) -> Tensor Constructs a tensor with :attr:data. Args: data (array_like): Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types. dtype (:class:torch.dtype, optional): the desired data type of returned tensor. Regarding the RuntimeError: I cannot reproduce the error in Linux distros. Printing the tensor works perfectly fine from ipython terminal. Taking a closer look at the error, this seems to be a problem only in Windows OS. As mentioned in the comments, have a look at the issues/6339: Error when printing tensors containing large values
has comment: http://stackoverflow.com/comment/89305240
score: 0
has comment: http://stackoverflow.com/comment/89304860
has comment: http://stackoverflow.com/comment/89304994
has comment: http://stackoverflow.com/comment/89305059
has comment: http://stackoverflow.com/comment/89326997

http://stackoverflow.com/comment/89301547
comment on: http://stackoverflow.com/q/51156542
type: QuestionComment
type: Comment
has text: Why not just place the `MyClass.py` one level up in the `project` dir?
score: 0

http://stackoverflow.com/q/51146964
answer count: 1
has body: In my machine python 2.7.15 is auto updated from 2.7.14. When to try to launch Ride.py it throws an error wxPython not found. You need to install wxPython 2.8.12.1 or 3.0.2 or newer with Unicode support to run RIDE. wxPython can be downloaded from http://sourceforge.net/projects/wxpython/files/wxPython/ Although is wxpython 2.8.12.1 installed its doesn't recognize it. can anyone help out how can I over come this issue. I have Ride 2.0a1. should I downgrade ride or how can I fix this issue.
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89302671
has title: Unable to launch RIDE.py after python updated to 2.7.15 version
type: UnansweredQuestion
tagged with: selenium
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/89315015
type: Question
tagged with: robotframework
has answer: http://stackoverflow.com/a/51181602
upvote count: 0

http://stackoverflow.com/comment/89301265
type: QuestionComment
has text: @Two-Bit Alchemist no
score: 0
comment on: http://stackoverflow.com/q/51158872
type: Comment

http://stackoverflow.com/comment/89024908
score: 0
comment on: http://stackoverflow.com/a/51015525
type: Comment
has text: What version of Python are you in? I'm using 3.6 and it works for me.
type: AnswerComment

http://stackoverflow.com/a/51014253
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51014044
type: Answer
answers question: http://stackoverflow.com/q/51014044
has comment: http://stackoverflow.com/comment/89021447
downvote count: 0
score: 1
has body: You have a mismatch in what the model predicts, currently 3D, and what the target is, 2D. You have 2 options: Apply Flatten and remove TimeDistributed which means the model will predict based on the entire sequence. Remove return_sequences=True from last LSTM to let the LSTM compress the sequence and again remove TimeDistributed. This way the model will predict based on the last LSTM output not the sequences. I would prefer the second option given the size of the sequence and the number of hidden units you have. Option one will create a very large kernel for the Dense layer if you just flatten the sequence, i.e. too many parameters.

http://stackoverflow.com/a/51164736
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51164466
score: 0
accepted answer of: http://stackoverflow.com/q/51164466
has comment: http://stackoverflow.com/comment/89453717
type: Answer
has comment: http://stackoverflow.com/comment/89453779
has comment: http://stackoverflow.com/comment/89453763
has body: One possible solution is to use QTableViews with a model and a QSortFilterProxyModel, so when you order the QTableView you will be ordering the model, which will notify the other QTableView. This solution saves resources since it orders only one element: the model. from PyQt4 import QtCore, QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) model = QtGui.QStandardItemModel() proxy = QtGui.QSortFilterProxyModel() proxy.setSourceModel(model) table1 = QtGui.QTableView() table1.setModel(proxy) table1.setSortingEnabled(True) table2 = QtGui.QTableView() table2.setModel(proxy) for i in range(100): for j, w in enumerate([QtGui.QLineEdit, QtGui.QPushButton, QtGui.QCheckBox]): text = "{}-{}".format(i,j) it = QtGui.QStandardItem() if j == 0: it.setText(text) model.setItem(i, j, it) ix = model.indexFromItem(it) widget = w(text) table2.setIndexWidget(proxy.mapFromSource(ix), widget) for i in range(1, proxy.columnCount()): table1.setColumnHidden(i, True) lay = QtGui.QVBoxLayout(self) splitter = QtGui.QSplitter() splitter.addWidget(table1) splitter.addWidget(table2) lay.addWidget(splitter) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())

http://stackoverflow.com/q/51083210
tagged with: python-multiprocessing
type: Question
tagged with: python-import
answer count: 2
has answer: http://stackoverflow.com/a/51083991
score: 0
has body: I'm trying to import mymodule.py in the constructor of C class in order each new instance of the C class to use its own mymodule when the f method is called as a new process using multiprocessing module. Please review the code below: mymodule.py import random n = random.randint(0, 1000) mp_test.py import time import multiprocessing as mp import imp class C(object): def __init__(self, c='*'): self.mm=imp.load_module('mm', *imp.find_module('mymodule')) self.c = c def f(self): print self.c, id(self.mm), id(self.mm.n), self.mm.n def main(): p = [] for _ in range(2): p.append(mp.Process(target=C().f)) p[-1].start() time.sleep(1) print '' p0 = mp.Process(target=C(c='&gt;').f) p1 = mp.Process(target=C(c='&gt;').f) p0.start() p1.start() if __name__ == '__main__': main() After the execution of the mp_test.py the stdout result is: funk@linux:~/mp_test# python mp_test.py * 140679674677800 94828316092856 40 * 140679674677800 94828316835224 486 &gt; 140679674677800 94828317211688 763 &gt; 140679674677800 94828317211688 763 As expected the following piece of code creates to different instances of mymodule and consequently two different random numbers are generated: p = [] for _ in range(2): p.append(mp.Process(target=C().f)) p[-1].start() * 140679674677800 94828316092856 40 * 140679674677800 94828316835224 486 When the start() methods are called as follows mymodule is not imported twice and consequently the random numbers are the same... p0 = mp.Process(target=C(c='&gt;').f) p1 = mp.Process(target=C(c='&gt;').f) p0.start() p1.start() &gt; 140679674677800 94828317211688 763 &gt; 140679674677800 94828317211688 763 Your ideas please...! Edit zwer's suggestion resolves the issue: Code correction # ERROR self.mm=imp.load_module('mm', *imp.find_module('mymodule')) self.mm=imp.load_module('mm_' + str(uuid.uuid4()), *imp.find_module('mymodule')) Updated results funk@linux:~/mp_test# python -O mp_test.py * 139813126327944 94540189500648 396 * 139813126447184 94540189500504 491 &gt; 139813…
tagged with: python-module
tagged with: python
possible better answer: http://stackoverflow.com/a/51083714
has answer: http://stackoverflow.com/a/51083714
accepted answer: http://stackoverflow.com/a/51083991
type: AnsweredQuestion
has title: Cannot load the same module, in the same process, multiple times using imp.load_module

jupyter-notebook
tags question: http://stackoverflow.com/q/51121647
tags question: http://stackoverflow.com/q/51013935
tags question: http://stackoverflow.com/q/51090389
tags question: http://stackoverflow.com/q/51105475
tags question: http://stackoverflow.com/q/51099089
tags question: http://stackoverflow.com/q/51049779
tags question: http://stackoverflow.com/q/51127814
tags question: http://stackoverflow.com/q/51140216
tags question: http://stackoverflow.com/q/51112108
tags question: http://stackoverflow.com/q/51055302
tags question: http://stackoverflow.com/q/51071844
tags question: http://stackoverflow.com/q/51018536
tags question: http://stackoverflow.com/q/51101912
tags question: http://stackoverflow.com/q/51072843
tags question: http://stackoverflow.com/q/51137110
tags question: http://stackoverflow.com/q/51046034
tags question: http://stackoverflow.com/q/51098041
type: Tag
tags question: http://stackoverflow.com/q/51032159
tags question: http://stackoverflow.com/q/51095543
tags question: http://stackoverflow.com/q/51109345
tags question: http://stackoverflow.com/q/51068397
tags question: http://stackoverflow.com/q/51068987
tags question: http://stackoverflow.com/q/51096500
tags question: http://stackoverflow.com/q/51051333
tags question: http://stackoverflow.com/q/51144474
tags question: http://stackoverflow.com/q/51057058
tags question: http://stackoverflow.com/q/51101181
tags question: http://stackoverflow.com/q/51028241
tags question: http://stackoverflow.com/q/51111611
tags question: http://stackoverflow.com/q/51049923
tags question: http://stackoverflow.com/q/51102243
tags question: http://stackoverflow.com/q/51045264
tags question: http://stackoverflow.com/q/51015379
tags question: http://stackoverflow.com/q/51032382
tags question: http://stackoverflow.com/q/51162522
tags question: http://stackoverflow.com/q/51055788
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/51039271
tags question: http://stackoverflow.com/q/51161478
tags question: http://stackoverflow.com/q/51153744
tags question: http://stackoverflow.com/q/51067664
tags question: http://stackoverflow.com/q/51025112
tags question: http://stackoverflow.com/q/51065611
tags question: http://stackoverflow.com/q/51044411
tags question: http://stackoverflow.com/q/51103944

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/51106297
type: Tag

http://stackoverflow.com/comment/89190470
type: Comment
type: QuestionComment
score: 2
has text: `print(int(''.join(map(str, [1,2,3]))))` ?
comment on: http://stackoverflow.com/q/51101668

http://stackoverflow.com/q/51105216
has body: Let's say I have the following data sample: df = pd.DataFrame({'date':['2011-01-01','2011-01-02', '2011-01-03','2011-01-04','2011-01-05', '2011-01-06','2011-01-07','2011-01-08', '2011-01-09','2011-12-30','2011-12-31'], 'revenue':[5,3,2, 10,12,2, 1,0,6,10,12]}) # Let's format the date and add the week number and year df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d') df['week_number'] = df['date'].dt.week df['year'] = df['date'].dt.year df date revenue week_of_year year 0 2011-01-01 5 52 2011 1 2011-01-02 3 52 2011 2 2011-01-03 2 1 2011 3 2011-01-04 10 1 2011 4 2011-01-05 12 1 2011 5 2011-01-06 2 1 2011 6 2011-01-07 1 1 2011 7 2011-01-08 0 1 2011 8 2011-01-09 6 1 2011 9 2011-12-30 10 52 2011 10 2011-12-31 12 52 2011 I would like to compute the revenue per week, in order to later plot the results, and analyze the time series. The expected output would then be something like that : week revenue 0 1 8 1 2 33 2 52 22 I first thought of using the week number given by timestamp.week. However, I can't figure out how to deal with the ISO week number definition for the week preceeding week number 1. I am a bit confused, since grouping by week_number would in that case sum both the revenue at the very beginning of the year, and those at the end of the year.
has answer: http://stackoverflow.com/a/51105819
has comment: http://stackoverflow.com/comment/89197503
linked to: http://stackoverflow.com/q/44372048
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
tagged with: datetime
possible better answer: http://stackoverflow.com/a/51105914
tagged with: python
has comment: http://stackoverflow.com/comment/89198584
has title: Pandas groupby week given a datetime column
downvote count: 0
score: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89197604
type: Question
has answer: http://stackoverflow.com/a/51105811
accepted answer: http://stackoverflow.com/a/51105811
upvote count: 6
has answer: http://stackoverflow.com/a/51105914
favorite count: 0

http://stackoverflow.com/q/51020750
type: Question
tagged with: debugging
tagged with: console
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/70065363
favorite count: 0
tagged with: pycharm
has title: Error while using Debug Console: DeprecationWarning: The `use_readline` parameter is deprecated and ignored since IPython 6.0
has body: I have an issue with the Pycharm Debug console. Here's what I do step by step: I set a breakpoint somewhere in my code and when it stops at this breakpoint, I open the debug console as described here. This is prompted: >>> Then I try to do something basic like a = 1, but I get this error message (screenshot). As copy-paste: Traceback (most recent call last): File "C:\dev\PyCharm Community Edition 2018.1\helpers\pydev\pydevconsole.py", line 362, in get_interpreter interpreterInterface = getattr(__builtin__, 'interpreter') AttributeError: module 'builtins' has no attribute 'interpreter' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\dev\PyCharm Community Edition 2018.1\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 1443, in do_it result = pydevconsole.console_exec(self.thread_id, self.frame_id, self.expression, dbg) File "C:\dev\PyCharm Community Edition 2018.1\helpers\pydev\pydevconsole.py", line 467, in console_exec need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg) File "C:\dev\PyCharm Community Edition 2018.1\helpers\pydev\pydevconsole.py", line 383, in exec_code interpreterInterface = get_interpreter() File "C:\dev\PyCharm Community Edition 2018.1\helpers\pydev\pydevconsole.py", line 364, in get_interpreter When I start doing this for a whole new python file, everything works out well, but instead of the >>> what is prompted is In[2]: Where is the difference coming from and what can I do to use the debug console in the first case?
tagged with: python
type: AnsweredQuestion
score: 7
has answer: http://stackoverflow.com/a/51042551
accepted answer: http://stackoverflow.com/a/51042551
upvote count: 7
has answer: http://stackoverflow.com/a/70065363

http://stackoverflow.com/comment/89237250
type: QuestionComment
has text: Printing outputs this: C:\Users\Václav Parchomenko\AppData\Local\Programs\Python\Python37-32\lib\socket.py and my Python version is 3.7.0
score: 0
comment on: http://stackoverflow.com/q/51125740
type: Comment

http://stackoverflow.com/comment/89262505
type: Comment
comment on: http://stackoverflow.com/a/51137670
type: AnswerComment
has text: Lets try something. I think your issue might be in the way you handle the data. In the reading part you have a stream of bytes coming from the transmitter module(your MAC). Try to remove the bytes part in this (ser.write(bytes("hello world"))) and check if there is a change in the result in both modules. if the uart setup is correct then the issue is in the way you handle the data. Keep me updated. ALSO check the port on the raspi
score: 0

http://stackoverflow.com/comment/89386904
has text: I must have worked past that issue, as the same error was being produced from `shutil.rmtree(dir)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51088315

http://stackoverflow.com/a/51052575
has comment: http://stackoverflow.com/comment/89164272
accepted answer of: http://stackoverflow.com/q/51052452
score: 1
has comment: http://stackoverflow.com/comment/89096493
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89165407
has comment: http://stackoverflow.com/comment/89096337
has body: You've never altered the position of the sprite player. How do you expect it to move? All you've done is to change the value of your local variable playerx, but you've never pushed that change back into the sprite object. Start by adding the middle line below: playerx += x_change player.rect.center = (playerx, playery) all_sprites.update() See how that alters things? Can you take it from there?
has comment: http://stackoverflow.com/comment/89096261
type: Answer
has comment: http://stackoverflow.com/comment/89102542
answers question: http://stackoverflow.com/q/51052452
upvote count: 1

http://stackoverflow.com/comment/89027108
score: 0
comment on: http://stackoverflow.com/q/51016896
type: Comment
type: QuestionComment
has text: That's not what **name** is used for https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.fields.files.FieldFile.name

http://stackoverflow.com/a/51170136
score: 0
answers question: http://stackoverflow.com/q/51137646
has body: Try the following solutions: Change the default timeout of 10 seconds to request_timeout=n where n could be a number more than 10, ideally 30. Increase if error persists. Check your config/elasticsearch.yml to ensure that the http.proxy variable points to the right address. Try changing the port from 9200 to 443. Change use_ssl to True. Hope this helps.
type: Answer

http://stackoverflow.com/comment/89241524
score: 2
comment on: http://stackoverflow.com/q/51128226
has text: You tried to transpose a `Series`, which is just itself (1 dim). If you do `df["col"] = y_xxxx` you'll create a brand new column with y_xxx values. Now you'll have a 2-dim `df`that can be transposed
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51033886
has answer: http://stackoverflow.com/a/51232738
upvote count: 2
tagged with: tensorflow
type: Question
has title: tensorflow events file only written the first time by estimator
accepted answer: http://stackoverflow.com/a/51232738
downvote count: 0
answer count: 1
favorite count: 0
has body: # This script should train for one step and store the events file in model_dir: model_dir = '/tmp/test' shutil.rmtree(model_dir, ignore_errors=True) estimator = tf.estimator.Estimator( model_fn, params=params, model_dir=model_dir) estimator.train(input_fn=make_input_fn(None), steps=1) Now if I run ls /tmp/test I see this: [quant@home tmp]$ ls test/ checkpoint events.out.tfevents.1529978068.376da96eeba4 graph.pbtxt model.ckpt-1.data-00000-of-00001 model.ckpt-1.index model.ckpt-1.meta However, if I run the same script again with the same kernel (ie. in the same instance of my jupyter notebook), I see this: [quant@home tmp]$ ls test/ checkpoint graph.pbtxt model.ckpt-1.data-00000-of-00001 model.ckpt-1.index model.ckpt-1.meta If I change the name of my directory (e.g. to /tmp/test2) the events file is printed again, but only the first time. Clearly there is some state being captured somewhere, but where, and how do I reset my estimator completely?
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89069930

http://stackoverflow.com/q/51057447
has body: In one of my test functions I have the following piece of code: for key, expected_value in tools.config['expected_values']['devices']['specs'][device_spec].items(): if expected_value &gt; 0: try: value = data[device_spec][key] assert expected_value == value, pytest.fail('ERROR: Missing device using {}: {}.\nDetected: {}. Expected: {}\nEndpoint: {}'.format(device_spec, key, value, expected_value, endpoint), pytrace=False) except KeyError: pytest.fail('ERROR: There are no clients using {}: {}\nExpected: {}\nEndpoint: {}'.format(device_spec, key, expected_value, endpoint), pytrace=False) raise SystemExit(1) It might fail for two different reasons: Because there are not the expected number of devices using some expected specifications (e.g. 4 Linux are detected but 7 were expected). Because there are not devices at all using certain spec (e.g. there is no Windows device). The thing is that during the test runtime, both conditions might meet. For example, the config might be: expected_values: devices: specs: operating_systems: LINUX: 1 MACOS: 2 WINDOWS: 0 ANDROID: 1 IOS: 1 And assume there is only 1 MacOS device and there are not Android devices. The output should be: ERROR: Missing device using operating_system: MACOS. Detected: 1. Expected: 2 Endpoint: example.com/api/operating_system ERROR: There are no clients using operating_system: Android. Expected: 1. Endpoint: example.com/api/operating_system In fact, if I add a print(key), I can confirm that LINUX is displayed, MACOS is displayed, and after that, the code stops. It didn't read the other keys. However, only the first one is displayed and my guess is that the pytest.fail is breaking the for. So, how can I prevent this situation?
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51059488
possible better answer: http://stackoverflow.com/a/51057632
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51057632
type: Question
type: AnsweredQuestion
tagged with: pytest
has answer: http://stackoverflow.com/a/51059488
answer count: 2
has title: How to prevent this loop breaking?

http://stackoverflow.com/a/51087850
accepted answer of: http://stackoverflow.com/q/51087747
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51087747
has comment: http://stackoverflow.com/comment/89165138
type: Answer
has body: sim_scores.eval() is equivalent to doing: sess.run(sim_scores, feed_dict={}) so tensorflow is (rightfully) complaining that you didn't feed sim_input1 (or sim_input2) Instead store the result of the sess.run() call and print that, or give the feed_dict argument to the eval() call.
score: 2
upvote count: 2

http://stackoverflow.com/q/51045785
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89083157
has body: I am trying to predict lung cancer through risk factor wise. I confused whether I am getting correct value or not and What is the best way of visualizing SVM predicted data. Script import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('lung_cancer.csv') dataset.loc[dataset['GENDER'] == 'F', 'GENDER'] = 0 dataset.loc[dataset['GENDER'] == 'M', 'GENDER'] = 1 X = dataset.iloc[:, 0:14].values y = dataset.iloc[:, 15].values from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) from sklearn.svm import SVC C = 1.0 classifier = SVC(kernel='poly', C=C, decision_function_shape='ovr').fit(X, y) classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) from sklearn.metrics import classification_report, confusion_matrix cm = confusion_matrix(y_test,y_pred) class_report = classification_report(y_test,y_pred) Input file GENDER AGE SMOKING YELLOW_FINGERS ANXIETY PEER_PRESSURE CHRONIC DISEASE FATIGUE ALLERGY WHEEZING ALCOHOL CONSUMING COUGHING SHORTNESS OF BREATH SWALLOWING DIFFICULTY CHEST PAIN LUNG_CANCER F 59 0 0 0 1 0 1 0 1 0 1 1 0 1 0 F 63 0 1 0 0 0 0 0 1 0 1 1 0 0 0 F 75 0 1 0 0 1 1 1 1 0 1 1 0 0 1 M 69 0 1 1 0 0 1 0 1 1 1 1 1 1 1 M 74 1 0 0 0 1 1 1 0 0 0 1 1 1 1 M 63 1 1 1 0 0 0 0 0 1 0 0 1 1 0 Please suggest for the same. Thank you in advance
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89083001
type: Question
tagged with: matplotlib
has title: Visualize SVM predicted data in python

http://stackoverflow.com/q/51043952
has title: Catching "Access denied" error when setting an environment variable using subprocess.call
tagged with: python
has comment: http://stackoverflow.com/comment/89079246
has comment: http://stackoverflow.com/comment/89079153
has answer: http://stackoverflow.com/a/51044183
type: Question
has body: I was attempting to set an environment variable and it failed due to access denied, however, the try-except block did not catch this as an error. I could catch the exit code myself and then check if the exit code is different than 0, but I was hoping a more pythonic way is possible. This is what I have tried so perform: try: exit_code = subprocess.call(["SETX", "-m", "ENV_VAR", "Test"]) print 'exit_code: {}'.format(exit_code) # for debugging purposes except Exception: raise Exception("Could not set environment variable") And this was the result: ERROR: Access to the registry path is denied. exit_code: 1 Process finished with exit code 0 As you can see, the exit code that is being returned from subprocess.call is 1, indicating a failure, however, the entire Python process is exiting with exit code 0 and "raise Exception" is never called. What would be the best way to solve it?
answer count: 1
tagged with: python-2.7
score: 0
tagged with: method-call
has comment: http://stackoverflow.com/comment/89078930
tagged with: subprocess
type: UnansweredQuestion

http://stackoverflow.com/q/51102237
has answer: http://stackoverflow.com/a/51102626
tagged with: python-requests
type: Question
score: 0
has title: How to save output of my python script as a CSV file?
has comment: http://stackoverflow.com/comment/89192300
has comment: http://stackoverflow.com/comment/89192309
has comment: http://stackoverflow.com/comment/89192157
answer count: 1
has comment: http://stackoverflow.com/comment/89191794
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89192008
tagged with: python
has body: Having a bit of an issue trying to figure out how to save the output of my python script as a CSV. When I run this script, the file does not appear in the location that i need in order to access it. Any suggestions? import pandas as pd import os folder_path = os.path.join("T:", "04. Testing","3. Wear Testing","TESTS","CKUW","180604 OP STRAPLESS","Survey Response Data") mapping_path = os.path.join(folder_path + r'\Survey_MappingTable Strapless.xlsx') # Read mapping table mapping = pd.ExcelFile(mapping_path) mapping.sheet_names # ['SurveyInfo', 'Question Mapping', 'Answer Mapping'] # Transform sheets to 3 tables (surveyinfo, Q_mapping, A_mapping) surveyinfo = mapping.parse("SurveyInfo") Q_mapping = mapping.parse("Question Mapping", skiprows = 2) A_mapping = mapping.parse("Answer Mapping", skiprows = 3) # Get input file name and read the data. Table name is df. input_file_name = surveyinfo.loc[surveyinfo['Parameter Name']=='Input File Name','Value'].to_string(index=False) path = os.path.join(r'T:\04. Testing\3. Wear Testing\TESTS\CKUW\180604 OP STRAPLESS\Survey Response Data',input_file_name) df = pd.read_csv(path,header=None,engine='python') # ,encoding='utf-8' Tried this as a way to fix but it didn't work # Fill in previous colunmn names if blank, using the preceeding header df.iloc[0] = df.iloc[0].fillna(method='ffill') # Read the count of columns n_col = len(df.iloc[0]) n_respondent = len(df)-2 c_name = [] for i in range(n_col): # Multiple columns; each columns with differnt single answer. and the question text is to combine the category ex. support, comfort, are both in the satisfaction category etc. # If it's satisfaction question, concatenate first row and second row if "satisfaction" in df.iloc[0][i]: c_name.append(df.iloc[0][i]+df.iloc[1][i]) elif "functionality" in df.iloc[0][i]: c_name.append(df.iloc[0][i]+df.iloc[1][i]) elif ("shape" in df.iloc[0][i]) and ("please specify" in df.iloc[1][i]): c_name.append(df.iloc[0][i]+df.iloc[1][i]) elif ("room in the cup"…
has comment: http://stackoverflow.com/comment/89191875

http://stackoverflow.com/comment/89210170
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51111216
has text: It could be that `matplotlib` is using different backends in the two cases you've mentioned. Can you try running it without `plt.axis('tight')` in PyCharm.?

http://stackoverflow.com/a/51148178
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51087335
has body: I just resolved this issue by avoiding feed_dict and moving to Datset API: https://www.tensorflow.org/programmers_guide/datasets

http://stackoverflow.com/q/51060212
downvote count: 1
has comment: http://stackoverflow.com/comment/89112259
has answer: http://stackoverflow.com/a/51061195
type: Question
score: -1
has body: I'm using BeautifulSoup for a while and I've hadn't had much problems. But now I'm trying to scrape from a site that gives me some problem. My code is this: preSoup = requests.get('https://www.betbrain.com/football/world/') print(currUrl) soup = BeautifulSoup(preSoup.content,"lxml") print(soup) the content I get seems to be some sort of script and/or api they're connected to, but not the real content of the webpage I see in the browser. I cant reach the games for example. Does anyone knows a way around it? Thank you
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51061195
favorite count: 0
tagged with: beautifulsoup
has title: BeautifulSoup - Cant get the content of the page
tagged with: python
linked to: http://stackoverflow.com/q/2148493
type: AnsweredQuestion
tagged with: web-scraping

http://stackoverflow.com/comment/89287797
score: 0
has text: I added the whole views.py file, check the code if this will help to find why this error happen.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51151660

http://stackoverflow.com/q/51152402
has answer: http://stackoverflow.com/a/51153033
tagged with: python
has title: Improving 10-to-8bit-conversion performance
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89293056
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89290932
type: Question
has answer: http://stackoverflow.com/a/51152922
has comment: http://stackoverflow.com/comment/89292669
tagged with: performance
has body: I have greyscale image file with 10 bit data. The 10 bit are saved over 2 bytes, low-bit aligned (the 10 bit Value 0b10 0000 1111 is saved as 0x020F. I want to convert this to 8bit, keeping the most significant byte. def convert_10bitTo8Bit(tenBitData): output_size = int(len(tenBitData) / 2) eightBitData = bytearray(output_size) for i in range(output_size): lowbyte, highbyte = tenBitData[i * 2 + 1], tenBitData[i * 2] value = (highbyte &lt;&lt; 8) + lowbyte value = (value &gt;&gt; 2) &amp; 0xff eightBitData[i] = value return eightBitData This works, but is pretty slow: For a 3MB Image it takes around 0.5 seconds on my dev machine and >8 seconds on the device it's intended to run on (ARM System, similar performance to a PI). I tried to profile it to find the bottleneck, but cProfile just reports builtins.exec as the most time consuming function. $ python3 ImageTools.py 5 function calls in 8.560 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 8.560 8.560 &lt;string&gt;:1(&lt;module&gt;) 1 8.559 8.559 8.559 8.559 ImageTools.py:11(convert_10bitTo8Bit) 1 0.000 0.000 8.560 8.560 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {built-in method builtins.len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} How can I improve the performance?
has comment: http://stackoverflow.com/comment/89289227
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51092737
upvote count: 10
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51092966
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/45473896
has answer: http://stackoverflow.com/a/51093923
favorite count: 0
answer count: 3
has title: Vectorized assignment in Numpy
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51092852
has comment: http://stackoverflow.com/comment/89173900
has body: Let's assume I have a large 2D numpy array, e.g. 1000x1000 elements. I also have two 1D integer arrays of length L, and a float 1D arrray of the same length. If I want to simply assign floats to different positions in the original array according to integer array, I could write: mat = np.zeros((1000,1000)) int1 = np.random.randint(0,999,size=(50000,)) int2 = np.random.randint(0,999,size=(50000,)) f = np.random.rand(50000) mat[int1,int2] = f But if there were collisions i.e. multiple floats corresponding to single location, all but the last would be overwritten. Is there a way to somehow aggregate all the collisions, e.g. mean or median of all the floats falling at the same location? I would like to take advantage of vectorization and hopefully avoid interpreter loops. Thanks!
has comment: http://stackoverflow.com/comment/89173863
score: 10

http://stackoverflow.com/comment/89104817
has text: @U9-Forward it return the value of the key which is larger than score but the smallest.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51057028

http://stackoverflow.com/a/51103885
has body: You don't need to load the Anaconda Command Prompt to install packages. Even when installing a local package with conda it will check for the packages existence in the default channels. So not having an internet connection is problematic with conda. You are correct that pip is the way to go for local packages. You simply need to run: pip install /path/to/your/pacakage.tar.gz Obviously you should ensure that the environment you want to install the package in is currently activated before installing with pip. e.g. conda activate some_env
answers question: http://stackoverflow.com/q/51097380
score: 0
has comment: http://stackoverflow.com/comment/89195440
has comment: http://stackoverflow.com/comment/89195117
has comment: http://stackoverflow.com/comment/89195601
type: Answer
has comment: http://stackoverflow.com/comment/89195726
has comment: http://stackoverflow.com/comment/89195488

http://stackoverflow.com/a/51093208
has body: If your variable user_settings is a dictionary, you could use this to print only not empty items, but its almost the same thing as @leelum1 answer {% for key,value in user_settings.items %} {% if value %} {{ value }} {% endif %} {% endfor %}
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51092139
has comment: http://stackoverflow.com/comment/89175557

http://stackoverflow.com/q/51130278
has body: I have a data set that looks approximately like this: data_set = pd.DataFrame([ {'img_type': 'bias', 'CCD-TEMP': -10, 'explen': 0, 'mean': 1023.4234}, {'img_type': 'bias', 'CCD-TEMP': -10, 'explen': 0, 'mean': 1024.4334}, {'img_type': 'bias', 'CCD-TEMP': -15, 'explen': 0, 'mean': 1022.2344}, {'img_type': 'bias', 'CCD-TEMP': -15, 'explen': 0, 'mean': 1021.1031}, {'img_type': 'dark', 'CCD-TEMP': -10, 'explen': 30, 'mean': 1025.9959}, {'img_type': 'dark', 'CCD-TEMP': -10, 'explen': 30, 'mean': 1023.3434}, {'img_type': 'dark', 'CCD-TEMP': -10, 'explen': 60, 'mean': 1020.1234}, {'img_type': 'dark', 'CCD-TEMP': -10, 'explen': 60, 'mean': 1022.4234}, {'img_type': 'dark', 'CCD-TEMP': -15, 'explen': 30, 'mean': 1025.9959}, {'img_type': 'dark', 'CCD-TEMP': -15, 'explen': 30, 'mean': 1023.3434}, {'img_type': 'dark', 'CCD-TEMP': -15, 'explen': 60, 'mean': 1020.1234}, {'img_type': 'dark', 'CCD-TEMP': -15, 'explen': 60, 'mean': 1022.4234}, ]) What I am trying to do is isolate the img_type='bias' rows, group them by CCD-TEMP, and calculate the mean() of 'mean' for each group. This seems to do that trick: &gt;&gt;&gt; data_set[data_set['img_type'].isin(['bias'])].groupby('CCD-TEMP')['mean'].mean() ... CCD-TEMP -15 1021.66875 -10 1023.92840 Name: mean, dtype: float64 What I need to do now is apply those values to a new column called 'Offset' to a group of all rows based on CCD-TEMP. I've tried a few things so far, the last attempt looking as follows: &gt;&gt;&gt; data_set['Offset'] = data_set[data_set['img_type'].isin(['bias'])].groupby('CCD-TEMP')['mean'].mean() &gt;&gt;&gt; data_set CCD-TEMP explen img_type mean Offset 0 -10 0 bias 1023.4234 NaN 1 -10 0 bias 1024.4334 NaN 2 -15 0 bias 1022.2344 NaN 3 -15 0 bias 1021.1031 NaN 4 -10 30 dark 1025.9959 NaN 5 -10 30 dark 1023.3434 NaN 6 -10 60 dark 1020.1234 NaN 7 -10 60 dark 1022.4234 NaN 8 -15 30 dark 1025.9959 NaN 9 -15 30 dark 1023.3434 NaN 10 -15 60 dark 1020.1234 NaN 11 -15 60 dark 1022.4234 NaN Obviously NaN is not what I'm afte…
has answer: http://stackoverflow.com/a/51130351
tagged with: python
has comment: http://stackoverflow.com/comment/89261303
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51130351
has comment: http://stackoverflow.com/comment/89276748
has title: Assigning values to columns based on groups in pandas
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89222798
has text: If your code works without errors, you could ask on [codereview.se].
score: 0
comment on: http://stackoverflow.com/q/51118108
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89244423
type: AnswerComment
score: 0
type: Comment
has text: did you use the `&&` between the cd and the scrapy?
comment on: http://stackoverflow.com/a/51129668

http://stackoverflow.com/comment/89155271
type: Comment
comment on: http://stackoverflow.com/q/51082556
score: 1
type: QuestionComment
has text: You only create one figure and are then you're wondering why you only get one figure?

http://stackoverflow.com/comment/89200898
score: 0
has text: Do you need the email address inside the author tag?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51106848

http://stackoverflow.com/a/51016519
downvote count: 0
type: Answer
upvote count: 1
has body: Hope you're finding something like this one!! [{i+1,j} for i,j in enumerate(list(seq))] Results: [set([1, 'M']), set(['I', 2]), set([3, 'G']), set(['Q', 4]), set([5, 'F']), set([6, 'G']), set(['L', 7])]
score: 1
answers question: http://stackoverflow.com/q/51016482

http://stackoverflow.com/a/51146591
answers question: http://stackoverflow.com/q/51146522
upvote count: 1
has comment: http://stackoverflow.com/comment/89277226
has comment: http://stackoverflow.com/comment/89278119
type: Answer
downvote count: 0
score: 1
has body: Here's a one-line way of doing this: member_id="273493248051539968" [k for k, v in colors.items() if member_id in v['members']] Output: ['Blue']

http://stackoverflow.com/a/51030717
accepted answer of: http://stackoverflow.com/q/51022381
answers question: http://stackoverflow.com/q/51022381
type: Answer
has body: For the first step, you should convert your image to a binary image using the appropriate tools like cv2.cvtColor(), cv2.threshold(), cv2.bitwise_not(),... (depending on the image) - this means that your image will contain only black or white pixels. Example: Then you should find your contours (cv2.findContours) on the image and filter them out with size criterion (cv2.contourArea()) to eliminate other contours like the big pentagon in the middle of the image. Next step you should find the moments of each contour (cv2.moments()) so you will be able to get x and y coordinates of the center of the contour and put them in a list. (Be careful to append the right x and y coordinate together). After you have your points you can calculate the distance between all points (with the distance between two points formula - sqrt((x2-x1)^2+(y2-y1)^2)) Then you can use whatever logic you want to get the coordinates of points of shortest distance for every point (in the example below I zipped them in a list and made an array containing distance, x and y coordinates for every point). Example in code: import numpy as np import cv2 img = cv2.imread('points.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(gray,150,255,cv2.THRESH_BINARY) cv2.bitwise_not(threshold, threshold) contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) listx = [] listy=[] for cntr in range(0, len(contours)): cntr = contours[i] size = cv2.contourArea(cntr) if size < 1000: M = cv2.moments(cntr) cX = int(M["m10"] / (M["m00"] + 1e-5)) cY = int(M["m01"] / (M["m00"] + 1e-5)) listx.append(cX) listy.append(cY) listxy = list(zip(listx,listy)) listxy = np.array(listxy) for x1, y1 in listxy: distance = 0 secondx = [] secondy = [] dist_listappend = [] sort = [] for x2, y2 in listxy: if (x1, y1) == (x2, y2): pass else: distance = np.sqrt((x1-x2)**2 + (y1-y2)**2) secondx.append(x2) secondy.append(y2) dist_listappend.append(distance) secondxy = list(zip(dist_list…
upvote count: 9
score: 9
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51014859
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89024598
has comment: http://stackoverflow.com/comment/89023167
has body: The answer to your question is fairly simple: In the staticData.py file you can store your variables simply like this: a = 3 b = "Some text" In some other file, lets say main.py you can then import them: from staticData import a from staticData import b And then you can use them however you want. P.S If you want to change the value of those variables in one function and then preserve this value in other functions, you have two ways: Either import module and reference variables like this: import staticData staticData.a = 10 staticData.b = "changed the text" or you can use global (especially if referencing from a function)
accepted answer of: http://stackoverflow.com/q/51014504
answers question: http://stackoverflow.com/q/51014504
has comment: http://stackoverflow.com/comment/89041220
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89029307

http://stackoverflow.com/comment/89309450
comment on: http://stackoverflow.com/a/51162990
type: Comment
score: 2
has text: the requests library's get function has a `.json()` function. So you can use that instead. So instead of your second row: `print(response.json())`
type: AnswerComment

http://stackoverflow.com/q/51159132
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/89301739
tagged with: python
has body: I have build a swagger doc, generated the swagger client (python-flask with python2 support). I've built my code up, tested, happy with what I've got. Now I want to secure my API endpoints using https and Basic Auth. This is v2 of the Open Api Specification (OAS) so I'm setting up as follows (described https://swagger.io/docs/specification/2-0/authentication/basic-authentication/) swagger: "2.0" securityDefinitions: basicAuth: type: "basic" Whether I specify that my endpoint have individual security settings or whether I specify this at the root level in the YAML for all endpoints, it makes no difference. security: - basicAuth: [] I take my YAML, export to JSON, then run the following to rebuild the swagger_server code: java -jar swagger-codegen-cli-2.3.1.jar generate -l python-flask - DsupportPython2=true -i swagger.json -a "Authorization: Basic Base64encodedstring" What I'm expecting is for the controller or model code to validate that a basic auth header has been passed that matches the authrization specified in the generation code but I see no references anywhere. Not sure if I've just read this wrong or if there's an issue with the way I'm doing it or some of the options I'm using?
has answer: http://stackoverflow.com/a/51163843
accepted answer: http://stackoverflow.com/a/51163843
has comment: http://stackoverflow.com/comment/89309501
has title: Swagger Codegen Authorisation for Python-Flask
type: AnsweredQuestion
tagged with: openapi
tagged with: swagger
type: Question
answer count: 1

http://stackoverflow.com/q/51104326
favorite count: 0
has answer: http://stackoverflow.com/a/51104420
has comment: http://stackoverflow.com/comment/89197042
has comment: http://stackoverflow.com/comment/89196057
type: UnansweredQuestion
tagged with: pip
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89197841
score: 1
has comment: http://stackoverflow.com/comment/89197912
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89195886
has body: The operating system is Windows 10 64 bit. I tried to do the following: pip install matplotlib. Didn't work. Then I tried as it is written in https://matplotlib.org/users/installing.html#build-requirements: python -mpip install -U pip python -mpip install -U matplotlib Then somewhere I read that setuptools upgrade can resolve the problem. I tried it with: pip install --upgrade setuptools easy_install -U setuptools The response is always the same: Command "python setup.py egg_info" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pip-install-pqlhz7ux\matplotlib\ Can you help me? Python version is 3.7.0 BUILDING MATPLOTLIB matplotlib: yes[2.2.2] python: yes [3.7.0 (v3.7.0:1bf9cc5093, Jun 2 7 2018, 04:06:47) [MSC v.1914 32 bit (Intel)]] platform: yes [win32] REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] install_requires: yes [handled by setuptools] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] freetype: no [The C/C++ header for freetype (freetype2\ft2build.h) could not be found. You may need to install the development pack age.] png: no [The C/C++ header for png (png.h) could not be found. You may need to install the development package.] qhull: yes [pkg-config information for 'libqhull' could not be found. Using local copy.]
type: Question
has comment: http://stackoverflow.com/comment/89197981
downvote count: 0
answer count: 1
has title: Error while installing matplotlib Python

http://stackoverflow.com/comment/89193218
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51094317
type: AnswerComment
has text: print(a.hour) and print(a.minute) prints the hour and minute. You need to extract the hour and minute from the timestamp

http://stackoverflow.com/a/51024245
score: 3
has body: The entry widget is not capable of being expanded vertically. This is because there is already a widget designed for this and that is called Text(). For adding text to the text widget we can use insert() and you specify where with a 2 part index. The first part is the row and the 2nd is the column. For the row/line it starts at number 1 and for the index of that row it starts at zero. For example if you wish to insert something at the very first row/column you would do insert("1.0", "some data here"). Here is you code with the use of Text() instead. import re from tkinter import * window = Tk() window.minsize(width=300, height= 20) wr = [] def work(): x = e1.get("1.0", "end-1c") print(x) BigLetterSearcher = re.compile(r'\. .|\n') mo = BigLetterSearcher.findall(x) x = 1 y = 0 v = 0 z = "" wr = [] for i in mo: if i == '\n': x += 1 elif i != i.upper(): v = 1 if x != y: z = "Row", x wr.append(z) wr.append(i) y = x if v == 0: wr.append ("Congratulations none of your grammar was wrong!") l1.configure(text=wr) l1 = Label(window, text="example") e1 = Text(window, width=20, height=3) e1.insert("end", "Enter text here: ") b1 = Button(window, text="Work", command=work) leb = [l1, e1, b1] for all in leb: all.pack() window.mainloop()
has comment: http://stackoverflow.com/comment/89041366
accepted answer of: http://stackoverflow.com/q/51024135
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89041255
type: Answer
answers question: http://stackoverflow.com/q/51024135
upvote count: 3

http://stackoverflow.com/q/51013520
has comment: http://stackoverflow.com/comment/89019734
tagged with: dataframe
type: Question
answer count: 2
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51013565
favorite count: 0
has answer: http://stackoverflow.com/a/51013540
has body: I am seeking to loop the columns in a dataframe and when the column name meets a criteria create a new dataframe and/or add it to an existing dataframe. For exmaple - my current dataframe has the following column names: open high low IVV volume open high low EWH volume open high low INDY volume open high low EWG volume open high low ENZL volume I want a loop which will find IVV,EWH,INDY,EWG, and ENZL and add them to their own dataframe. I have tried the following: Indexlist = ['IVV', 'EWH', 'INDY', 'EWG', 'ENZL'] Attempt to drop the values columns: for column in data: print(column) if column != Indexlist: data.drop([column], axis=0)) Attempt to del the columns for column in data: print(column) if column != Indexlist: del data[column] Attempt to select the columns data_sample = data[column].isin(Indexlist) all these methods are throwing errors.
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Looping Pandas Column Names To Create New Data Frame
tagged with: indexing
score: 1

http://stackoverflow.com/q/51090632
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51090659
has title: Python - excel export
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89169605
downvote count: 0
tagged with: pandas
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89169598
possible better answer: http://stackoverflow.com/a/51090673
has body: I've got this code: import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.content,'lxml') table = soup.find_all('table')[0] df = pd.read_html(str(table)) writer = pd.ExcelWriter('test.xlsx',engine='xlsxwriter') workbook = writer.book df.to_excel(writer,sheet_name='quotations',startrow=0 , startcol=0) after running it, the following error shows up: AttributeError: 'list' object has no attribute 'to_excel' Can anybody help me?
tagged with: python
has answer: http://stackoverflow.com/a/51090673
has answer: http://stackoverflow.com/a/51090659

http://stackoverflow.com/comment/89066336
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51037132
has text: If that is the case why for some of the values it's working fine even though it less than `12`. Obviously it would be looking for something and then creating?
score: 0

http://stackoverflow.com/comment/89213124
type: QuestionComment
comment on: http://stackoverflow.com/q/51113317
has text: Can you add data sample and expected output?
score: 1
type: Comment

http://stackoverflow.com/comment/89132662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51070875
has text: would you mind telling the backend db server? Also what error are you getting?
score: 0

http://stackoverflow.com/q/51092155
has comment: http://stackoverflow.com/comment/89174428
score: 12
has comment: http://stackoverflow.com/comment/89172687
downvote count: 0
answer count: 1
favorite count: 0
has title: how to quit/close Anaconda Navigator
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/68190983
tagged with: anaconda
type: Question
has body: When I tried to launch Anaconda Navigator, the screen shows that I have Anaconda Navigator opened. But I couldn't find it on my task bar. The exact language is: There is an instance of Anaconda Navigator already running. I'm using Windows 10. How can I force Anaconda Navigator to quit and relaunch it. Thank you so much.
upvote count: 12

readonly
tag name: readonly
tags question: http://stackoverflow.com/q/51104120
type: Tag

http://stackoverflow.com/a/51032354
has body: scipy.stats.entropy computes the entropy of a discrete distribution. The values are expected to be probabilities, not probability densities. (In fact, if the sum of the values in the input is not 1, the values are scaled so the sum is 1. This is mentioned in the docstring.) If that is what you have (e.g. the 2-d array p holds the joint distribution probabilities of a bivariate discrete distribution) you can simply pass the flattened array to scipy.stats.entropy; e.g. entropy(p.ravel(), base=2). The function scipy.stats.entropy does not compute the same mathematical quantity as the entropy method of a scipy continuous distribution such as scipy.stats.multivariate_normal. The entropy method computes the differential entropy of the distribution. See the wikipedia article on differential entropy for a discussion of the difference between the discrete entropy computed by scipy.stats.entropy and the differential entropy computed by the entropy method of the scipy distributions.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51022380
accepted answer of: http://stackoverflow.com/q/51022380
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51093268
accepted answer: http://stackoverflow.com/a/51093350
has comment: http://stackoverflow.com/comment/89174806
tagged with: http://stackoverflow.com/tag/json
has body: @commands.command(pass_context=True) @checks.serverowner() async def change(self, ctx, change): channel = self.bot.get_channel('432738903221469186') change = ctx.message.clean_content[8:] now = datetime.now() count = len(self.changes.items()) + 1 self.changes[count] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change} dataIO.save_json('data/local/changes.json', self.changes) await self.bot.send_message(channel, bold("\N{SPARKLE} This change to the server was just made:") + box(change)) await self.bot.add_reaction(ctx.message, "\N{WHITE HEAVY CHECK MARK}") Here is changes.json: { "1" : { "change" : "TEST", "date" : "2018-06-29 01:07:37" } } Here's the full error: 2|cdb_laun | Traceback (most recent call last): 2|cdb_laun | File "lib/discord/ext/commands/core.py", line 50, in wrapped 2|cdb_laun | ret = yield from coro(*args, **kwargs) 2|cdb_laun | File "/root/craig/cdbot/cogs/local.py", line 73, in change 2|cdb_laun | dataIO.save_json('data/local/changes.json', self.changes) 2|cdb_laun | File "/root/craig/cdbot/cogs/utils/dataIO.py", line 20, in save_json 2|cdb_laun | self._save_json(tmp_file, data) 2|cdb_laun | File "/root/craig/cdbot/cogs/utils/dataIO.py", line 50, in _save_json 2|cdb_laun | json.dump(data, f, indent=4, sort_keys=True, separators=(",", " : ")) 2|cdb_laun | File "/usr/lib64/python3.5/json/__init__.py", line 178, in dump 2|cdb_laun | for chunk in iterable: 2|cdb_laun | File "/usr/lib64/python3.5/json/encoder.py", line 429, in _iterencode 2|cdb_laun | yield from _iterencode_dict(o, _current_indent_level) 2|cdb_laun | File "/usr/lib64/python3.5/json/encoder.py", line 352, in _iterencode_dict 2|cdb_laun | items = sorted(dct.items(), key=lambda kv: kv[0]) 2|cdb_laun | TypeError: unorderable types: str() &lt; int() I apologize for the vague title and question, I've just dealt with handling JSON quite often and I'm not understanding the error here. I'm not even seeing where strings and integers are being compared. My initial thought was that it h…
has comment: http://stackoverflow.com/comment/89174968
has comment: http://stackoverflow.com/comment/89174741
answer count: 2
has comment: http://stackoverflow.com/comment/89174732
downvote count: 0
has title: Why am I getting "TypeError: unorderable types: str() < int()" in this code?
has comment: http://stackoverflow.com/comment/89174687
possible better answer: http://stackoverflow.com/a/51093358
favorite count: 0
has answer: http://stackoverflow.com/a/51093358
tagged with: typeerror
has answer: http://stackoverflow.com/a/51093350
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89174745
has comment: http://stackoverflow.com/comment/89174779
upvote count: 1
has comment: http://stackoverflow.com/comment/89174686
type: Question

http://stackoverflow.com/comment/89133611
comment on: http://stackoverflow.com/q/51070495
score: 0
type: Comment
type: QuestionComment
has text: Okay, I will do so. Thank you.

http://stackoverflow.com/a/51069043
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51068907
has body: Solved with help by Konstantin and juanpa.arrivillaga's answers combined. Used import json not ijson test = json.loads(msg.payload.decode()) print([x.get('rssi') for x in test])
type: Answer
answers question: http://stackoverflow.com/q/51068907

http://stackoverflow.com/a/51028218
has body: lst = ['w', 'a', 's', 'x', 'v', 'q'] images = {key:key+".jpg" for key in lst} Output: {'a': 'a.jpg', 'q': 'q.jpg', 's': 's.jpg', 'v': 'v.jpg', 'w': 'w.jpg', 'x': 'x.jpg'}
answers question: http://stackoverflow.com/q/51027787
score: 0
type: Answer

http://stackoverflow.com/comment/89134315
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51072105
type: Comment
has text: @machetazo I lost my mind for a second, just updated my answer with something 100x cleaner

http://stackoverflow.com/q/51151949
favorite count: 0
type: Question
has body: I'm working on django-import-export library for importing & exporting xls format, Everything working probably at AdminModel,Now I'm trying to make importing working with views.py & templates but for some reasons didn't work with me views.py def simple_upload(request): if request.method == 'POST': person_resource = resources.SimsResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'import_sims.html', {'errors': result.has_errors(), 'result': result}) return render(request, 'import_sims.html') resources.py class SimsResource(resources.ModelResource): class Meta: model = models.Sim fields = ['s_serial_number', 's_number', 's_provider', 'status'] forms.py class UploadFileForm(forms.Form): file = forms.FileField() url.py url(r'^importing_sims/$', views.simple_upload, name='Import'), template {% if errors %} errors: {{ errors }} resluts : {{ result }} {% endif %} {% csrf_token %} Upload and error output : errors: True resluts : <import_export.results.Result object at 0x1072b75f8> UPDATE : after some updates in views.py here is the new error : KeyError at /importing_sims/ 'id' which is not showing in admin import and here is update : def simple_upload(request): if request.method == 'POST': form = forms.UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data['file'] data = bytes() for chunk in file.chunks(): data += chunk dataset = XLS().create_dataset(data) result = resources.SimsResource().import_data(dataset, dry_run=False, raise_errors=True, user=request.user) return render(request, 'import_sims.html', {'errors': result.has_errors(), 'result': result}) return render(request, 'import_sims.html')
tagged with: django-import-export
tagged with: django
tagged with: python
score: 4
upvote count: 4
answer count: 0
type: UnansweredQuestion
has title: django-import-export import data from views.py
downvote count: 0

http://stackoverflow.com/a/70332920
has comment: http://stackoverflow.com/comment/124328500
type: Answer
answers question: http://stackoverflow.com/q/51119495
has body: I was facing the same issue when doing flask run in the VScode. But when I tried on CMD it worked fine
score: 0

http://stackoverflow.com/q/51142314
type: UnansweredQuestion
has body: I am running into an issue with reading a file that has UTF8 and ASCII character. The problem is I am using seek to only read some part of the data, but I have no idea if I am "read" in the "middle" of an UTF8. osx python 3.6.6 to simply it, my issue can demoed with following code. # write some utf-8 to a file open('/tmp/test.txt', 'w').write(chr(12345)+chr(23456)+chr(34567)+'\n') data = open('/tmp/test.txt') data.read() # this works fine. to just demo I can read the file as whole data.seek(1) data.read(1) # UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte # I can read by seek 3 by 3 data.seek(3) data.read(1) # this works fine. I know I can open the file in binary then read it without issue by seeking to any position, however, I need to process the string, so I will end up with same issue when decode into string. data = open('/tmp/test.txt', 'rb') data.seek(1) z = data.seek(3) z.decode() # will hit same error without using seek, I can read it correctly even just calling read(1). data = open('/tmp/test.txt') data.tell() # 0 data.read(1) data.tell() # shows 3 even calling read(1) one thing I can think is after seek to a location, try to read, on UnicodeDecodeError, position = position -1, seek(position), until I can read it correctly. Is there a better (right) way to handle it?
tagged with: python
has title: python read file utf-8 decode issue
type: Question
has comment: http://stackoverflow.com/comment/89268852
has answer: http://stackoverflow.com/a/51142427
score: 0
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/a/51062284
score: 3
has body: The short answer Do your initial work in Jupyter or something else that has a long-lived interpreter session, so you don't need to wait around for imports that much. The long answer You can use python -v to trace imports. I installed moreutils from apt and tensorflow and tflearn from pip in a pristine python:3.6-stretch Docker container... root@10e4bcd91377:/# python -v -c 'import tensorflow' 2&gt;&amp;1 | ts '%H:%M:%.S' | grep 'import ' | wc -l 954 root@10e4bcd91377:/# python -v -c 'import tflearn' 2&gt;&amp;1 | ts '%H:%M:%.S' | grep 'import ' | wc -l 1768 It's immediately clear that importing tflearn imports a whole lot of packages. Which ones? # python -v -c 'import tflearn' 2&gt;&amp;1 | grep 'import ' | cut -f1 -d# | sort | uniq &gt; tflearn-imports.txt # python -v -c 'import tensorflow' 2&gt;&amp;1 | grep 'import ' | cut -f1 -d# | sort | uniq &gt; tensorflow-imports.txt # diff --suppress-common-lines tensorflow-imports.txt tflearn-imports.txt I'll spare the 831 lines of output, but it looks like tflearn imports all of tensorflow.contrib, which is taking quite a while, and it's not something importing tensorflow itself does. Armed with this info, we can look at the original python -v -c 'import tflearn' 2&gt;&amp;1 output – it looks like tflearn.variables is the module importing tensorflow.contrib... # &lt;snip&gt; import 'tensorflow.contrib.summary.summary' import 'tensorflow.contrib' import 'tflearn.variables' import 'tflearn.config' # &lt;snip&gt; Could it be this from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope statement? Let's find out... # time python -v -c 'from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope' 2&gt;&amp;1 | grep 'import ' | wc -l 1727 real 0m4.010s user 0m3.820s sys 0m0.410s root@10e4bcd91377:/# Ayup, looks like it! Due to the way Python's importing works, importing a submodule has to evaluate the whole package, and since tensorflow.contrib doesn't use Tensor…
accepted answer of: http://stackoverflow.com/q/51061689
has comment: http://stackoverflow.com/comment/89114846
answers question: http://stackoverflow.com/q/51061689
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89143764
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89098706
has text: EDIT: to change the range length based on @blhsing's answer. still prefer this to the `any`/`map` so will leave here.
comment on: http://stackoverflow.com/a/51053821
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/113680894
comment on: http://stackoverflow.com/a/51125687
score: 0
type: AnswerComment
has text: This answer could use some more explanation about why the first line above is wrong. StandardScaler is a class, so why can't we just pass just its name? I may be mistaken, but, I think the issue is the difference between the name of a class and a new instance of it, but don't you think this answer could benefit from at least one more sentence of explanation to that effect?
type: Comment

kinect
type: Tag
tag name: kinect
tags question: http://stackoverflow.com/q/51050784

http://stackoverflow.com/comment/89108108
type: AnswerComment
has text: write = ExcelWriter('./PythonExportt.xlsx') This will write the file into the same folder as manage.py file.
type: Comment
comment on: http://stackoverflow.com/a/51058893
score: 0

http://stackoverflow.com/q/51155505
tagged with: anaconda
has answer: http://stackoverflow.com/a/53003966
has comment: http://stackoverflow.com/comment/89294572
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/64411442
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51155681
answer count: 4
has comment: http://stackoverflow.com/comment/89294495
has title: Maximum recursion depth exceeded with pyinstaller in Python?
upvote count: 3
has body: This is a common issue with certain libraries like pandas. I read that the solution may be by adding: import sys sys.setrecursionlimit(3000) in the setup.py .Where is this setup file? I have created the py file and located it in the directory that i want to turn to exe but i don't know where i should add that piece of code? There is also this fix: hook-pandas.py hiddenimports = ['pandas._libs.tslibs.timedeltas', 'pandas._libs.tslibs.nattype', 'pandas._libs.tslibs.np_datetime', 'pandas._libs.skiplist'] but I don't know how to make this hook even though I read the post in the official site. If you can, make a clear answer about how to solve this.
type: Question
has answer: http://stackoverflow.com/a/51155707
score: 3

http://stackoverflow.com/a/51053260
downvote count: 0
score: 1
has body: It looks like your trying to run code written for Windows on Ubuntu. It looks like the path name is not a POSIX style path. You will need to configure linux odbc properly - or just install python on Windows and run your code there... As far as I know there is no free linux ODBC driver for accdb files. You would likely have to convert the database, use commercial software, or access the DB from Windows.
has comment: http://stackoverflow.com/comment/89097630
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51053114
accepted answer of: http://stackoverflow.com/q/51053114
type: Answer

http://stackoverflow.com/comment/89134944
type: Comment
type: QuestionComment
has text: `x = str(x)` isn't going to do anything when `x` is a string. It's just the _wrong_ string. (If my guess is right: the `repr` of a string is another string, because the `repr` of _anything_ is a string.)
comment on: http://stackoverflow.com/q/51072399
score: 0

http://stackoverflow.com/q/51115744
answer count: 10
favorite count: 0
score: 39
has answer: http://stackoverflow.com/a/52352339
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56876632
has body: How to set path for python 3.7.0? I tried the every possible way but it still shows the error! Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry_points.txt' Consider using the --user option or check the permissions
has answer: http://stackoverflow.com/a/56334610
tagged with: python
linked to: http://stackoverflow.com/q/42988977
has comment: http://stackoverflow.com/comment/124897107
has title: Access is denied when trying to pip install a package on Windows
has answer: http://stackoverflow.com/a/57087841
has answer: http://stackoverflow.com/a/59008965
type: Question
has answer: http://stackoverflow.com/a/55100713
downvote count: 0
has answer: http://stackoverflow.com/a/71598398
has answer: http://stackoverflow.com/a/54334551
has answer: http://stackoverflow.com/a/78342280
has answer: http://stackoverflow.com/a/51543327
linked to: http://stackoverflow.com/q/31172719
upvote count: 39
tagged with: windows

http://stackoverflow.com/q/51164163
type: Question
tagged with: pandas
has body: I'm getting a table not found error when I utilize multiprocessing on chunked Pandas dataframe in each processor started by the mp library. I'm using pandasql library for SQL in the following manner: import pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) df = pd.DataFrame({'a': [1,2,4,3,6,1,2], 'b': ['a','a','b','b','c','c','c']}) This works for single thread: sorted_df = pysqldf("select * from df order by b, a") It doesn't work when I apply multiprocessing to process each chunk of df in parallel: def parallelize_dataframe(df, func): unique_bs = df.b.unique().tolist() df_split = [df[df.a == l] for l in unique_bs] df = pd.concat(pool.map(func, df_split)) pool = Pool(num_cores) pool.close() pool.join() return df def sort_chunks(data): sorted_data = pysqldf("select * from data order by b, a") return sorted_data sorted_df = parallelize_dataframe(df, sort_chunks) The error I get is the following: PandaSQLException: (sqlite3.OperationalError) no such table: data [SQL: 'select * from data'] (Background on this error at: http://sqlalche.me/e/e3q8) I understand what the error is telling me. Basically, the data DF in each processor isn't found in the Database. I'm not sure what would be the workaround for this issue. Any input would be much appreciated. Thank you.
tagged with: python
tagged with: pandasql
has answer: http://stackoverflow.com/a/51179026
upvote count: 1
answer count: 1
tagged with: multiprocessing
type: UnansweredQuestion
has title: Multiprocessing Pandas SQL
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/89219939
comment on: http://stackoverflow.com/a/51116516
type: AnswerComment
has text: @UdiVahaba this works for me: `candlestick_ohlc( ax, ohlc, width=0.6, colorup='#77d879', colordown='#db3f3f', alpha=0.3 )` (with my data)
score: 0
type: Comment

http://stackoverflow.com/comment/89064449
type: AnswerComment
comment on: http://stackoverflow.com/a/51035794
score: 0
type: Comment
has text: @abarnert ohhh, right, yeah but why still use python 2.7?!

http://stackoverflow.com/a/51074666
accepted answer of: http://stackoverflow.com/q/51074615
type: Answer
has comment: http://stackoverflow.com/comment/89138792
has comment: http://stackoverflow.com/comment/89138660
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51074615
type: AcceptedAnswer
downvote count: 0
has body: \s* considers any spaces before the actual digit at the beginning. \b checks for the first word. Moreover, can use strip() afterward to remove any unneeded spaces in start and end of the remaining string. re.sub(r'\s*\b(\d+\w*)', '', "3g wireless").strip() # 'wireless' re.sub(r'\s*\b(\d+\w*)', '', "RPG400").strip() # 'RPG400'

http://stackoverflow.com/q/51015646
has answer: http://stackoverflow.com/a/51015672
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89024028
has answer: http://stackoverflow.com/a/51015670
type: Question
linked to: http://stackoverflow.com/q/38980507
tagged with: dataframe
linked to: http://stackoverflow.com/q/43408621
has title: Pandas: move row (index and values) from last to first
has body: I would like to move an entire row (index and values) from the last row to the first row of a DataFrame. Every other example I can find either uses an ordered row index (to be specific - my row index is not a numerical sequence - so I cannot simply add at -1 and then reindex with +1) or moves the values while maintaining the original index. My DF has descriptions as the index and the values are discrete to the index description. I'm adding a row and then would like to move that into row 1. Here is the setup: df = pd.DataFrame({ 'col1' : ['A', 'A', 'B', 'F', 'D', 'C'], 'col2' : [2, 1, 9, 8, 7, 4], 'col3': [0, 1, 9, 4, 2, 3], }).set_index('col1') #output In [7]: df Out[7]: col2 col3 col1 A 2 0 A 1 1 B 9 9 F 8 4 D 7 2 C 4 3 I then add a new row as follows: df.loc["Deferred Description"] = pd.Series(['']) In [9]: df Out[9]: col2 col3 col1 A 2.0 0.0 A 1.0 1.0 B 9.0 9.0 F 8.0 4.0 D 7.0 2.0 C 4.0 3.0 Deferred Description NaN NaN I would like the resulting output to be: In [9]: df Out[9]: col2 col3 col1 Defenses Description NaN NaN A 2.0 0.0 A 1.0 1.0 B 9.0 9.0 F 8.0 4.0 D 7.0 2.0 C 4.0 3.0 I've tried using df.shift() but only the values shift. I've also tried df.sort_index() but that requires the index to be ordered (there are several SO examples using df.loc[-1] = ... then then reindexing with df.index = df.index + 1). In my case I need the Defenses Description to be the first row.
answer count: 2
duplicate of: http://stackoverflow.com/q/43408621
tagged with: pandas
score: 3
accepted answer: http://stackoverflow.com/a/51015670
downvote count: 0
has comment: http://stackoverflow.com/comment/89024041
possible better answer: http://stackoverflow.com/a/51015672
favorite count: 0

http://stackoverflow.com/comment/89306665
score: 0
type: AnswerComment
has text: @AlainD..can you please explain a little more on when you say "the fluctuation is an order of magnitude lower than the trend"\
comment on: http://stackoverflow.com/a/51157881
type: Comment

http://stackoverflow.com/comment/89017123
comment on: http://stackoverflow.com/q/51011742
score: 0
type: Comment
type: QuestionComment
has text: How are you creating the file `output1.csv`, with this `with open("INPUT", 'w') as f_in:`? Surely that is creating a file called `INPUT`.

http://stackoverflow.com/comment/89059651
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51032673
type: Comment
has text: As @PixelEinstein mentioned you can answer your own question. Edit this answer with the exact steps you have taken to solve your question and come back after 48 hours to accept the answer as a solution to your question

http://stackoverflow.com/q/51158770
type: Question
has body: Q: Code runs but only prints the else statement... Any help is appreciated. fruit = str() favorite_fruits = ["mango", "kiwi", "pineapple"] if fruit in favorite_fruits is "mango": print('You really like ' + fruit + '.') if fruit in favorite_fruits is "kiwi": print('You really like ' + fruit + '.') if fruit in favorite_fruits is "pineapple": print('You really like ' + fruit + '.') if fruit in favorite_fruits is "apple": print('You really like' + fruit + '.') else: print('Your going to starve.')
has answer: http://stackoverflow.com/a/51158942
score: 0
has comment: http://stackoverflow.com/comment/89305524
answer count: 1
accepted answer: http://stackoverflow.com/a/51158942
tagged with: python-3.x
has title: New at Python need some guidance with IF statements
tagged with: python
has comment: http://stackoverflow.com/comment/89301126
type: AnsweredQuestion

http://stackoverflow.com/q/51075396
type: AnsweredQuestion
has title: Python Django does not overwrite newly uploaded file with old one
tagged with: django
upvote count: 1
has body: I want to overwrite/replace a file whenever a new file is uploaded. Currently the app can upload the file to a specific folder but its not overwriting files in an event that a new file has been uploaded. I need assistance to resolve that. views.py def uploadfunc(request): if request.method=='POST': form =uploadfileform(request.POST,request.FILES) if form.is_valid(): form.save() return render_to_response('upload_successful.html') else: form=uploadfileform() return render(request, 'upload.html',{'form':form}) models.py class uploadfolder(models.Model): """ my application """ File_to_upload = models.FileField(upload_to='') forms.py class uploadfileform(forms.ModelForm): class Meta: model=uploadfolder fields=('File_to_upload',)
type: Question
tagged with: django-views
has comment: http://stackoverflow.com/comment/89140126
linked to: http://stackoverflow.com/q/9522759
has answer: http://stackoverflow.com/a/51075617
answer count: 2
has comment: http://stackoverflow.com/comment/89140709
possible better answer: http://stackoverflow.com/a/51093099
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51093099
favorite count: 0
has comment: http://stackoverflow.com/comment/89140657
tagged with: python
accepted answer: http://stackoverflow.com/a/51075617

http://stackoverflow.com/a/51014754
type: Answer
answers question: http://stackoverflow.com/q/51014688
has comment: http://stackoverflow.com/comment/89022599
has comment: http://stackoverflow.com/comment/89022636
score: 0
has body: You haven't created a virtual environment. There were errors. Please reread carefully your own screenshots, last but one and the last. Cannot copy/paste the error message here from the images. That's one of many reasons why images without text are bad.
has comment: http://stackoverflow.com/comment/89022523

http://stackoverflow.com/q/51087174
has title: Performance optimization (python): Speeding up .append() to pandas DataFrame
type: Question
tagged with: mongodb
has body: I have a very large dataset in a mongoDB which is queried and appended to a resulting DataFrame. for tree in db.im_tree_active.find({"date" : { '$gte' : startdate , '$lte' : enddate },"depth" : {'$gte' : 1, '$lte' : 4}, no_cursor_timeout = True).batch_size(1500): if count % 1000 == 0: print(count, tot) #keyFill(keylist, tree) &lt;-- added to compensate for mismatched columns #im = im.append(tree) &lt;-- ran too slowly im.loc[count, :] = tree &lt;-- runs much faster but keyFill() slows down count+=1 Using pandas .append() function created a copy of the dataframe, which took far too long when the DataFrame became much larger. I replaced the append statement with a .loc[] statement which I read should speed up the query a bit, however I receive a mismatched column error. This is because some of the trees that are iterated through in the MongoDB don't have some of the fields which other ones do have. I fixed this by adding a function keyFill() given by the following simple code: def keyFill(keylist, tree): for key in keylist: if key not in tree.keys(): tree[key] = "" return tree However running this before every single .loc[] call causes the query to slow down nearly 1000% (estimated). Is there a way to speed this whole process up? The query runs a lot quicker before it reaches about 50% through the dataset, and then continues to slow down to the point that the last 1000 trees that it appends takes nearly 10x as long to run as the first 1000.
upvote count: 3
has comment: http://stackoverflow.com/comment/89163165
tagged with: pandas
has comment: http://stackoverflow.com/comment/89163878
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89163789
linked to: http://stackoverflow.com/q/31674557
score: 3
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/89163176
tagged with: pymongo

http://stackoverflow.com/comment/89065745
type: Comment
type: QuestionComment
has text: @min2bro updated.
comment on: http://stackoverflow.com/q/51036056
score: 0

http://stackoverflow.com/comment/89189037
score: 0
type: AnswerComment
has text: Also: a module is only loaded once per process (the first time it's imported), then it's cached in `sys.modules`, - but this is only true if it's always imported with the same qualified name. When you have the same module accessible as both package.sub.module and sub.module _and_ it's imported once with each path, the module is actually loaded and cached twice. This is inefficient, but it also plays havoc with any piece of code relying on identity - such as exception handlers - since the module object itself _and all the objects it exports_ are duplicated under different ids.
type: Comment
comment on: http://stackoverflow.com/a/51095822

http://stackoverflow.com/a/51087278
accepted answer of: http://stackoverflow.com/q/51085184
score: 1
has body: The following should do the trick: loadHr.groupby(['mo', 'OnOff', 'he']).mean()\ .reset_index().groupby(['OnOff', 'period']).mean().loc[(1, 201606)] We have to reset the index for groupby to be able to pick it up again. Since we end up with a multi-index, we have to pass a tuple to the .loc method.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51085184
type: Answer
upvote count: 1

http://stackoverflow.com/q/51084601
accepted answer: http://stackoverflow.com/a/51084703
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89158073
type: Question
linked to: http://stackoverflow.com/q/29815129
answer count: 1
has answer: http://stackoverflow.com/a/51084703
duplicate of: http://stackoverflow.com/q/29815129
score: 0
tagged with: pandas
has body: I was wondering how to make cleaner code, so I started to pay attention to some of my daily code routines. I frequently have to iterate over a dataframe to update a list of dicts: foo = [] for index, row in df.iterrows(): bar = {} bar['foobar0'] = row['foobar0'] bar['foobar1'] = row['foobar1'] foo.append(bar) I think it is hard to maintain, because if df keys are changed, then the loop will not work. Besides that, write same index for two data structures is kind of code duplication. The context is, I frequently make api calls to a specific endpoint that receives a list of dicts. I'm looking for improviments for that routine, so how can I change index assignments to some map and lambda tricks, in order to avoid errors caused by key changes in a given dataframe(frequently resulted from some query in database)? In other words, If a column name in database is changed, the dataframe keys will change too, So I'd like to create a dict on the fly with same keys of a given dataframe and fill each dict entry with dataframe corresponding values. How can I do that?
tagged with: python-3.x
has title: Dataframe iteration better practices for values assignment
has comment: http://stackoverflow.com/comment/89157640

http://stackoverflow.com/q/51091969
tagged with: pyqt
answer count: 1
has answer: http://stackoverflow.com/a/51143307
has comment: http://stackoverflow.com/comment/89172498
tagged with: python
tagged with: qtableview
type: AnsweredQuestion
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/51143307
has body: I am working with QTableView. I am able to sort the data based on individual column headers in both ascending as well as descending orders. Once I sort the data by column header, I would like to again sort it based on the original index. I tried following this question but was unable to fix it. Code: import numpy as np from qtpy import QtCore, QtGui, QtWidgets from qtpy.QtCore import Qt, QAbstractTableModel from qtpy.QtWidgets import QApplication, QTableView data = np.random.random((10, 3)) app = QApplication(['']) class SimpleModel(QAbstractTableModel): headers = 'Col 1', 'Col 2', 'Col 3' def __init__(self, *args, **kwargs): super(SimpleModel, self).__init__(*args, **kwargs) table.setSortingEnabled(True) self.order = np.arange(data.shape[0]) self.layoutChanged.emit() def rowCount(self, index=None): return 10 def columnCount(self, index=None): return 3 def data(self, index, role): if role == Qt.DisplayRole: col = index.column() row = index.row() return str(data[self.order[row], col]) def sort(self, column, ascending): self.order = np.argsort(data[:, column]) if ascending == Qt.DescendingOrder: self.order = self.order[::-1] self.layoutChanged.emit() def headerData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole : if orientation == QtCore.Qt.Horizontal : return self.headers[section] elif orientation == QtCore.Qt.Vertical : return section return None table = QTableView() table.setModel(SimpleModel()) table.show() app.exec_() Screenshot: Thank You.
type: Question
has title: QTableView: How to sort input data in TableView by row index (header index -1)?
linked to: http://stackoverflow.com/q/49555969
tagged with: qtablewidget
score: 0
has comment: http://stackoverflow.com/comment/89266291

http://stackoverflow.com/comment/89197151
comment on: http://stackoverflow.com/q/51104597
score: 0
type: Comment
type: QuestionComment
has text: Why aren't you able? Does the program crash? Does it throw an error? Does nothing at all happen?

http://stackoverflow.com/q/51030047
downvote count: 1
has answer: http://stackoverflow.com/a/51030172
has comment: http://stackoverflow.com/comment/89052611
has title: python convert "unicode" as list
type: Question
has comment: http://stackoverflow.com/comment/89053089
has answer: http://stackoverflow.com/a/51030127
tagged with: python-2.7
score: 0
answer count: 4
favorite count: 0
type: UnansweredQuestion
has body: I have a doubt about treat a return type in python. I have a database function that returns this as value: (1,13616,,"My string, that can have comma",170.90) I put this into a variable and did test the type: print(type(var)) I got the result: &lt;type 'unicode'&gt; I want to convert this to a list and get the values separeteds by comma. Ex.: var[0] = 1 var[1] = 13616 var[2] = None var[3] = "My string, that can have comma" var[4] = 170.90 Is it possible?
has answer: http://stackoverflow.com/a/51030295
has answer: http://stackoverflow.com/a/51030126
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89300588
type: AnswerComment
comment on: http://stackoverflow.com/a/51158126
type: Comment
has text: make sure that your indentations are correct, and you are **closing the sockets properly** as that's the reason why you're getting this error, I think you're trying to use the socket after calling shutdown or something similar. hope it works for you
score: 1

http://stackoverflow.com/q/51057476
has comment: http://stackoverflow.com/comment/89107368
has comment: http://stackoverflow.com/comment/89105826
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89106836
type: Question
has title: Compare each file with their corresponding file in another folder in Python?
has comment: http://stackoverflow.com/comment/89106063
has answer: http://stackoverflow.com/a/51058582
has comment: http://stackoverflow.com/comment/89106278
accepted answer: http://stackoverflow.com/a/51058582
has body: This code takes one shapefile, looks at its schema and compares it with another shapefile (its corresponding) in another location and prints their differences in their schemas. pst_n=fiona.open(r'C:\Users\user\Desktop\new\PST')#new pst pst_o=fiona.open(r'C:\Users\user\Desktop\old\PST')#old_pst pst_n.schema d1 = pst_n.schema['properties'] d2 = pst_o.schema['properties'] d1_items = set(d1.items()) d2_items = set(d2.items()) result = sorted([(k, 'd1', v) for k, v in d1_items if (k, v) not in d2_items] + [(k, 'd2', v) for k, v in d2_items if (k, v) not in d1_items]) result = [(k, v, d) for k, d, v in result] pprint(result) And shows the differences like that: [('ADDRESS', 'int:4', 'd1'), ('ADDRESS', 'str:254', 'd2'), ('AREA', 'float:19.11', 'd2'), ('DEC_ID', 'int:4', 'd1'), ('DEC_ID', 'str:254', 'd2'), ('DESC_', 'str:254', 'd1'), ('FID_PERIVL', 'int:9', 'd1'), ('KAEK', 'str:50', 'd1'), ('KAEK', 'str:12', 'd2'), ('LEN', 'float:19.11', 'd2') This is done manually here. I want it to be done by searching in one main directory for the old versions of the files and comparing each in every subfolder of the other main directory with the corresponding new versions. What is the wanted result One main folder A with B,C,D... subfolders. This main folder has new under consideration files.Most of the subfolders have shps. There is one other main folder though. Let's call it K with L,M,N.. subfolders.These subfolders are the corresponding from the other subfolders of the other folder with the new files. The subfolders from A have the same names with the ones from K although K may have more that we don't need. I want the user to insert the directory of the main A folder and read the first shp from the first subfolder (if it exists an shp there) then go to the other old main folder and check the corresponding subfolder, get the shp from there and do some comparisons between them and print the results(the italics parts i have already solved them)and then continue with the rest of the new…
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/a/62438923
score: 0
has body: Here is the code for a 3 layer sparse autoencoder, implemented in Tensorflow 2.1. The input and the output, in this case, are 1D arrays (496). I would like to give credit to Dr. Zhiwei Lin at Ulster University for providing the initial implementation on github https://github.com/zhiweiuu/sparse-autoencoder-tensorflow/blob/master/SparseAutoEncoder.py I have wrapped it in a class, where each layer is now an instance variable. This makes it easier to get different outputs for each layer. You will notice that I have used only the first layer output for the sparsity constraint. This architecture is similar to the one used in this article: https://pubmed.ncbi.nlm.nih.gov/29302382/ My implementation is simple and the training and it can be improved :) to train the model model = my_model() then you loop for i in range(1000): model.network_learn(X,Y) class my_model: def __init__(self): xavier=tf.keras.initializers.GlorotUniform() self.l1 = tf.keras.layers.Dense(496,kernel_initializer=xavier,activation=tf.nn.sigmoid,input_shape=(496,)) self.l2 = tf.keras.layers.Dense(496,kernel_initializer=xavier,activation=tf.nn.sigmoid) self.l3 = tf.keras.layers.Dense(496,kernel_initializer=xavier,activation=tf.nn.sigmoid) self.train_op = tf.keras.optimizers.SGD(learning_rate=0.01) self.rho = 0.05 self.alpha= 0.001 self.beta = 4 def kl_divergence(self, rho, rho_hat): return rho * tf.math.log(rho) - rho * tf.math.log(rho_hat) + (1 - rho) * tf.math.log(1 - rho) - (1 - rho) * tf.math.log(1 - rho_hat) def run(self,X): out1=self.l1(X) out2=self.l2(out1) out3 = self.l3(out2) return out3 def get_loss(self,X,Y): rho_hat = tf.reduce_mean(self.l1(X),axis=0) kl = self.kl_divergence(self.rho,rho_hat) out1=self.l1(X) out2=self.l2(out1) X_prime=self.l3(out2) diff = X-X_prime W1 = self.l1.variables[0] W2 = self.l2.variables[0] W3 = self.l3.variables[0] cost= 0.5*tf.reduce_mean(tf.reduce_sum(diff**2,axis=1)) \ +0.5*self.alpha*(tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2) + tf.nn.l2_loss(W3)) \ +self.beta*tf.reduc…
type: Answer
answers question: http://stackoverflow.com/q/51015799

spline
tags question: http://stackoverflow.com/q/51086248
tag name: spline
type: Tag
tags question: http://stackoverflow.com/q/51050622

http://stackoverflow.com/q/51128208
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51159039
has title: Python pointing to wrong OpenSSL version
favorite count: 0
has comment: http://stackoverflow.com/comment/89241634
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89241480
tagged with: pip
tagged with: python
score: 1
upvote count: 1
type: Question
has body: I've upgraded my OpenSSL version: [root@server ~]# openssl version OpenSSL 1.0.2o 27 Mar 2018 I'm still getting SSL errors with Python/Pip (SSLError(SSLError(1, '[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version) so I checked my Python OpenSSL version: [root@server ~]# python3.5 -c "import ssl; print(ssl.OPENSSL_VERSION)" OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008 How do I point Python 3.5 to v1.0.2? Is there a way without a full recompile? Running CentOS, I compiled OpenSSL to upgrade.
tagged with: openssl

http://stackoverflow.com/comment/89016264
type: Comment
type: QuestionComment
has text: Should I run it after `plot`?
comment on: http://stackoverflow.com/q/51011424
score: 0

http://stackoverflow.com/q/51157219
has comment: http://stackoverflow.com/comment/89298012
has comment: http://stackoverflow.com/comment/89297998
type: Question
has comment: http://stackoverflow.com/comment/89298429
tagged with: python-sockets
score: -2
has body: This is the code i am trying to run import socket s = socket.socket() print ("Socket successfully created") port = 12345 s.bind(('', port)) print ("socket binded to %s" %(port)) s.listen(5) print ("socket is listening") while True: c, addr = s.accept() print ('Got connection from', addr) c.send('Thank you for connecting') c.close() This code is running successfully, but the problem occurs when i try to run these commands: # start the server $ python server.py # keep the above terminal open # now open another terminal and type: $ telnet localhost 12345 Error that is coming: When i type $ python server.py I am getting the same error. A possible solution to this would have been that i didnt set my environment variable right, but when i type python in the command prompt, i get no error. What I am doing wrong? I copied this code from Here (Python socket network programming) PS: I am using 3.4.3 version
tagged with: python-webbrowser
has comment: http://stackoverflow.com/comment/89297941
downvote count: 3
has comment: http://stackoverflow.com/comment/89298216
upvote count: 1
tagged with: python-server-pages
answer count: 1
favorite count: 0
has title: Syntax error when trying to run server.py through command prompt
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51157312
has comment: http://stackoverflow.com/comment/89297831
accepted answer: http://stackoverflow.com/a/51157312
has comment: http://stackoverflow.com/comment/89297950
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89297850

http://stackoverflow.com/q/51125641
has answer: http://stackoverflow.com/a/51125912
tagged with: ini
tagged with: makemessages
score: 0
has title: How to best translate strings passed as variable to a Django module?
answer count: 1
has body: I'm doing my first steps in Django and am trying to get translations of text to work which I'm passing into the application through an .ini file. Say my init.ini is: [test] GREETING = Hello World and in my settings.py, I'm doing: from six.moves import configparser from django.utils.translation import ugettext_lazy as _ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Retrieve initialization configuration init_parser = configparser.ConfigParser() init_parser.read(os.path.join(BASE_DIR, 'init.ini')) ... HELLO = init_parser.get('test', 'GREETING') HELLO = _(init_parser.get('test', 'GREETING')) my tags translations do not show up when calling makemessage. The documentation says (The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin makemessages, won’t be able to find these strings. More on makemessages later.) but they although makemessage is covered aplenty on the documentation page, it does not provide a solution on how to translate variables/computed values like this. Thus my question: Is there any recommended practical way of passing strings as variables into a python module and have makemessage catch them? EDIT: adding the extension as in django-admin makemessages -l de --e=html,py,txt,ini doesn't work either, but now I'm curious how I could make a txt file that would be covered. Maybe that's an idea.
tagged with: django
tagged with: python
tagged with: internationalization
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51125912
type: Question

http://stackoverflow.com/q/51046863
upvote count: 1
has title: Select 1 True, 1 False per group in a pandas DataFrame
possible better answer: http://stackoverflow.com/a/51046864
has answer: http://stackoverflow.com/a/51046880
type: AnsweredQuestion
downvote count: 0
has body: I have a DataFrame with ~1mil rows, and ~100k unique events. There is 1 column Won which 1 row per event which is set to True, and each other row in the event has set as False. i.e., Event ID Runner ID Won E1 R1 True E1 R2 False E1 R3 False E2 R4 True E2 R5 False E2 R6 False and what I'd like to end up with is a balanced DataFrame, with only 1 winner, and only 1 non-winner per group. i.e., Event ID Runner ID Won E1 R1 True E1 R3 False E2 R4 True E2 R5 False I don't care which non-winner is selected per event, just so long as there's 1 winner, one non-winner. With pandas, I've tried a few things, select the winners, and the non-winners, _won = df.Won winners = df[_won] non_winners = df[~_won] but each process I've seen, and tried for selecting 1 non-winner per race has been extremely slow - as in a few seconds per event (which is IMO unreasonable when you've 100k events). One-shot with group and apply, new_df = winners.append( non_winners .groupby('Event ID') .apply(lambda grp: grp.sample(1)) Iterating over groupby, for event_id, grp in non_winners.groupby('Event ID'): winners.append(grp.sample(1)) Iterating over the event ids in winners, event_ids = set(winners['Event ID'].drop_duplicates()) for event_id in event_ids: winners.append( non_winners[non_winners['Event ID'] == event_id].sample(1)) But each option seems to be incredibly slow when dealing with ~1mil and ~100k events.
favorite count: 0
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51046880
tagged with: python
score: 1
answer count: 2
has answer: http://stackoverflow.com/a/51046864

zeep
tags question: http://stackoverflow.com/q/51029223
tags question: http://stackoverflow.com/q/51156327
type: Tag
tags question: http://stackoverflow.com/q/51145378
tag name: zeep

http://stackoverflow.com/q/51059608
type: Question
has body: I have a script that searches through a csv file and a fasta file and any ID's that are in both files will be used to extract the fasta sequence from fasta file. It looks like this: import os import shlex import subprocess import argparse import glob import pysam from pysam import FastaFile #setup options for this program parser = argparse.ArgumentParser() group = parser.add_argument_group('Options for annotation.py') group.add_argument( '-f', '--fasta', help='FASTA file (RAST). all_fprau.fasta', required=True) group.add_argument( '-c', '--csv', help='CSV file (parsed orthomcl groups). parsed_groups.csv', required=True) args = parser.parse_args() fasta = FastaFile(args.fasta) with open(args.csv) as infile: infile.readline() ## skip header for index, line in enumerate(infile): strain, matches = line.strip().split("\t") if not len(matches): print('Warning: Skipping strain {}. No matches'.format(strain)) continue matches = set(matches.split(',')) # remove duplicates key = '{}.faa'.format(strain) with open(key, 'w') as out_file: for match in matches: name = 'fig|{}'.format(match) try: sequence = fasta[name] except KeyError: print('Sequence absent in FASTA file {0}: {1}'.format(args.fasta, name)) continue out_file.write("&gt;{0}\n{1}\n".format(name, sequence)) I am having a problem running this script however. I get this error: File "pysam/libcfaidx.pyx", line 123, in pysam.libcfaidx.FastaFile.__cinit__ File "pysam/libcfaidx.pyx", line 183, in pysam.libcfaidx.FastaFile._open OSError: error when opening file `all_fprau.fasta` The fasta file all_fprau.fasta contains a large number of sequences and I think that this may be the problem? When I cut down the size of the file the script works, however I need all the sequences to be available for the next step in this pipeline to work. I have tried to use: fasta = glob.glob("/home/brian/my_orthomcl_dir/annotations/*.fasta") in place of fasta = FastaFile(args.fasta) in an attempt to search through the fasta files individually, bu…
has comment: http://stackoverflow.com/comment/89113871
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89112172
favorite count: 0
has comment: http://stackoverflow.com/comment/89109624
type: UnansweredQuestion
tagged with: pysam
tagged with: python
has title: Python error: OSError: error when opening file `all_fprau.fasta`. Fasta file too large?
has comment: http://stackoverflow.com/comment/89109540
has comment: http://stackoverflow.com/comment/89111129
has answer: http://stackoverflow.com/a/51065676
has comment: http://stackoverflow.com/comment/89109918
has comment: http://stackoverflow.com/comment/89113555
score: 1
upvote count: 1

geoalchemy2
tag name: geoalchemy2
tags question: http://stackoverflow.com/q/51083410
type: Tag

http://stackoverflow.com/q/51124383
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/4917006
type: Question
has title: Extract JSON from Text in python
has comment: http://stackoverflow.com/comment/89234717
upvote count: 2
answer count: 2
has body: I want to extract JSON/dictionary from a log text. The Sample log text: 2018-06-21 19:42:58 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'locations', 'CLOSESPIDER_TIMEOUT': '14400', 'FEED_FORMAT': 'geojson', 'LOG_FILE': '/geojson_dumps/21_Jun_2018_07_42_54/logs/coastalfarm.log', 'LOG_LEVEL': 'INFO', 'NEWSPIDER_MODULE': 'locations.spiders', 'SPIDER_MODULES': ['locations.spiders'], 'TELNETCONSOLE_ENABLED': '0', 'USER_AGENT': 'Mozilla/5.0'} 2018-06-21 19:43:00 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 369, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'downloader/response_bytes': 1718, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 6, 21, 14, 13, 0, 841666), 'item_scraped_count': 4, 'log_count/INFO': 8, 'memusage/max': 56856576, 'memusage/startup': 56856576, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2018, 6, 21, 14, 12, 58, 499385)} 2018-06-21 19:43:00 [scrapy.core.engine] INFO: Spider closed (finished) I have tried (\{.+$\}) as the regex expression but it gives me the the dict which is on single line, {'BOT_NAME': 'locations',..., 'USER_AGENT': 'Mozilla/5.0'} which is not what is expected. The json/dictionary I want to extract: Note: The dictionary would not the same keys, it could differ. {'downloader/request_bytes': 369, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'downloader/response_bytes': 1718, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 6, 21, 14, 13, 0, 841666), 'item_scraped_count': 4, 'log_count/INFO': 8, 'memusage/max': 56856576, 'memusage/startup': 56856576, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequ…
possible better answer: http://stackoverflow.com/a/69870245
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51124437
accepted answer: http://stackoverflow.com/a/51124437
tagged with: python
has answer: http://stackoverflow.com/a/69870245
tagged with: regex

http://stackoverflow.com/a/51076669
type: Answer
has body: In Java, you can do something like - data.substring(data.indexOf("&lt;/strong&gt;")+"&lt;/strong&gt;".length(), data .length())); May be you can convert it : )
answers question: http://stackoverflow.com/q/51076418
score: 0

http://stackoverflow.com/q/51111008
tagged with: libreoffice-basic
has answer: http://stackoverflow.com/a/51112680
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: libreoffice-calc
upvote count: 1
has comment: http://stackoverflow.com/comment/89212298
score: 1
type: Question
has body: I am new in Python and Basic. I am trying to replicate the IMPORTHTML function from Google Sheets in LibreOffice (LO) Calc. In a nutshell, I want to create a GetHtmTable( Url, Table Index) Basic function in Calc which will call a Python script to do the heavy work. So based on Villeroy's great example, I implemented in LO 5.1.6.2. the Basic SOUNDEX function which calls the Python script sheetFunctions.py to get familiar with the process. My environment is Linux Mint 18, I use Python 3, I imported all kind of libraries such as Uno, PIP etc.. I use PycharmProjects as a Python editor. I see clearly under the LO Calc menu tools->macro->organize macros->python the sheetFunctions.py Python script, which indeed is in the folder /usr/lib/libreoffice/share/Scripts/python. Whenever, I run the SOUNDEX Basic function I see the following error message: BASIC runtime error. An exception occurred Type: com.sun.star.script.provider.ScriptFrameworkErrorException Message: : an error occurred during file opening /usr/lib/libreoffice/program/pythonscript.py:429 in function getModuleByUrl() [lastRead = self.sfa.getDateTimeModified( url )] /usr/lib/libreoffice/program/pythonscript.py:993 in function getScript() [mod = self.provCtx.getModuleByUrl( fileUri )] I tried to debug the SOUNDEX basic function and found out the blocking point is when the program runs getScript("vnd.sun.star.script:sheetFunctions.py$soundex?language=Python&amp;location=user"). I've been trying for days now to overcome this error, unsuccessfully I must confess. I wonder if I need to bring some extra extensions in the Basic environment or a missing add-in in the Linux/Python one? I changed the location=user by location=document and got stuck again. I added recently libreoffice-script-provider-python thanks to the command sudo apt-get install libreoffice-script-provider-python but this did not help. I also embedded in the Calc document the Python script but same this did not solve the issue.
has title: Error in calling a Python script from a Basic function
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89235165
type: Comment
comment on: http://stackoverflow.com/q/51125119
has text: What did you expect `pass` to do?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51117659
tagged with: postgresql
has title: django clone repo is not working
type: Question
tagged with: django
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89222016
has answer: http://stackoverflow.com/a/51118111
has comment: http://stackoverflow.com/comment/89221391
type: UnansweredQuestion
tagged with: git-clone
has body: I clone a Django project from github. But when I ran the python manage.py runserver it showed the following errors. How to fix them? python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/human-inside/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/human-inside/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/human-inside/Desktop/web_project/parsifal/settings.py", line 18, in &lt;module&gt; default = config('DATABASE_URL')) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 198, in __call__ return self.config(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 77, in __call__ return self.get(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 64, in get raise UndefinedValueError('%s option not found and default value was not defined.' % option) decouple.UndefinedValueError: DATABASE_URL option not found and default value was not defined. The setting.py is here: from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP from unipath import Path import dj_database_url from decouple import config, Csv from mendeley import Mendeley SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_COO…

http://stackoverflow.com/a/51154548
accepted answer of: http://stackoverflow.com/q/51154528
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89305321
type: Answer
score: 6
downvote count: 0
upvote count: 6
answers question: http://stackoverflow.com/q/51154528
has body: Use lstrip and convert to floats: s = s.str.lstrip('$').astype(float) print (s) 0 233.94 1 214.14 2 208.74 3 232.14 4 187.15 5 262.73 6 176.35 7 266.33 8 174.55 9 221.34 10 199.74 11 228.54 12 228.54 13 196.15 14 269.93 15 257.33 16 246.53 17 226.74 Name: A, dtype: float64 Setup: s = pd.Series(['$233.94', '$214.14', '$208.74', '$232.14', '$187.15', '$262.73', '$176.35', '$266.33', '$174.55', '$221.34', '$199.74', '$228.54', '$228.54', '$196.15', '$269.93', '$257.33', '$246.53', '$226.74']) print (s) 0 $233.94 1 $214.14 2 $208.74 3 $232.14 4 $187.15 5 $262.73 6 $176.35 7 $266.33 8 $174.55 9 $221.34 10 $199.74 11 $228.54 12 $228.54 13 $196.15 14 $269.93 15 $257.33 16 $246.53 17 $226.74 dtype: object

http://stackoverflow.com/q/51110110
has title: Implementing user inputs into neural network
linked to: http://stackoverflow.com/q/45056401
tagged with: machine-learning
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89221722
has comment: http://stackoverflow.com/comment/89221767
downvote count: 0
answer count: 1
tagged with: neural-network
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51116610
tagged with: python
accepted answer: http://stackoverflow.com/a/51116610
score: 2
type: AnsweredQuestion
has body: I have some theoretical questions along with my original question. I am very new to Keras, and am having some logical questions. The first question is regarding the train, test etc. I come from using Sci-kit learn and usually use the test_train_split library to do this (I am assuming I can do the same here?) My next question would be the transformation of the features and labels. From my understanding so far, we cannot feed strings into the neural network, so some sort of nomalization would have to be done. I learned either tokenization or dummy variables for categorical variables, normalization should be done for the numerical values. My question with this is: there are 5 columns (2 categorical and 3 numerical) in a feature vector. Can I create dummy variables for the 2 categorical and then normalize the ENTIRE feature vector? After this, my question would in the code below about the input_shape(x, y). The example code below is from image recognization. Say that I want to use my own data set, will I have to know the input_shape beforehand and define it that way? Or is that something that the model can learn itself? My last question would be in this: say that the features vector is composed of variables a, b, c, and d. How can I have the user enter their value for a, b, c, and d and have the model give an output? In the example, the model was loaded in from a CSV into a dataframe and then I spit that data into testing and training for features and labels. In this instance, do I need to store the users variables into a dataframe in order for the model to predict output? The code I am referring to is for images, but my use case will not be images rather integers. Code: from keras.datasets import mnist from keras import models from keras import layers (train_images, train_labels), (test_images, test_labels) = mnist.load_data() model = model.Sequential() model.add(layers.Dense(16, activation = 'relu', input_shape = (10000,))) model.add(layers.Dense(16, activation = 'rel…
upvote count: 2

nlp
tags question: http://stackoverflow.com/q/51142294
tags question: http://stackoverflow.com/q/51058877
tags question: http://stackoverflow.com/q/51113885
tags question: http://stackoverflow.com/q/51135507
tags question: http://stackoverflow.com/q/51100043
tags question: http://stackoverflow.com/q/51076475
tags question: http://stackoverflow.com/q/51079986
tags question: http://stackoverflow.com/q/51132716
tags question: http://stackoverflow.com/q/51161751
tags question: http://stackoverflow.com/q/51016017
tags question: http://stackoverflow.com/q/51087854
tags question: http://stackoverflow.com/q/51056731
tags question: http://stackoverflow.com/q/51049568
tags question: http://stackoverflow.com/q/51120323
tags question: http://stackoverflow.com/q/51159622
tags question: http://stackoverflow.com/q/51092795
tags question: http://stackoverflow.com/q/51102007
tags question: http://stackoverflow.com/q/51087661
tags question: http://stackoverflow.com/q/51038266
tags question: http://stackoverflow.com/q/51070345
tags question: http://stackoverflow.com/q/51062603
tags question: http://stackoverflow.com/q/51082572
tags question: http://stackoverflow.com/q/51011474
tags question: http://stackoverflow.com/q/51138290
tags question: http://stackoverflow.com/q/51144078
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/51014463
tags question: http://stackoverflow.com/q/51105753
tags question: http://stackoverflow.com/q/51142051

http://stackoverflow.com/q/51152647
has answer: http://stackoverflow.com/a/51220891
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-pbr
tagged with: python
accepted answer: http://stackoverflow.com/a/51220891
type: AnsweredQuestion
tagged with: python-3.x
tagged with: setup.py
upvote count: 3
type: Question
score: 3
has title: How to tell pbr to include non-code files in package
has body: I only run into this problem when I build in a python:alpine image. Reproducing it is a bit of a pain, but these are the steps: Docker container setup: $ docker run -it python:3.7-rc-alpine /bin/ash $ pip install pbr Small package setup, including non-python files test ├── .git ├── setup.cfg ├── setup.py └── src └── test ├── __init__.py ├── test.yml └── sub_test ├── __init__.py └── test.yml setup.py: from setuptools import find_packages, setup setup( setup_requires=['pbr'], pbr=True, package_dir={'': 'src'}, packages=find_packages(where='src'), ) setup.cfg: [metadata] name = test All other files are empty. I copy them to the container with docker cp test &lt;docker_container&gt;:/test. Back in the container I now try to build the package with cd test; pip wheel -w wheel ., the test.yml in test/src/test will be included in it, but the one in test/src/test/sub_test won't. I have no clue why this happens, since the (pitifully sparse, and imo quite confusing) documentation of pbr on that matter states that Just like AUTHORS and ChangeLog, why keep a list of files you wish to include when you can find many of these in git. MANIFEST.in generation ensures almost all files stored in git, with the exception of .gitignore, .gitreview and .pyc files, are automatically included in your distribution. I could not find a pbr-parameter that lets me explicitly include some file or file type, which I expected to exist. Creating a MANIFEST.in with import src/test/sub_test.test.yml actually solves this problem, but I'd rather understand and avoid this behavior all together instead.

http://stackoverflow.com/a/51133055
downvote count: 0
score: 1
has body: One suggestion is that you can use the timedelta function from datetime module: from datetime import datetime, timedelta etatime = datetime.strptime("2018-07-06T07:00:00.000", "%Y-%m-%dT%H:%M:%S.%f") # Before adding one hour print(etatime) etatime = etatime + timedelta(hours=1) # After adding one hour print(etatime) Output: 2018-07-06 07:00:00 2018-07-06 08:00:00
answers question: http://stackoverflow.com/q/51132916
upvote count: 1
has comment: http://stackoverflow.com/comment/89250843
type: Answer
has comment: http://stackoverflow.com/comment/89250928

http://stackoverflow.com/comment/125451847
comment on: http://stackoverflow.com/a/70920396
type: AnswerComment
has text: I am not sure if any of these functions run in a separate thread. As long as they don't, you should be fine... but I can't say for sure without more investigation.
score: 0
type: Comment

http://stackoverflow.com/q/51047116
tagged with: julia
accepted answer: http://stackoverflow.com/a/51048456
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/69177814
has body: I have a database created in Julia with the JLD Package This database contains 2 elements: input and output In julia, I can load it with the following code: using JLD data_in = load("file_path")["input"] 1×5 Array{Int64,2}: 1 2 3 4 5 data_out = load("file_path")["output"] 1×5 Array{Int64,2}: 3 6 9 12 15 I would like to load these arrays in Python. I tried the following (in Python): filename = "file_path" data = open(filename, r) data returns the following: data &lt;_io.TextIOWrapper name='file_path' mode='r' encoding='UTF-8'&gt; After that, I read a document that explained how to read a file. Nevertheless, if I run the following: print(data.readlines()) I have only this output: [] Is it possible to load these arrays in Python ? EDIT I tried to do an equivalent of Julia: data = open("file_path")["input"] But there is this error: TypeError: '_io.TextIOWrapper' object is not subscriptable Maybe there is an other function to read a file ?
has comment: http://stackoverflow.com/comment/89085584
score: 9
type: Question
has answer: http://stackoverflow.com/a/51048456
has comment: http://stackoverflow.com/comment/89088118
answer count: 2
has comment: http://stackoverflow.com/comment/89086059
upvote count: 9
has title: Load a JLD file in Python
has answer: http://stackoverflow.com/a/69177814
downvote count: 0
has comment: http://stackoverflow.com/comment/89088225
favorite count: 0
tagged with: python

http://stackoverflow.com/a/62209719
answers question: http://stackoverflow.com/q/51119495
has body: The set command works but to setup the environment, you need to make sure that you are in the right directory where the file is located. For example, if my application is hello_world.py and it is located at the venv\hello\hello_world.py, you need to make sure that you are in the right directory before setting up set FLASK_APP=hello_world.py this is for windows but in another OS, you need to use export instead set (venv) C:\Users\myProjects\venv\hello\set FLASK_APP=hello_world.py
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/51136120
has comment: http://stackoverflow.com/comment/89257693
has comment: http://stackoverflow.com/comment/89256771
answer count: 1
favorite count: 0
has title: Algorithm to detect a linear part of a data set
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89261140
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89256571
has answer: http://stackoverflow.com/a/51136313
type: Question
has body: I hope I'm in the right place to ask this but my problem is the following : I have a set of data (two lists x and y), I dont have much other information about this set (no function, or anything like this). My goal is to find the subset of this data that is linear (the part highlighted in yellow in the image below). As you can see on the image after plotting the data we can see that it becomes linear for a while. and I want to detect that subset automatically. since I dont have the function behind it I'm really lost!! Anyone has an idea on how this can be done ? an algorithm or a mathematical method I can implement ? (Im using python btw)
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89256718
downvote count: 0

http://stackoverflow.com/q/51044044
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/38250710
has title: How to Randomly split CSV Dataset into 70-30?
has comment: http://stackoverflow.com/comment/89079315
score: 0
tagged with: pandas
tagged with: dataset
tagged with: scikit-learn
favorite count: 0
has body: I am working with a custom dataset, and had to make the dataset myself. The following csv format is the result: Wall# Target Feature1 Feature2 Feature3 Feature4 ... 1 Yes &lt;float&gt; &lt;float&gt; &lt;float&gt; 2 No 3 Maybe I have tried the following: df = pd.read_csv("path_to_csv") df['split'] = np.random.randn(df.shape[0], 1) msk = np.random.rand(len(df)) &lt;= 0.7 train.to_csv('train_coeffs.csv', index=False) test.to_csv('test_coeffs.csv', index=False) But it's giving me messed up results with changed data values. What is the most efficient way to randomly split the dataset into a 70-30 train-test set?
has comment: http://stackoverflow.com/comment/89079187
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/38250710
answer count: 0
upvote count: 1

http://stackoverflow.com/a/51093871
score: 0
type: Answer
has body: Answer my own question, use tkinter winfo to get screen size and then put them in to videowriter and imagegrab: import tkinter as tk window = tk.Tk() width = window.winfo_screenwidth() height = window.winfo_screenheight() fourcc = cv2.VideoWriter_fourcc(*'XVID') vid=cv2.VideoWriter(r"C:\\IQOutput\\123.avi", fourcc, 12, (width, height)) while(True): img = ImageGrab.grab(bbox=(0,0,width,height))
has comment: http://stackoverflow.com/comment/94684662
answers question: http://stackoverflow.com/q/51093667

http://stackoverflow.com/comment/99803980
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56603506
has text: Put "set FLASK_APP = app.py" then "flask run" in the cmd command make shore you have installed flask with "pip install flask"
score: 1

http://stackoverflow.com/comment/89124125
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51066961
has text: Having answered a number of `transpose` questions, my guess is that you'll have to systematically test all `i` until you hit one that fails.
score: 0

http://stackoverflow.com/comment/89205197
score: 1
type: Comment
type: QuestionComment
has text: You could do a normal math division to obtain the unit you need
comment on: http://stackoverflow.com/q/51109012

http://stackoverflow.com/comment/89308435
type: Comment
type: QuestionComment
score: 0
has text: What i was looking for was resolved by creating a dictionary like you mentioned. Then write a for loop to to extract them. Thank you for all the suggestions!
comment on: http://stackoverflow.com/q/51162397

http://stackoverflow.com/comment/89113890
comment on: http://stackoverflow.com/a/51043267
score: 0
has text: Thanks for your suggestion. However, my problem is not that I have no workaround for this, it is more that my expectations of what `np.save` would do and what happened is inconsistent. It basically implies, that I would need to check prior every saving with `np.save` whether the leading dimension is the same. Moreover, `np.array` fails with an error in merging the two arrays.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89141218
has text: Hi, for_stack, thank you very much for your reply, and just one more question, I find an example from [here](https://github.com/andymccurdy/redis-py#pipelines), and there is a method to get result during a pipeline with WATCH, it seems it is possible to get values during a pipeline, because WATCH put a pipeline into immediate execution mode?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51061341
type: Comment

http://stackoverflow.com/comment/89262318
comment on: http://stackoverflow.com/a/51138235
has text: Have a look at this link https://cloud.google.com/iam/docs/granting-roles-to-service-accounts
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89275240
type: Comment
comment on: http://stackoverflow.com/a/51145417
type: AnswerComment
has text: i think the server means string-counts
score: 0

http://stackoverflow.com/q/51159461
favorite count: 0
has comment: http://stackoverflow.com/comment/89302733
tagged with: python
accepted answer: http://stackoverflow.com/a/51159763
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/37387273
has title: Flask error: sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:mongodb
has body: I am basically trying to integrate my mlab database with my flask app and I keep getting the error sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:mongodb I tested the mlab database already using the mongo shell and it worked fine but some reason the app has a problem acessing it from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) #tells srl alchemy how to connect to our database app.config['SQLALCHEMY_DATABASE_URI']='mongodb://xxxxx:xxxxxx@ds111103.mlab.com:11103/namebase' app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]= False db=SQLAlchemy(app) class Comment(db.Model): id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(20)) column=db.Column(db.String(200)) @app.route('/') def index(): return render_template('index.html') @app.route('/sign') def sign(): return render_template('sign.html') @app.route("/process",methods=["POST"]) def process(): name=request.form["name"] comment=request.form['comment'] return render_template("index.html", name=name,comment=comment ) if __name__ == '__main__': app.run(debug=True)
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/51159763
tagged with: mongodb
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51141762
has body: I have been trying this but have not got anywhere. I extract multiple values of type xe-1/2/3 and so on. I have to write a python script in such a way that, for xe-1/1/3, if it is 1, and the next value is 1, the value gets saved for FPC1: PIC1 for xe-1/2/3 if it is 1, and the next value is 2, the value gets saved for FPC1: PIC2 for xe-2/1/3 if it is 2, and the next value is 1, the value gets saved for FPC2: PIC1 Pseudo code would be: value = "xe-1/2/3" value.split("/") if value[0].endswith("1"): if [value[1].startswith("0"): print "FPC1: PIC1" But, I intend to not hard code the values, since the value is a list of many values which is extracted from an xml file. All the data that is extracted needs to be further printed in a text file. Open to any suggestions on how all this data needs to be saved, for now I am using simple ways just printing it directly and so on ...
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/89280714
answer count: 1
has comment: http://stackoverflow.com/comment/89271050
has comment: http://stackoverflow.com/comment/89267667
has comment: http://stackoverflow.com/comment/89271075
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51141901
has comment: http://stackoverflow.com/comment/89267672
score: -3
upvote count: 1
has comment: http://stackoverflow.com/comment/89271344
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51141901
has title: Way to iterate through a string xe-1/2/3 in Python

http://stackoverflow.com/a/51034131
type: Answer
answers question: http://stackoverflow.com/q/51033964
score: 0
has body: This is sample code, maybe has better way. lis = [3, 3, 5, 2, 7, 2, 3, 0, 0, 0, 0, 4] MaximumValue = 4 start_index = 0 for i,v in enumerate(lis): start_index = i if v == 0: start_index = i - 1 break for i in range(start_index, 0, -1): diff = MaximumValue - lis[i] if diff &gt;= 0: lis[i] += diff lis[i-1] -= diff if lis[i-1] == 0: break print(lis) Output: [1, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4]

http://stackoverflow.com/comment/89256188
type: QuestionComment
has text: @brunodesthuilliers please see the updated question. I have added a screenshot of the sample output of python script in shell.
type: Comment
comment on: http://stackoverflow.com/q/51134952
score: 0

http://stackoverflow.com/comment/89251162
has text: Is there any reason why you need to retrieve a JSON key using the Google API? It looks like you could just create a service account with scopes to run BigQuery and then run these commands on your EC2 instance. Also note that the GET API call your using will retrieve the Public Key for the service account, not the Private Key you need to make authenticated calls.
comment on: http://stackoverflow.com/a/51132371
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/51027286
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51027197
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51027197
score: 2
has body: Use cut with parameter right=False for includes the rightmost edges: bins = [-np.inf, .5, .7, .9, np.inf] labels = ['Low', 'Fair', 'Good', 'High'] df['Banding'] = pd.cut(df['score'], bins=bins, labels=labels, right=False) print (df) User score Banding 0 123 0.7355 Good 1 456 0.6074 Fair 2 789 0.9000 High 3 987 0.5000 Fair 4 654 0.0000 Low
downvote count: 0

http://stackoverflow.com/q/51123088
favorite count: 0
has body: I am using the tensorflow, and I feel confused about the tf.where function. As we known, the function include three parameters: cond, x and y. If x and y are both not None, it will return a tensor contains elements that when cond is true return the element of x and cond is false returen the element of y. But, I find the result of the code is confused. The code is below: import tensorflow as tf import numpy as np sess = tf.Session() variable_bool1 = tf.convert_to_tensor(np.array([True, False]), dtype=tf.bool) variable_bool2 = tf.convert_to_tensor(tf.Variable([True, False]), dtype=tf.bool) variable_bool3 = tf.convert_to_tensor(tf.constant([True, False]), dtype=tf.bool) variable_number1 = tf.convert_to_tensor(np.array([1.0, 2.0]), dtype=tf.float32) variable_number2 = tf.convert_to_tensor(np.array([3.0, 4.0]), dtype=tf.float32) where_result1 = tf.where(variable_bool1, variable_number1, variable_number2) where_result2 = tf.where(variable_bool2, variable_number1, variable_number2) where_result3 = tf.where(variable_bool3, variable_number1, variable_number2) sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) print variable_bool1, sess.run(variable_bool1), sess.run([where_result1]) print variable_bool2, sess.run(variable_bool2), sess.run([where_result2]) print variable_bool3, sess.run(variable_bool3), sess.run([where_result3]) And the result present below: Tensor("Const:0", shape=(2,), dtype=bool) [ True False] [array([1., 4.], dtype=float32)] Tensor("Variable/read:0", shape=(2,), dtype=bool) [ True False] [array([0., 0.], dtype=float32)] Tensor("Const_1:0", shape=(2,), dtype=bool) [ True False] [array([1., 4.], dtype=float32)] It seems that the variable_bool2 couldn't return the expected result. Is it a problem about the difference between the Variable and constant? Why do the variable_bool2 always return zero? Could you explain it? Thank you very much!
type: Question
has comment: http://stackoverflow.com/comment/89854098
tagged with: python
has comment: http://stackoverflow.com/comment/89889615
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89883753
answer count: 0
type: UnansweredQuestion
has title: Tensorflow, the parameters of tf.where
downvote count: 0
score: 1

http://stackoverflow.com/q/51121515
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: pycharm
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51122290
linked to: http://stackoverflow.com/q/2218330
has title: Proflie multi-thread python application
type: Question
has body: I'm using Pycharm IDE on a multi thread python application. I tried the default cProfile and the yappi but cannot get results for threads other than the main thread. I'm using python 3.6. Any help?
tagged with: yappi
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89022004
has text: I'm not so familiar with this library, but looking at the Python document, `ET.iterparse()` returns a tuple `(event, elem)` whereas `write` needs to act on an element tree. The docs show that write can be used on the value returned by `ET.parse()`. [Documentation](https://docs.python.org/2/library/xml.etree.elementtree.html)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51014407

http://stackoverflow.com/comment/89094894
has text: Have you considered using a class?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51051894

http://stackoverflow.com/comment/89063638
score: 0
has text: @Dark which updated link?!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51035731

concurrency
tag name: concurrency
type: Tag
tags question: http://stackoverflow.com/q/51071378

http://stackoverflow.com/comment/89255553
score: 0
type: AnswerComment
has text: Yes, that give the correct output that i'm after. Thanks for your help.
type: Comment
comment on: http://stackoverflow.com/a/51135618

http://stackoverflow.com/comment/89123616
type: AnswerComment
score: 0
type: Comment
has text: @ZejiangWang It is hard to believe that by introducing daemon thread it is still not able to reduce loop execution time. Anyway, Have you tried reducing serial write timeout?
comment on: http://stackoverflow.com/a/51064156

http://stackoverflow.com/a/51143657
accepted answer of: http://stackoverflow.com/q/51143210
answers question: http://stackoverflow.com/q/51143210
type: AcceptedAnswer
downvote count: 0
has body: Not sure if this qualifies as "simple", but you can use gather_nd for this: def batched_gather(values, indices): row_indices = tf.range(0, tf.shape(values)[0])[:, tf.newaxis] row_indices = tf.tile(row_indices, [1, tf.shape(indices)[-1]]) indices = tf.stack([row_indices, indices], axis=-1) return tf.gather_nd(values, indices) Explanation: The idea is to construct index vectors such as [0, 1] meaning "the value in the 0th row and 1st column". The column indices are already given in the indices argument to the function. The row indices are a simple progression from 0 to e.g. 128 (in your example), but are repeated (tiled) in accordance with the number of column indices for each row (3 in your example; could hardcode this instead of using tf.shape if this number is fixed). The row and column indices are then stacked to produce the index vectors. In your example, the resulting indices would be array([[[0, 2], [0, 3], [0, 6]], [[1, 0], [1, 2], [1, 3]]]) and gather_nd produces the desired result.
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89273778
upvote count: 1

http://stackoverflow.com/q/51161801
has comment: http://stackoverflow.com/comment/89324160
has comment: http://stackoverflow.com/comment/89307258
favorite count: 0
has comment: http://stackoverflow.com/comment/89368032
has comment: http://stackoverflow.com/comment/89307441
has title: devstack stack.sh fails because of pip package requirements
upvote count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: requirements.txt
tagged with: openstack
score: 2
has comment: http://stackoverflow.com/comment/89506335
answer count: 0
type: Question
has body: I am trying to install OpenStack on Ubuntu-server16.04 using devstack I cloned the stable branch of queens and i have a simple local.conf file when i try to run stack.sh it keeps printing the following warnings while doing some of the work Ignoring EditorConfig: markers 'python_version == "3.4"' don't match your environment Ignoring EditorConfig: markers 'python_version == "3.5"' don't match your environment Ignoring argh: markers 'python_version == "3.4"' don't match your environment Ignoring argh: markers 'python_version == "3.5"' don't match your environment Ignoring blinker: markers 'python_version == "3.4"' don't match your environment Ignoring blinker: markers 'python_version == "3.5"' don't match your environment Ignoring brotlipy: markers 'python_version == "3.4"' don't match your environment Ignoring brotlipy: markers 'python_version == "3.5"' don't match your environment Ignoring cssutils: markers 'python_version == "3.4"' don't match your environment Ignoring cssutils: markers 'python_version == "3.5"' don't match your environment Ignoring dnspython3: markers 'python_version == "3.4"' don't match your environment Ignoring dnspython3: markers 'python_version == "3.5"' don't match your environment Ignoring h2: markers 'python_version == "3.4"' don't match your environment And early on in the install it tells me that i will have an old package glance-store 0.24.0 has requirement oslo.concurrency&gt;=3.26.0, but you'll have oslo-concurrency 3.25.1 which is incompatible. openstacksdk 0.14.0 has requirement keystoneauth1&gt;=3.7.0, but you'll have keystoneauth1 3.4.0 which is incompatible. oslo-vmware 2.30.0 has requirement oslo.concurrency&gt;=3.26.0, but you'll have oslo-concurrency 3.25.1 which is incompatible. And at some point it stops with the following error Obtaining file:///opt/stack/glance Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) F…
has comment: http://stackoverflow.com/comment/89514778
has comment: http://stackoverflow.com/comment/89512911
downvote count: 0
tagged with: virtualenv

http://stackoverflow.com/a/51038689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89088136
has body: You are comparing flower with the first character, not component. Try using: for row in f: cols = row.split(',') if cols[0].strip() == flower: print (cols[1].strip())
type: Answer
accepted answer of: http://stackoverflow.com/q/51038626
answers question: http://stackoverflow.com/q/51038626
has comment: http://stackoverflow.com/comment/89087795
score: 0

http://stackoverflow.com/q/51054844
possible better answer: http://stackoverflow.com/a/51055230
tagged with: dataframe
has answer: http://stackoverflow.com/a/51054932
type: Question
upvote count: 2
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-2.7
has title: Python Pandas | Find maximum value only from a specific part of a column
tagged with: pandas
has answer: http://stackoverflow.com/a/51055230
has body: I have been trying to do this. Pandas max() would find the maximum value from the entire column. What I need is: My input csv file: Id Param1 Param2 Val1 1 -5.00138282776 2.04990620034e-08 1.738e-05 1 -4.80147838593 2.01516989762e-08 1.628e-05 1 -4.60159301758 1.98263165885e-08 1.671e-05 1 -4.40133094788 1.94918392538e-08 1.576e-05 1 -4.20143127441 1.91767686175e-08 2 -5.00141859055 6.88369405921e-09 5.512e-06 2 -4.80152130126 6.77335965093e-09 5.964e-06 2 -4.60163593292 6.65415056389e-09 3 -5.00138044357 1.16316911658e-08 4.008e-06 3 -4.80148792267 1.15515588206e-08 7.347e-06 3 -4.60160970681 1.14048361866e-08 8.446e-06 3 -4.40137386322 1.12357021465e-08 Output needed: Id Param1 Param2 Val1 Max_Val1_for_each_Id 1 -5.00138282776 2.04990620034e-08 1.738e-05 1.738e-05 1 -4.80147838593 2.01516989762e-08 1.628e-05 1 -4.60159301758 1.98263165885e-08 1.671e-05 1 -4.40133094788 1.94918392538e-08 1.576e-05 1 -4.20143127441 1.91767686175e-08 2 -5.00141859055 6.88369405921e-09 5.512e-06 5.964e-06 2 -4.80152130126 6.77335965093e-09 5.964e-06 2 -4.60163593292 6.65415056389e-09 3 -5.00138044357 1.16316911658e-08 4.008e-06 8.446e-06 3 -4.80148792267 1.15515588206e-08 7.347e-06 3 -4.60160970681 1.14048361866e-08 8.446e-06 3 -4.40137386322 1.12357021465e-08 I am not sure how to select/group values from Val1 column with the same Id and then find their maximum value. Also, I have some blanks in the Val1 column, rendering its datatype as object. I don't know how to go about this. Any help would be most welcome.
tagged with: python
accepted answer: http://stackoverflow.com/a/51054932
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89080077
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51044336
type: AnswerComment
has text: Maybe this answer will shed light on the issue :)

http://stackoverflow.com/comment/89278141
has text: The delimiters are tab delimited.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51146867

http://stackoverflow.com/comment/89144953
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51062458
has text: result.group('islive').lower().encode('utf8') == "u'na'", since the string is u'na' and not na

http://stackoverflow.com/q/51066742
score: 0
accepted answer: http://stackoverflow.com/a/51071746
tagged with: python
linked to: http://stackoverflow.com/q/21406057
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51071746
type: Question
has body: I have a simple Route in Flask where I want to add and remove items to a Session dictionary list value. Adding things to it is fine but it doesn't seem to remove the items. I've tried adding session.modified = True but that doesn't seem to have helped. What am I doing wrong? @app.route('/todo/&lt;profile_id&gt;') def todo(profile_id): kw = request.args.get('kw', None) lp = request.args.get('lp', None) # remove if it exists try: session[lp].pop(kw) session.modified = True return True except: pass # add if it doesn't exist if kw and lp: try: session[lp].append(kw) except: session[lp] = [kw] return '{}'.format(session[lp])
has title: Nested List Item not removing from Flask Session
answer count: 1
tagged with: flask

http://stackoverflow.com/comment/89174208
comment on: http://stackoverflow.com/q/51093022
type: Comment
score: 1
has text: Basically, if you need precise arithmetic don't use `float`s. Instead, use something like the [`decimal`](https://docs.python.org/3/library/decimal.html) module.
type: QuestionComment

http://stackoverflow.com/comment/89030335
score: 0
type: AnswerComment
type: Comment
has text: @AbdulRehman The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads.
comment on: http://stackoverflow.com/a/51017434

http://stackoverflow.com/comment/89314250
type: AnswerComment
has text: @JimDeLaHunt Oh I should have said "`create_connection()` ... creates a streaming transport, which is a TCP connection **in this case**". I agree with you that stream is more generic than just TCP. And actually `create_connection()` may also be used to create UNIX domain sockets, by passing in a `sock` instance initialized with `AF_UNIX`, it is just not a traditional usage though with `create_unix_connection()` present. The implication in this documentation is: it is creating a streaming transport with **socket**.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51112207

http://stackoverflow.com/q/51124516
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: python requests POST with header and parameters
tagged with: python
tagged with: request
linked to: http://stackoverflow.com/q/10768522
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51124572
has comment: http://stackoverflow.com/comment/89234111
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/51124572
type: Question
has body: I have a post request which I am trying to send using requests in python. But I get an invalid 403 error. The requests works fine through the browser. POST /ajax-load-system HTTP/1.1 Host: xyz.website.com Accept: application/json, text/javascript, */*; q=0.01 Accept-Language: en-GB,en;q=0.5 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0 Referer: http://xyz.website.com/help-me/ZYc5Yn Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Content-Length: 56 Cookie: csrf_cookie_name=a3f8adecbf11e29c006d9817be96e8d4; ci_session=ba92hlh6o0ns7f20t4bsgjt0uqfdmdtl; _ga=GA1.2.1535910352.1530452604; _gid=GA1.2.1416631165.1530452604; _gat_gtag_UA_21820217_30=1 Connection: close csrf_test_name=a3f8adecbf11e29c006d9817be96e8d4&amp;vID=9999 What I am trying in python is: import requests import json url = 'http://xyz.website.com/ajax-load-system' payload = { 'Host': 'xyz.website.com', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-GB,en;q=0.5', 'Referer': 'http://xyz.website.com/help-me/ZYc5Yn', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'Content-Length': '56', 'Cookie': 'csrf_cookie_name=a3f8adecbf11e29c006d9817be96e8d4; ci_session=ba92hlh6o0ns7f20t4bsgjt0uqfdmdtl; _ga=GA1.2.1535910352.1530452604; _gid=GA1.2.1416631165.1530452604; _gat_gtag_UA_21820217_30=1', 'Connection': 'close', 'csrf_test_name': 'a3f8adecbf11e29c006d9817be96e8d4', 'vID': '9999', } headers = {} r = requests.post(url, headers=headers, data=json.dumps(payload)) print(r.status_code) But this is printing a 403 error code. What am I doing wrong here? I am expecting a return response as json: {"status_message":"Thanks for help.","help_count":"141","status":true}
tagged with: post
upvote count: 4
linked to: http://stackoverflow.com/q/53721153
score: 0
downvote count: 4
has comment: http://stackoverflow.com/comment/89234105

http://stackoverflow.com/comment/89114302
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51039271
has text: Possible duplicate of [Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)
score: 0

http://stackoverflow.com/q/51033858
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Extract a string from a CSV cell containing special characters in Python
type: Question
has body: I'm writing a Python program to extract specific values from each cell in a .CSV file column and then make all the extracted values new columns. Sample column cell:(This is actually a small part, the real cell contains much more data) AudioStreams":[{"JitterInterArrival":10,"JitterInterArrivalMax":24,"PacketLossRate":0.01353227,"PacketLossRateMax":0.09027778,"BurstDensity":null,"BurstDuration":null,"BurstGapDensity":null,"BurstGapDuration":null,"BandwidthEst":25245423,"RoundTrip":520,"RoundTripMax":11099,"PacketUtilization":2843,"RatioConcealedSamplesAvg":0.02746676,"ConcealedRatioMax":0.01598402,"PayloadDescription":"SIREN","AudioSampleRate":16000,"AudioFECUsed":true,"SendListenMOS":null,"OverallAvgNetworkMOS":3.487248,"DegradationAvg":0.2727518,"DegradationMax":0.2727518,"NetworkJitterAvg":253.0633,"NetworkJitterMax":1149.659,"JitterBufferSizeAvg":220,"JitterBufferSizeMax":1211,"PossibleDataMissing":false,"StreamDirection":"FROM-to- One value I'm trying to extract is number 10 between the "JitterInterArrival": and ,"JitterInterArrivalMax" . But since each cell contains relatively long strings and special characters around it(such as ""), opener=re.escape(r"***")and closer=re.escape(r"***") wouldn't work. Does anyone know a better solution? Thanks a lot!
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51033933
accepted answer: http://stackoverflow.com/a/51033933
favorite count: 0
tagged with: extract
tagged with: python
tagged with: regex

http://stackoverflow.com/q/51094138
tagged with: python
tagged with: utf-8
tagged with: templates
has body: I'm trying create a web app using django with python and the jupyter notebook environment. I am following the tutorial on djangoproject website : https://docs.djangoproject.com/en/2.0/intro/tutorial03/ When I try to load a template in the views file of my project, I get the following error : 'utf-8' codec can't decode byte 0xe9 in position 19983: invalid continuation byte. Here is the part of the code where I call the file : def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) After some research, I found out that a file : mysite/polls/templates/polls/index_fichiers/themedata.thmx gives me the following message when I try to open it in jupyter : Error ! mysite/polls/templates/polls/index_fichiers/themedata.thmx is not UTF-8 encoded. Saving disabled. See Console for more details. In my console : 400 GET /api/contents/polls/templates/polls/index_fichiers/themedata.thmx?type=file&amp;format=text&amp;_=1530244665665 (::1) 4.00ms referer=http://localhost:8888/edit/polls/templates/polls/index_fichiers/themedata.thmx I tried to convert this file in UTF-8 by opening it in a text document and saving it with a UTF-8 encoding, but it still have the same message. I tried to add an argument : encoding='UTF-8' to the get_template fonction, but "encoding" is not a keyword argument for it. Does someone know what I should try ? Maybe change the encoding parameters of my files ? (but I don't know how to do that) Thanks !
answer count: 0
has comment: http://stackoverflow.com/comment/89179740
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89177809
tagged with: django
type: Question
tagged with: encoding
has title: Django : "'utf-8' codec can't decode byte 0xe9 in position 19983: invalid continuation byte" when loading a template
score: 0

http://stackoverflow.com/q/51110925
has comment: http://stackoverflow.com/comment/89213700
accepted answer: http://stackoverflow.com/a/51113947
answer count: 1
has comment: http://stackoverflow.com/comment/89213726
has comment: http://stackoverflow.com/comment/89213525
tagged with: python
has comment: http://stackoverflow.com/comment/89209012
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89213681
has comment: http://stackoverflow.com/comment/89213694
has answer: http://stackoverflow.com/a/51113947
has comment: http://stackoverflow.com/comment/89208887
tagged with: scipy
has title: Fit data within two function bounds
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89213747
has body: I have a set of data which, according to a theory, is bounded within two bounds. The upper bound is : f(x)=1/x (x&lt;0.5) The lower bound is : f(x)=1+1/(2x)(x&lt;0.5) The data I got is close to one of these two bounds. I’m trying to find a function to describe these data. But if I use normal fitting method, the fitted curve can be outside of these two bounds. How can I force my fitted curve between these two bounds by using scipy.curve_fit? I'm trying to use Pade approximant to do the fitting, the code I'm using is following: def pfuncp_3_1(x, a0, a1, a2, a3, b1): p1 = ((a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1)-1-1/(2*x)&lt;0)*2.0 p2 = ((a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1)-1/x&gt;0)*2.0 return (a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1) + p1 + p2 def ffuncp_3_1(x, a0, a1, a2, a3, b1): return (a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1) def data_fitter(pfunc, ffunc, fit_x, fit_y, new_x): popt, pcov = opt.curve_fit(pfunc, fit_x, fit_ny) perr = np.sqrt(np.diag(pcov)) interp_y = np.zeros(len(interp_x)) for k in range(len(interp_x)): interp_y[k] = ffunc(interp_x[k], *popt) return interp_y if __name__ == "__main__": results = data_fitter(pfunc, ffunc, original_x, original_y, interpx)
score: 0

http://stackoverflow.com/comment/89322659
has text: Any solution without using pandas?
type: Comment
comment on: http://stackoverflow.com/a/51169336
score: 0
type: AnswerComment

http://stackoverflow.com/a/68393616
has body: Step 1:- Import Module. Step 2:- Create splash screen. step 3:- Set title and geometry for splash screen. step 4:- Insert photo file name to be display. step 5:- Create Label and Pack the Label. # Import Module from tkinter import * splash = Tk() splash.title("Welcome") # assigning title for splash screen splash.geometry("800x750+300+100") # set geometry for splash screen splash.after(4000, splash.destroy) # splash screen will destroy after 4 sec bg = PhotoImage(file = "file_name.png") # insert file name to be display lab = Label(splash, image = bg) # create label lab.pack() # pack the label splash.mainloop()
score: 0
answers question: http://stackoverflow.com/q/51106995
type: Answer
has comment: http://stackoverflow.com/comment/120894260

http://stackoverflow.com/q/51141955
answer count: 1
has answer: http://stackoverflow.com/a/51142467
has title: Python realtime plot, re-update
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51142467
tagged with: python
tagged with: plot
score: 0
tagged with: matplotlib
has body: I want to have two plots (#1, #2). I want to update the plot #1 as data is coming up, and then update plot #2 as well. After this, I might want to go back and update plot #1. However, I am unable to update plot #1. Any help? Here are my source code. import matplotlib.pyplot as plt import numpy as np a = np.random.random(10) b = np.random.random(10) plt.subplot(311) for i in range (10): y = a[i] x = b[i] plt.scatter(x,y) plt.pause(0.05) plt.subplot(312) for i in range (10): x = a[i] y = b[i] plt.scatter(x,y) plt.pause(0.05) # update plot #1, but this doesn't work aa = np.random.random(20) bb = np.random.random(20) plt.subplot(311) for i in range (20): y = aa[i] x = bb[i] plt.scatter(x,y) plt.show()

http://stackoverflow.com/comment/89128959
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51069204
has text: I want exponential axes. So the opposite effect of logscale.
score: 0

http://stackoverflow.com/q/51050082
tagged with: regex
tagged with: parsing
has comment: http://stackoverflow.com/comment/89091230
type: UnansweredQuestion
has title: Parse through list in python for string that starts with certain characters and is length N
tagged with: python
has answer: http://stackoverflow.com/a/51050155
has comment: http://stackoverflow.com/comment/89091582
linked to: http://stackoverflow.com/q/1427107
type: Question
has answer: http://stackoverflow.com/a/51050097
score: 0
answer count: 2
has body: I tried to emulate this Find strings of length 10 with regex with this for char in updated_metabolite: found_all = re.findall('^cpd.{5}$', updated_metabolite) the list updated_metabolites looks like this before running the above code: cpd00001;cpd00009;cpd00015;cpd00041;cpd00095;cpd00982;cpd02333 cpd00001;cpd00003;cpd00004;cpd00067;cpd00075;cpd00985 cpd00003;cpd00004;cpd00067;cpd15560;cpd15561 cpd00005;cpd00006;cpd00067;cpd14938;cpd17051 cpd00001;cpd00002;cpd00003;cpd00004;cpd00008;cpd00009;cpd00067;cpd00149;cpd03913;cpd03914 cpd00005;cpd00006;cpd11669;cpd17097 cpd00005;cpd00006;cpd00067;cpd00129;cpd02431 cpd00001;cpd00015;cpd00067;cpd00129;cpd00858;cpd00982 cpd00005;cpd00006;cpd00011;cpd00017;cpd00060;cpd00067;cpd00791;cpd02083;cpd03091;

http://stackoverflow.com/comment/89123169
score: 0
type: Comment
has text: J.J Thanks for your attention. Well, the data send from PC to robot car goes through an RFID hardware whose maximal baudrate is 19200. This is a hard constraint.
comment on: http://stackoverflow.com/a/51064156
type: AnswerComment

argparse
tags question: http://stackoverflow.com/q/51071358
tags question: http://stackoverflow.com/q/51144970
tags question: http://stackoverflow.com/q/51030971
tags question: http://stackoverflow.com/q/51104674
tags question: http://stackoverflow.com/q/51085465
tags question: http://stackoverflow.com/q/51029193
tag name: argparse
tags question: http://stackoverflow.com/q/51036964
tags question: http://stackoverflow.com/q/51113866
tags question: http://stackoverflow.com/q/51019956
type: Tag

http://stackoverflow.com/a/51127381
upvote count: 1
has body: The problem was solved by executing the program using spyder.exe (an IDE included in WinPython). It wasn't working before because I was trying to execute the program directly by the Python interpreter installed on my USB flash drive.
downvote count: 0
answers question: http://stackoverflow.com/q/51126979
type: Answer
score: 1

http://stackoverflow.com/a/51070358
type: Answer
has comment: http://stackoverflow.com/comment/89131546
has comment: http://stackoverflow.com/comment/89131407
answers question: http://stackoverflow.com/q/51069231
score: 0
has body: I modified your code and it works: import csv import unicodecsv input_filename = 'test.csv' input_headers = ['ID', 'Search Company', 'Past Job Title 1', 'Past Job Title 2', 'Past Job Title 3'] output_headers = ['ID', 'Search Company', 'Consolidated Company', 'Past Job Title 1', 'Past Job Title 2', 'Past Job Title 3'] #set up the file writer out_employees_file = open('consolidated_' + input_filename, 'wb') employees_writer = unicodecsv.DictWriter(out_employees_file, lineterminator='\n', escapechar='\\', fieldnames=output_headers) #set up the file reader employees_file = open(input_filename, 'r', encoding='utf-8') employees_reader = csv.reader(employees_file, delimiter=',') rows = [] for row in employees_reader: consolidated_name = '' if 'Search Company' != row[1]: if row[1] in row[2]: consolidated_name = row[2] if row[1] in row[3]: consolidated_name = row[3] if row[1] in row[4]: consolidated_name = row[4] r = {'ID': row[0], 'Search Company': row[1], 'Consolidated Company': consolidated_name, 'Past Job Title 1': row[2], 'Past Job Title 2': row[3], 'Past Job Title 3': row[4]} rows.append(r) employees_writer.writerows(rows) You did not wrote the second row in your version (Searched company) and you had at least a type in the if condition: if 'Searched Company' != row[1]: But the row is called 'Search Company'. You missed the "ed". I think, that was the main reason for your problem. Also you should collect the rows and write them with .writerows(). My Output: 1,Good Company,Good Company,Bad Company,Horrid Cmp LLC,Good Company 2,Good Company,Good Company,Good Company,Rotten Company,Stupid Compny 3,Good Company,Good Company,Stinky Company,Good Company,Company Malo I discarded the headers, I know... Edit: To include the headers, add employees_writer.writer.writerow(output_headers) just before employees_writer.writerows(rows)

http://stackoverflow.com/comment/89278588
score: 1
comment on: http://stackoverflow.com/q/51147176
type: Comment
type: QuestionComment
has text: can you write your formulas correctly?

http://stackoverflow.com/q/51039164
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89070766
has body: I have a scenario like Process1 and Process2 want to access same python file(sample.py). With respect to each process some code snippet is written. I don't want Process1 to access Process2 related python code and vice versa. Process A from myapp1 import ABC Process B from myapp2 import DEF from myapp1 import ABC should not be accessible in Process B and from myapp2 import DEF should not be accessible in Process A Update: Fixed this issue by introducing environment variable in Process A and checking at sample.py. Fix: In manage.py(Process A) added os.environ.setdefault("CS_DJANGO_MODULE", "1") In sample.py, added following code CS_DJANGO = os.environ.get('CS_DJANGO_MODULE') if CS_DJANGO == "1": from myapp1 import ABC else: from myapp2 import DEF
has title: Two processes want to access same python file
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89071357
score: 0
has comment: http://stackoverflow.com/comment/89069960
tagged with: python
has comment: http://stackoverflow.com/comment/89070211
answer count: 0

http://stackoverflow.com/q/51120058
has title: adding a legend to animated scatterplot
tagged with: scatter-plot
upvote count: 4
accepted answer: http://stackoverflow.com/a/51129350
linked to: http://stackoverflow.com/q/41191273
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/35677980
favorite count: 0
has body: I am building an animation with a scatter plot showing data for multiple groups over time. When I want to add a legend, the best I could get only shows one group. sample dataset: import pandas as pd df = pd.DataFrame([ [1, 'a', 0.39, 0.73], [1, 'b', 0.87, 0.94], [1, 'c', 0.87, 0.23], [2, 'a', 0.17, 0.37], [2, 'b', 0.03, 0.12], [2, 'c', 0.86, 0.22], [3, 'a', 0.01, 0.15], [3, 'b', 0.03, 0.1], [3, 'c', 0.29, 0.19], columns=['period', 'group', 'x', 'y'] ) I build my animation like this: import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() ax.set_xlim(0, 1) ax.set_ylim(0, 1) colors = { 'a': 'r', 'b': 'b', 'c': 'g' } scat = ax.scatter([], [], c=df['group'].map(colors), ) def init(): scat.set_offsets([]) return scat, def update(period): scat.set_offsets(df[df['period'] == period]'x', 'y') scat.set_label(df[df['period'] == period]['group']) ax.legend([scat], df['group'].unique().tolist(), loc=1) ax.set_title(period) return scat, ani = animation.FuncAnimation(fig, update, init_func=init, frames=[1,2,3,4,5], interval=500, repeat=True) plt.show() I get only group a showing up in the legend. If I only type ax.legend(loc=1), It shows something that looks like this: 6 a 7 b 8 c Name: group, dtype:object The numbers change in each frame. I already checked those answers: How do I get this to show the legend on the plot?: got me where I am now. How to add legend/label in python animation: I get UnboundLocalError: local variable 'legend' referenced before assignment on legend.remove() Add a legend for an animation (of Artists) in matplotlib: only shows group a.
tagged with: python-3.x
tagged with: animation
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41508888
has answer: http://stackoverflow.com/a/51129350
type: Question
tagged with: matplotlib
score: 4

http://stackoverflow.com/a/51211958
score: 3
has body: You need to tell nbconvert to look for your template by creating an jupyter_nbconvert_config.py file and storing it in ~/.jupyter. I use this for LaTeX--here's what my file looks like: import os c = get_config() c.LatexExporter.template_path = ['.', os.path.expanduser('~/.jupyter/templates')] c.LatexExporter.template_file = 'custom_latex.tplx' Assuming you template extends an existing one, you need to include '.' when setting template_path so it knows where to look for the standard templates.
accepted answer of: http://stackoverflow.com/q/51137110
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51137110
upvote count: 3
has comment: http://stackoverflow.com/comment/113428264
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89132962
type: QuestionComment
has text: It actually looks like you want to remove elements that appear exactly 4 times in your list. If so, you can follow a similar route to [this answer](https://stackoverflow.com/a/26773120/5858851).
score: 0
comment on: http://stackoverflow.com/q/51071513
type: Comment

http://stackoverflow.com/comment/89507396
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51143556
has text: @swigganicks looks like you have provided a proper answer in comments. Would you like to post it as such and earn some points?

http://stackoverflow.com/comment/89157277
score: 0
type: QuestionComment
type: Comment
has text: @cricket_007, i read the example and guessed the result. but it is not the same as i thought. And i couldn't understand..
comment on: http://stackoverflow.com/q/51084036

http://stackoverflow.com/q/51070397
has title: Python equivalent of MATLAB function findchangepts
answer count: 3
has answer: http://stackoverflow.com/a/51162198
tagged with: python
has comment: http://stackoverflow.com/comment/89131883
favorite count: 0
accepted answer: http://stackoverflow.com/a/51162198
downvote count: 1
tagged with: matlab
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/60506166
has comment: http://stackoverflow.com/comment/89133406
has answer: http://stackoverflow.com/a/60506166
has body: I need a python equivalent of the MATLAB command findchangepts . I am unable to find one yet. Essentially I want to find K abrupt changes in my time series. I am able to use the matlab command but unable to find an equivalent function in python. Any help/pointers to existing libraries will be very helpful. I am not proficient in the optimization modules of scipy and thus would prefer an existing python package. Thanks.
has answer: http://stackoverflow.com/a/78174119
tagged with: scipy
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/89300925
has comment: http://stackoverflow.com/comment/89135369

http://stackoverflow.com/comment/93675035
score: 2
has text: You can install tornado with conda, like this `conda install tornado`, so you need to do that instead of using pip. That's because pip and conda are not interchangeable. I'd also suggest to update your answer and change pip for conda.
comment on: http://stackoverflow.com/a/53380958
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51041835
has body: Problem here is that iqoptionapi/ws/chanels/candles.py module from latest PyPI version differs from Github's master branch version and there is no amount parameter (it seems to be equal to 2). In master branch: def __call__(self, active_id, duration, amount): ... "from": self.api.timesync.server_timestamp - (duration * amount), ... In 0.5 version: def __call__(self, active_id, duration): ... "from": self.api.timesync.server_timestamp - (duration * 2), ... So we can ignore this parameter (do not pass it at all and use default value 2) or install master branch version using git like &gt; pip install --upgrade git+https://github.com/n1nj4z33/iqoptionapi.git@master Here we are using --upgrade flag since version didn't change so we force to reinstall package. Or another option: you can ask repo owner to release new version and publish it on PyPI.
accepted answer of: http://stackoverflow.com/q/51039974
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51039974
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89075660
upvote count: 2

http://stackoverflow.com/comment/89154733
type: QuestionComment
has text: Make your question a little more specific, what is the change you want to make to your model?
score: 0
comment on: http://stackoverflow.com/q/51081200
type: Comment

http://stackoverflow.com/q/51117323
has comment: http://stackoverflow.com/comment/89221433
accepted answer: http://stackoverflow.com/a/51117626
tagged with: tkinter
has body: I have two python programs in same folder named main.py and tk_version.py I am importing main.py in tk_version.py I have a variable in main.py which has default value lets say 'xyz' Now in tk_version.py I am taking the value for the variable from user using Tkinter GUI. So what I want is when main.py is executed the constant value must be taken and when tk_version.py is executed the value given by user override the default value. Example: main.py var="default" def show(): print(var) if __name__ == '__main__': show() tk_version.py from tkinter import * import main Main = Tk() var= StringVar() def e1chk(): global var var = e1.get() main.show() return e1=Entry(Main,textvariable=var,width=50) e1.grid(row=0,column=5,sticky=NSEW) b1=Button(Main,text="Save",command=e1chk) b1.grid(row=0,column=8,sticky=NSEW) Main.mainloop() OUTPUT for main.py &gt;&gt;&gt; =============== RESTART: C:/Users/Gupta Niwas/Desktop/main.py =============== default &gt;&gt;&gt; OUTPUT for tk_version.py (I have entered "abc" in Entry box) &gt;&gt;&gt; ============ RESTART: C:/Users/Gupta Niwas/Desktop/tk_version.py ============ default &gt;&gt;&gt; I want variable to be StringVar to control the entry box values.
tagged with: python
has comment: http://stackoverflow.com/comment/89228848
has comment: http://stackoverflow.com/comment/89221190
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51117626
has title: Python: How to change data type and override a variable from imported module
type: Question
score: 0
answer count: 1

facebook
tags question: http://stackoverflow.com/q/51041998
type: Tag
tags question: http://stackoverflow.com/q/51091402
tags question: http://stackoverflow.com/q/51022550
tag name: facebook
tags question: http://stackoverflow.com/q/51148933
tags question: http://stackoverflow.com/q/51031479
tags question: http://stackoverflow.com/q/51153571

http://stackoverflow.com/a/51066356
answers question: http://stackoverflow.com/q/51066245
downvote count: 0
has body: I want to use pycuda to accelerate the fft You can't. PyCUDA has no built-in FFT support of any kind.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89291186
comment on: http://stackoverflow.com/q/51045222
has text: @Cukic0d: Indeed, the payload seems to make the trouble. If I remove it or if I trim it down to four bytes (so that the resulting packet is 60 bytes long) then wireshark seems to be happy.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51121647
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/70920396
has title: Get the current contents of the entire Jupyter Notebook
has answer: http://stackoverflow.com/a/51127026
possible better answer: http://stackoverflow.com/a/70920396
has answer: http://stackoverflow.com/a/79291290
has body: I have a Jupyter Notebook running. I want to be able to access the source of the current Jupyter Notebook from within Python. My end goal is to pass it into ast.parse so I can do some analysis on the user's code. Ideally, I'd be able to do something like this: import ast ast.parse(get_notebooks_code()) Obviously, if the source code was an IPYNB file, there'd be an intermediary step of extracting the code from the Python cells, but that's a relatively easy problem to solve. So far, I've found code that will use the list_running_servers function of the IPython object in order to make a request and match up kernel IDs - this gives me the filename of the currently running notebook. This would work, except for the fact that the source code on disk may not match up with what the user has in the browser (until you save a new checkpoint). I've seen some ideas involving extracting out data using JavaScript, but that requires either a separate cell with magic or calling the display.Javascript function - which fires asynchronously, and therefore doesn't allow me to pass the result to ast.parse. Anyone have any clever ideas for how to dynamically get the current notebooks source code available as a string in Python for immediate processing? I'm perfectly fine if I need to make this be an extension or even a kernel wrapper, I just need to get the source code somehow.
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78528307
downvote count: 0
linked to: http://stackoverflow.com/q/12544056
accepted answer: http://stackoverflow.com/a/51127026
score: 6
linked to: http://stackoverflow.com/q/54350254
has comment: http://stackoverflow.com/comment/103341281
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/32237275
upvote count: 6

http://stackoverflow.com/comment/89237739
comment on: http://stackoverflow.com/q/51124540
score: 0
has text: ops, yes, i meant "consecutively", thank you Matt
type: Comment
type: QuestionComment

openpyxl
tags question: http://stackoverflow.com/q/51165213
tags question: http://stackoverflow.com/q/51090140
tags question: http://stackoverflow.com/q/51145253
tags question: http://stackoverflow.com/q/51135083
tags question: http://stackoverflow.com/q/51065715
tags question: http://stackoverflow.com/q/51148377
tags question: http://stackoverflow.com/q/51071844
tags question: http://stackoverflow.com/q/51137050
type: Tag
tags question: http://stackoverflow.com/q/51044736
tags question: http://stackoverflow.com/q/51014201
tags question: http://stackoverflow.com/q/51147054
tags question: http://stackoverflow.com/q/51156666
tag name: openpyxl
tags question: http://stackoverflow.com/q/51122855
tags question: http://stackoverflow.com/q/51144889
tags question: http://stackoverflow.com/q/51127382
tags question: http://stackoverflow.com/q/51048294
tags question: http://stackoverflow.com/q/51068361
tags question: http://stackoverflow.com/q/51127228
tags question: http://stackoverflow.com/q/51082458
tags question: http://stackoverflow.com/q/51091580

http://stackoverflow.com/comment/89089772
score: 0
has text: That doesn't seem to help. It does change the shape from the original training loss spikes a bit, but it is still periodic with roughly the same peeks. Adding `train_set.skip(n)`, changed the shape much more dramatically (as my data is stored like a video sequence), however it is still periodic.
comment on: http://stackoverflow.com/a/51047144
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89170318
type: QuestionComment
comment on: http://stackoverflow.com/q/51090434
score: 1
has text: The series starts `1, 1, 2, 3, 5, 8`. If you enter `4` it will never stop and eventually fill up the output file.
type: Comment

http://stackoverflow.com/q/51125571
type: Question
tagged with: seaborn
has comment: http://stackoverflow.com/comment/89238701
tagged with: python
has body: I just started with a tutorial on Seaborn from a book; 'Python Data Science Handbook'. When I execute the part about adding a legend to the plot, the plot figures goes blank. I entered these lines of code one by one in my Spyder console import matplotlib.pyplot as plt import numpy as np rng = np.random.RandomState(0) x = np.linspace(0, 10, 500) y = np.cumsum(rng.randn(500, 6), 0) plt.plot(x, y) Then followed by plt.legend('ABCDEF', ncol=2, loc='upper left'); Can't understand why the plot figure goes blank. And I have the latest version of Seaborn installed.
has comment: http://stackoverflow.com/comment/89236302
has comment: http://stackoverflow.com/comment/89238577
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51141947
has comment: http://stackoverflow.com/comment/89237234
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89236231
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51141947
has title: Seaborn plot goes blank when adding legend

http://stackoverflow.com/comment/89185070
score: 0
type: Comment
has text: _“to avoid creating a connection with a harmful website”_ - why? In what way to do imagine any “harmful website” could actually do any damage to your python script?
type: QuestionComment
comment on: http://stackoverflow.com/q/51098782

http://stackoverflow.com/q/51079150
favorite count: 0
type: Question
tagged with: python-asyncio
possible better answer: http://stackoverflow.com/a/51079550
has answer: http://stackoverflow.com/a/51079550
answer count: 2
score: 5
tagged with: python
has body: I am lacking understanding on how Python asyncio and protocols are working. Documentaion that seems relevant: class asyncio.Protocol Protocol.eof_received() state machine shows relevant transitions AbstractEventLoop.run_until_complete(future) Example code that is echo tcp client: import asyncio class EchoClientProtocol(asyncio.Protocol): def __init__(self, message, loop): self.message = message.encode() def connection_made(self, transport): self.transport = transport self.write_data() def data_received(self, data): print('Data received: {!r}',len(data)) self.write_data() def eof_received(self): print("eof") return True def write_data(self): print("write") self.transport.write(self.message) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') loop = asyncio.get_event_loop() message = 'Hello World!' coro = loop.create_connection(lambda: EchoClientProtocol(message, loop), '127.0.0.1', 5676) loop.run_until_complete(coro) print("done") Output when connceted on echo server: write Data received: {!r} 12 write done From what I understand this should run until connection is closed. From: Connection callbacks connection_made() and connection_lost() are called exactly once per successful connection. All other callbacks will be called between those two methods, which allows for easier resource management in your protocol implementation. and from also state machine: start -&gt; connection_made [-&gt; data_received]* [-&gt; eof_received]? -&gt; connection_lost -&gt; end But, function EchoClientProtocol.connection_lost is never called and loop.run_until_complete(coro) terminates before Protocol completes. Question is: How to get coroutine/future that wraps protocol in a way that coroutine completes when end state of protocol is reached and loop.run_until_complete returns on such event.
has answer: http://stackoverflow.com/a/51089229
upvote count: 5
type: AnsweredQuestion
downvote count: 0
has title: Understanding python asyncio Protocol
accepted answer: http://stackoverflow.com/a/51089229

http://stackoverflow.com/a/51050203
answers question: http://stackoverflow.com/q/51050066
has body: There are 16 posibilities, it means i need to write 16 if statements! No!, not if these parameters act more or less independent. We can for example first abstract common logic away: def add_custom_filters(qs, direction, strtype, city, province): if direction: qs = qs.filter(strdir=direction) if strtype: qs = qs.filter(strype=strtype) if city: qs = qs.filter(strcity=city) if privince: qs = qs.filter(strprov=privince) return qs (might need some altering) So now we can use this logic like: queryset = address.objects.filter(addline__startswith=keyword) queryset = add_custom_filters(queryset, direction, strtype, city, province)[:10] if not queryset: queryset = address.objects.filter(strname__startswith=keyword) queryset = add_custom_filters(queryset, direction, strtype, city, province)[:10] return queryset We thus only need four if cases, and we reuse this function for the two-attempt approach. Since filtering if not truthiness is True is a common pattern, we can encapsulate this in a helper function: def filter_if_truthfull(qs, **kwargs): retrurn qs.filter(**{k: v for k, v in kwargs.items() if v}) then we can use it like: queryset = address.objects.filter(addline__startswith=keyword) queryset = filter_if_truthfull(queryset, strdir=direction, strtype=strtype, strcity=city, strprov=province)[:10] if not queryset: queryset = address.objects.filter(strname__startswith=keyword) queryset = filter_if_truthfull(queryset, strdir=direction, strtype=strtype, strcity=city, strprov=province)[:10] return queryset This allows us to add an arbitrary amount of named filter criteria that are only applied in case the value has truthiness true (for a string, this happens if the string not empty, in case it is None, it is not a string, but these filters are also not considered). In case you are going to use the results of a QuerySet anyway, it is better to check if queryset, since this will perform a query, that loads the elements into the queryset as well, whereas .exists() will query with…
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/89187172
comment on: http://stackoverflow.com/a/51095966
type: AnswerComment
type: Comment
has text: Not clear the problem as you are asking a way to display F-statistics. However, if you need to run ANOVA with more details than your output, you can try, print(mt_model1.summary())
score: 0

http://stackoverflow.com/q/51011754
favorite count: 0
type: Question
tagged with: python
score: 1
tagged with: xpath
tagged with: selenium
has comment: http://stackoverflow.com/comment/89016320
accepted answer: http://stackoverflow.com/a/51011917
upvote count: 1
has body: I hope a kind soul can help me here. I need help with clicking the next page on this site: https://www.xtip.co.uk/en/today/index.html. My code: from selenium import webdriver url = 'https://www.xtip.co.uk/en/today/index.html' browser = webdriver.Chrome('./Browser/chromedriver') browser.get(url) amount_of_pages_xpath = browser.find_element_by_xpath('//*[@id="widget_today_tabbed"]/div[2]/div[2]/div') amount_of_pages_html = amount_of_pages_xpath.get_attribute('data-number-of-pages') for x in range(len(amount_of_pages_html)): browser.find_element_by_xpath('//*[@id="widget_today_tabbed"]/div[2]/div[2]/div/ul/li[8]/a').click() It uses JavaScript and AJAX and therefore I use Selenium, but I can't make it switch pages. What am I doing wrong? Normally it works when I go to Chrome -> Inspect -> Copy Xpath -> Put this path into find_element_by_xpath() and add click(). My error in console: selenium.common.exceptions.WebDriverException: Message: unknown error: Element &lt;a href="#" class="widget-page-link widget-page-link-next" data-target-page="next"&gt;...&lt;/a&gt; is not clickable at point (917, 654). Other element would receive the click: &lt;div class="cc_message"&gt;...&lt;/div&gt; (Session info: chrome=67.0.3396.87) (Driver info: chromedriver=2.38.552518 (183d19265345f54ce39cbb94cf81ba5f15905011),platform=Mac OS X 10.13.5 x86_64)
answer count: 1
has title: Python: Click next page with no link to follow (javascript/AJAX)
has comment: http://stackoverflow.com/comment/89016507
has comment: http://stackoverflow.com/comment/89016403
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/16788310
has comment: http://stackoverflow.com/comment/89016422
has answer: http://stackoverflow.com/a/51011917

http://stackoverflow.com/comment/89277442
type: AnswerComment
type: Comment
has text: This helps a lot, but any idea how to convert `⒍` to a integer or even a float?
comment on: http://stackoverflow.com/a/51146679
score: 0

http://stackoverflow.com/q/51108600
has answer: http://stackoverflow.com/a/51108743
tagged with: group-by
score: 0
tagged with: filter
tagged with: pandas
answer count: 1
has title: Pandas - Loop through groupby df and filter by intersection
has comment: http://stackoverflow.com/comment/89204423
type: UnansweredQuestion
has body: I am having trouble combining the following steps in Pandas: I have snapshots by date from 2 entities. I have found the intersection of objects between the 2 entities for each date, and these objects are stored in a list of lists (one sublist for each date). I would now like to filter the original dataframes of each entity to only consider the intersections, so I am trying to use Boolean indexing to filter while also using groupby. See below for the loop I'm trying to build: filtered_df=pd.DataFrame() for date_sublist in range(len(intersect_list): overlap_temp=df_orig[df_orig['ObjectName'].filter(intersect_list[date_sublist])] bkln_overlap.append(overlap_temp) I also tried the construct below as a test, where I was trying to only keep rows where the object name matched the particular intersection list: df_orig[df_orig['ObjectName'] in intersect_list[1]] Does anyone have any advice for this problem? Thank you.
tagged with: python
type: Question

http://stackoverflow.com/comment/89120070
type: Comment
has text: @vestland - So need add category to columns, need test it.
comment on: http://stackoverflow.com/a/51064960
score: 0
type: AnswerComment

http://stackoverflow.com/a/51159180
downvote count: 0
answers question: http://stackoverflow.com/q/51157958
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51157958
has body: If you want to print only directories that have files: for path, subdirs, files in os.walk(root): if files: print os.path.basename(path) for filename in files: print ' ' + filename # spaces are just for indent If you need empty directories too, remove if files.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/51029979
has body: This should work for you: class Polynomial(): def __init__(self,num_list = []): sorted_list = list(sorted(num_list,key=(lambda d:d[1]),reverse=True)) self.num_list = [i for i in sorted_list] def display(self): storage = [] for i in range(len(self.num_list)): storage.append(str(self.num_list[i][0]) + 'x^' + str(self.num_list[i][1])) print(''.join(storage)) a = Polynomial([[1,8],[-5,7],[-1,1],[-1,0]]) a.display() Output: 1x^8-5x^7-1x^1-1x^0 Obviously, there is some more advanced display logic you can play with, but I'll leave that up to you. Hope that helps! Or if you want to throw the display functionality into a one-liner (updated from @bobrobbob's comment): class Polynomial(): def __init__(self,num_list = []): sorted_list = list(sorted(num_list,key=(lambda d:d[1]),reverse=True)) self.num_list = [i for i in sorted_list] def display(self): print(''.join('%+dx^%d' % (a, b) if b!=0 else '%+d' % (a) for a, b in self.num_list)) a = Polynomial([[1,8],[-5,7],[-1,1],[-1,0]]) a.display() Output: +1x^8-5x^7-1x^1-1
type: Answer
has comment: http://stackoverflow.com/comment/89053449
has comment: http://stackoverflow.com/comment/89053700
downvote count: 0
has comment: http://stackoverflow.com/comment/89053876
has comment: http://stackoverflow.com/comment/89052928
has comment: http://stackoverflow.com/comment/89052488
score: 1
has comment: http://stackoverflow.com/comment/89053950
has comment: http://stackoverflow.com/comment/89052866
has comment: http://stackoverflow.com/comment/89052531
upvote count: 1
has comment: http://stackoverflow.com/comment/89052354
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89053146
accepted answer of: http://stackoverflow.com/q/51029703
has comment: http://stackoverflow.com/comment/89053784
has comment: http://stackoverflow.com/comment/89052310
answers question: http://stackoverflow.com/q/51029703
has comment: http://stackoverflow.com/comment/89052361

sublimelinter
tags question: http://stackoverflow.com/q/51085060
tag name: sublimelinter
type: Tag

http://stackoverflow.com/comment/89581495
score: 0
type: QuestionComment
type: Comment
has text: I use urllib.request. I don't know exactly how to use API, so I use a lot of json.get(). Could you please tell me how to use api with a simple example?
comment on: http://stackoverflow.com/q/51130535

http://stackoverflow.com/a/51058039
upvote count: 1
type: Answer
has body: It seems that you read the file from local path ? My answer is use eval to change the string: df.apply(lambda x:x.apply(eval))
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51056935

http://stackoverflow.com/a/51154216
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51153766
has comment: http://stackoverflow.com/comment/89312075
has body: You can use ["Cube.{0:03}".format(i)], which will pad with the necessary number of zeroes (3 in this case), for example: &gt;&gt;&gt; "Cube.{0:03}".format(1) 'Cube.001' &gt;&gt;&gt; "Cube.{0:03}".format(12) 'Cube.012' &gt;&gt;&gt; "Cube.{0:03}".format(123) 'Cube.123' In Python 3.6+ you can do like this (f-strings, see PEP 498): f"Cube.{i:03}" # where i is your index variable
answers question: http://stackoverflow.com/q/51153766

http://stackoverflow.com/comment/89086032
has text: Perhaps [paramiko](http://www.paramiko.org/) is right for you. [This method](http://docs.paramiko.org/en/2.4/api/keys.html#paramiko.pkey.PKey.from_private_key) seems on point.
comment on: http://stackoverflow.com/q/51044259
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51069148
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51068354
type: Answer
has body: You could do something like this: with open("./f") as f: read_next = False for line in f: if line.strip() == 'A.': read_next = True continue if read_next: read_next = False print line Where the file ./f contains: A. B. C. D. E. A. D. A. F. S. And this outputs: B. D. F. A simpler method that requires reading all of the data into memory is this: with open("./f") as f: lines = f.read().splitlines() for i,line in enumerate(lines): if line == 'A.' and i &lt; (len(lines)-1): print lines[i+1]
answers question: http://stackoverflow.com/q/51068354

http://stackoverflow.com/q/51105226
type: Question
has body: How can I increase the space between two specefic boxes in a seaborn boxplot? In the tips dataset, how can i modify the spacing between Sat and Sun without affecting the other boxes. I already included empty columns in the dataframe but with this workaround it's not possible to controll the spacing. %matplotlib inline import seaborn as sns tips = sns.load_dataset("tips") ax = sns.boxplot(x="day", y="total_bill", data=tips)
has answer: http://stackoverflow.com/a/57971898
score: 7
tagged with: matplotlib
has title: Seaborn boxplot individual box spacing
has answer: http://stackoverflow.com/a/51119188
answer count: 2
downvote count: 0
favorite count: 0
tagged with: seaborn
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35090425
tagged with: boxplot
tagged with: python
upvote count: 7

http://stackoverflow.com/comment/89147630
type: Comment
score: 1
has text: I'd say it's a NumPy bug, if it doesn't handle large integers properly. At least the error message should be clearer. Though I assume this bug is already reported somewhere on the NumPy repository.
comment on: http://stackoverflow.com/q/51079486
type: QuestionComment

http://stackoverflow.com/q/51165523
has body: I'm trying to build a script tool with ply. However I'm blocked by some parsing errors. By moving those p_xxx functions to different places, I got different syntext errors. Could any one give kind help? e.g. If I move p_funcall after other p_xxx functions, then I got: Syntax error at '(', lineno 4, pos 8, data ' fun(arg1,arg2,arg3) ' Below is the source code: #!/usr/bin/python # -*- coding: UTF-8 -*- __version__ = '3.16' import sys sys.path.insert(0, "..") import ply.lex as lex import ply.yacc as yacc import os import dumper class TdsParser(object): ''' Base class for a lexer/parser that has the rules defined as methods ''' def __init__(self, **kw): self.debug = kw.get('debug', 0) self.names = {} try: modname = os.path.split(os.path.splitext(__file__)[0])[ 1] + "_" + self.__class__.__name__ except: modname = "parser" + "_" + self.__class__.__name__ self.debugfile = modname + ".dbg" self.tabmodule = modname + "_" + "parsetab" print(self.debugfile, self.tabmodule) # Build the lexer and parser self.lexer = lex.lex(module=self, debug=self.debug) self.yaccer = yacc.yacc(module=self, debug=self.debug, debugfile=self.debugfile, tabmodule=self.tabmodule) tokens = ( 'COMMA', 'COLON', 'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE', 'ATOM', 'NUMBER', ) # Tokens # Tokens t_COMMA = r',' t_COLON = r':' def t_LPAREN(self, t): r'\(' return t def t_RPAREN(self, t): r'\)' return t def t_ATOM(self, t): r'[a-zA-Z_][a-zA-Z0-9_]*' return t def t_NUMBER(self, t): r'\d+|0[Bb][01]+|0[oO][0-7]|0[xX][a-f0-9]' return t def t_newline(self, t): r'\n+' t.lexer.lineno += len(t.value) t_ignore = ' \t' def t_error(self, t): print("Illegal character '%s', lineno %d, pos %d, data '%s'" % (t.value, t.lexer.lineno, t.lexer.lexpos, t.lexer.lexdata)) t.lexer.skip(1) def t_COMMENT(self, t): r'\#.*' pass #yacc parser def p_funcall(self, p): ''' funcall : ATOM LPAREN arglist RPAREN | ATOM LPAREN RPAREN ''' print("\n###", sys._getframe().f_code.co_name, "###\n") pass def p_varlist(self, p) : ''' varlist : varlist exp…
tagged with: ply
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/89314439
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89315250
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51165884
has title: Need help on ply LALR parser
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51165884
answer count: 1

http://stackoverflow.com/a/51104686
score: 17
has body: You can use any: dic = {'0': {'text': 'a', 'lang': 'es', 'rating': '4'}, '1': {'text': 'b', 'lang': 'es', 'rating': '3'}, '2': {'text': 'c', 'lang': 'es', 'rating': '1'}, '3': {'text': 'd', 'lang': 'es', 'rating': '2'}, '4': {'text': 'e', 'lang': 'es', 'rating': '5'}} result = any('a' in d.values() for d in dic.values())
type: AcceptedAnswer
upvote count: 17
type: Answer
accepted answer of: http://stackoverflow.com/q/51104645
downvote count: 0
answers question: http://stackoverflow.com/q/51104645

http://stackoverflow.com/a/68311983
score: 1
has body: You are searching for two separate items in string. If you split them into a list then the following code will find them. lk = [ 'Motor','101' ] s1 = [ 'Device Motor_101 is very high', '101Motor Device is very high', 'Motor device 101 is very is high' ] for i, a in enumerate( s1 ): result = -1 for b in a.split(): if lk[0] in b: result = i if lk[1] in b: if result &gt; -1: print( f'found in {a}' ) This code will search and find more than just two items lk = [ 'Motor','101' ] ln = len( lk ) s1 = [ 'Device Motor_101 is very high', '101Motor Device is very high', 'Motor device 101 is very is high' ] found = [] for i, a in enumerate( s1 ): for b in a.split(): result = -1 for gp in range( ln ): if lk[ gp ] in b: result += 1 if result &gt; -1 and found.count( a ) == 0: found.append( a ) print( f'found in {a}' ) print( f'{found}' ) Ok I've found that duplications of words cause false positives so... Here is my third attempt lk = [ 'sky', '101', 'Motor', 'very' ] ln = len( lk ) s1 = [ 'Device Motor_101 is very high in sky', '101Motor Device is sky sky very', 'Motor device is very is high very very' ] found = [] for i, a in enumerate( s1 ): result = 0 sa = a.split( ) for b in a.split(): for gp in range( ln ): if lk[ gp ] in b: if b in sa: sa.remove( b ) result += 1 if result == ln-1: found.append( a ) print( f'{found}' )
upvote count: 1
has comment: http://stackoverflow.com/comment/120731669
has comment: http://stackoverflow.com/comment/120731890
has comment: http://stackoverflow.com/comment/120731756
type: Answer
answers question: http://stackoverflow.com/q/51062015
has comment: http://stackoverflow.com/comment/120732168
downvote count: 0

http://stackoverflow.com/q/51072941
tagged with: python
tagged with: python-decorators
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/98598509
has title: Which way is ideal for Python factory registration?
has comment: http://stackoverflow.com/comment/89135481
type: AnsweredQuestion
has body: This is a question about which of these methods would be considered as the most Pythonic. I'm not looking for personal opinions, but, instead, what is idiomatic. My background is not in Python, so this will help me. I'm working on a Python 3 project which is extensible. The idea is similar to the factory pattern, except it is based on functions. Essentially, users will be able to create a custom function (across packages and projects) which my tool can locate and dynamically invoke. It will also be able to use currying to pass arguments down (but that code is not included here) My goal is for this to follow good-Pythonic practice. I'm torn between two strategies. And, since Python is not my expertise, I would like to know the pros/cons of the following practices: Use a decorator registered = {} def factoried(name): def __inner_factory_function(fn): registered[name] = fn return fn return __inner_factory_function def get_function(name): return registered[name] Then, the following function is automatically registered... @factoried('foo') def build_foo(): print('hi') This seems reasonable, but does appear slightly magical to those who are not familiar with decorators. Force sub-classing of an abstract class and use __subclasses__() If subclasses are used, there's no need for registration. However, I feel like this forces classes to be defined when a full class may be unnecessary. Also, the use of .__subclasses__() under the hood could seem magical to consumers as well. However, even Java can be used to search for classes with annotations. Explicit registration Forget all of the above and force explicit registration. No decorators. No subclasses. Just something like this: def build_foo(): # ... factory.register('foo', build_foo)
upvote count: 5
has comment: http://stackoverflow.com/comment/89135681
has comment: http://stackoverflow.com/comment/89135638
type: Question
linked to: http://stackoverflow.com/q/28035685
score: 5
has answer: http://stackoverflow.com/a/51072997
answer count: 1
accepted answer: http://stackoverflow.com/a/51072997
downvote count: 0
has comment: http://stackoverflow.com/comment/89135501
favorite count: 0
tagged with: idioms
has comment: http://stackoverflow.com/comment/89135656
has comment: http://stackoverflow.com/comment/89135562

http://stackoverflow.com/q/51058756
tagged with: python
upvote count: 4
has body: I'm using the Django ORM/Cache as the result backend for celery. I can see that django_celery_results_taskresult table is created in the database. After the tasks are finished the results are also inserted in the database which can be viewed from MySQL. But when I try to access the results using AsyncResult and task ID from django manage.py shell I get the following error. &gt;&gt;&gt; AsyncResult.get('88e4d870-1a2b-4675-8f7c-1eacb7199bda') Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/root/vms/lib/python3.6/site-packages/celery/result.py", line 199, in get if self.ignored: AttributeError: 'str' object has no attribute 'ignored' &gt;&gt;&gt; AsyncResult('88e4d870-1a2b-4675-8f7c-1eacb7199bda').get() Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/root/vms/lib/python3.6/site-packages/celery/result.py", line 224, in get on_message=on_message, File "/root/vms/lib/python3.6/site-packages/celery/backends/base.py", line 470, in wait_for_pending no_ack=no_ack, File "/root/vms/lib/python3.6/site-packages/celery/backends/base.py", line 773, in _is_disabled raise NotImplementedError(E_NO_BACKEND.strip()) NotImplementedError: No result backend is configured. Please see the documentation for more information. My celery.py file is: from __future__ import absolute_import, unicode_literals from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vms.settings') app = Celery('vms', broker='redis://localhost', include=['cve.tasks','cpe.tasks']) app.conf.update( result_backend='django-db', timezone = 'Asia/Kolkata' ) if __name__ == '__main__': app.start() I've included django_celery_results in settings.py INSTALLED_APPLICATIONS. I find it weird that the results get inserted into the database but cannot be retrieved.
favorite count: 0
tagged with: django
tagged with: celery
linked to: http://stackoverflow.com/q/68865144
type: AnsweredQuestion
downvote count: 0
has title: Celery - Cannot fetch task results
tagged with: django-celery
type: Question
answer count: 1
score: 4
has answer: http://stackoverflow.com/a/51059098
accepted answer: http://stackoverflow.com/a/51059098
tagged with: celery-task

http://stackoverflow.com/comment/89095889
comment on: http://stackoverflow.com/q/51035214
score: 0
type: Comment
type: QuestionComment
has text: Between which is a better coding options: a. Either to using grid_remove(), so that system keeps track of the components in its memory ? b. Or use grid_forget() and re-create when its required so that you free up the memory ?

http://stackoverflow.com/comment/89284826
type: Comment
comment on: http://stackoverflow.com/a/51134486
has text: how can i test the load
type: AnswerComment
score: 0

http://stackoverflow.com/q/51166800
upvote count: 4
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/65709704
favorite count: 0
has answer: http://stackoverflow.com/a/66308953
has answer: http://stackoverflow.com/a/67820120
tagged with: python
has title: Python Discord.py - ctx is a required argument
score: 4
has answer: http://stackoverflow.com/a/51166870
has answer: http://stackoverflow.com/a/66765003
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63552759
has answer: http://stackoverflow.com/a/51166853
has body: I'm trying to make a discord bot, and I am following a simple tutorial, and I can't get the simplest command to work. I am on python 3.6 and running discord.py version 0.16.12 #Imports import time import discord import asyncio from discord.ext import commands #Initialize client = discord.Client()#Creates Client bot = commands.Bot(command_prefix='!')#Sets prefix for commands(!Command) #Code @bot.command() async def SendMessage(ctx): await ctx.send('Hello') The code should work but it gives me the error discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
type: Question
tagged with: discord.py

http://stackoverflow.com/comment/89158060
has text: @tobias_k correct, I want to handle all properly formatted time strings.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51084316
score: 0

http://stackoverflow.com/q/51142082
has title: Choose ranges from each row in numpy array
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47982894
has body: I have a 2D numpy array and I need to select ranges from each row of that array, i.e. I need to do something like: arr = arr[:, 3:6] But instead of 3 and 6 I would like to use two 1D arrays, which contain starting and ending indices of required ranges. arr rows are packed of coordinates data. The length of each range is the same and is known beforehand. Starting and ending indices are aligned to the length of range (e.g. if the length of packed data is 3 then the length of the range is also 3 and starting and ending indices are multiples of 3) How can I do that in numpy (I need it to be efficient vectorised implementation)? Example: arr = np.array([[0,1,2,3], [4,5,6,7]]) str_idx = [0, 2] end_idx = [2, 4] Wanted result: selected = [[0,1], [6,7]]
answer count: 0
score: 1
duplicate of: http://stackoverflow.com/q/47982894
upvote count: 1
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/89268466
has comment: http://stackoverflow.com/comment/89269075

http://stackoverflow.com/comment/89167267
type: Comment
type: QuestionComment
score: 0
has text: Please Edit your post with the command you are using to run unit test cases. Seems like your test cases is not getting called. see: `Ran 0 tests in 0.000s`. Also, what is name of the file where `NamesTestCase` is present?
comment on: http://stackoverflow.com/q/51089099

http://stackoverflow.com/q/51110783
tagged with: python
answer count: 4
favorite count: 0
accepted answer: http://stackoverflow.com/a/51110816
has answer: http://stackoverflow.com/a/59497848
possible better answer: http://stackoverflow.com/a/68376648
has answer: http://stackoverflow.com/a/68376648
has body: I was wondering if it was possible to get the file path of a temporary file made using the tempfile library. Basically, I'm trying to make a function that intakes some data, and generates a temporary csv file based off of said data. I was wondering if there was a way to get the path of this temporary file?
type: AnsweredQuestion
tagged with: temporary-files
type: Question
has title: Is it possible to get the path of a tempfile in Python 3
has answer: http://stackoverflow.com/a/51110816
downvote count: 0
score: 72
has answer: http://stackoverflow.com/a/51110829
upvote count: 72

http://stackoverflow.com/comment/89311904
has text: Much better; nice job. This uses techniques more advanced than my private solution -- yours is more elegant (Pythonic); mine is closer to OP's tech level.
type: Comment
comment on: http://stackoverflow.com/a/51160128
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89309738
score: 1
type: QuestionComment
has text: Can you please post example data or a sample dataframe? You will get better answers if you include a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Are you looking for something like [this](https://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/)?
comment on: http://stackoverflow.com/q/51163175
type: Comment

http://stackoverflow.com/a/51066235
accepted answer of: http://stackoverflow.com/q/51065365
answers question: http://stackoverflow.com/q/51065365
has comment: http://stackoverflow.com/comment/89122489
has body: Let's break this down. We are trying to look for commas which are separating parts of a string. So first we need to look for a comma , Now we need to look ahead to make sure this comma is not within a pair of quotation marks. We look ahead with (?=...) We are looking for the first " so we can match as many non-quotes as possible. (we use ^" to indicate any character that is note a quotation mark) [^"]*, and then we look for the first quote, together this makes: [^"]*" If we have matched the first quote, we need to look for the second. There can be any number of non-quote characters ([^"]*) between them, so we repeat [^"]*" We want to match any two pairs of quotes as many times as possible (without capturing), so we look for zero to infinite occurrences of quoted strings (?:[^"]*"[^"]*")* Together this makes: (?=(?:[^"]*"[^"]*")*) Finally we want to match any remaining non-quote characters, and then we wish to match the end of the string (indicated by $) [^"]*$ Together all of this gives ,(?=(?:[^"]*"[^"]*")*[^"]*$) Essentially it is trying to match a comma by checking that every quote " character after the comma, can be paired with a closing quote character. This is why the output doesn't spereate the comma within "this is, test1" and "this is, test2"
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89312622
has text: L = ['Open','Closed','Open'] #create new df df = pd.DataFrame({'col':L})
comment on: http://stackoverflow.com/q/51164582
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89053040
has text: hi @CallCentreExecutive i am actually writing down my response for you. I like your answer but I have a few questions. :)
comment on: http://stackoverflow.com/a/51029438
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89199418
has text: Yes, a forward slash does work on windows for the most part, except in some older programs I believe. I would try that, and also make sure that there are no possibly different versions of potreeconverter around, which python may be seeing first, but are incorrect.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51091250
score: 0

http://stackoverflow.com/q/51027150
has answer: http://stackoverflow.com/a/51027352
duplicate of: http://stackoverflow.com/q/14856953
has comment: http://stackoverflow.com/comment/89047114
linked to: http://stackoverflow.com/q/14856953
has body: import msvcrt as m def wait(): m.getch() strength = 10 health = 10 input("You now have",strength,"strength and",health,"health") wait() This is a slice of a project i'm working on and I have come across a seemingly unsolvable issue. When this code is run, it should print ("You have now 10 strength and 10 health") but this is returned: input("You now have",strength,"strength and",health,"health") TypeError: input expected at most 1 arguments, got 5 I am absolutely baffled and I have tried many different things to fix this including adjusting the variables like: str(strength), (strength) and I tried replacing the commas with '+' but nothing seems to work and it stops my program from working properly.
has answer: http://stackoverflow.com/a/51027365
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51027350
has comment: http://stackoverflow.com/comment/89046742
has comment: http://stackoverflow.com/comment/89046943
score: 0
answer count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89046857
has title: How do you concatenate in an input?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89311402
comment on: http://stackoverflow.com/a/51162029
has text: Did you add python to the path in environment variables?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89275049
type: QuestionComment
type: Comment
has text: 1. pass Manager create_app instead of app 2. look up flask migrate init_app. 3. pretty sure you have a circular import but dont have the time to prove it right now! best of luck
comment on: http://stackoverflow.com/q/51145234
score: 0

http://stackoverflow.com/a/51133754
answers question: http://stackoverflow.com/q/51133602
type: Answer
accepted answer of: http://stackoverflow.com/q/51133602
upvote count: 1
type: AcceptedAnswer
has body: os.chdir(inputDir) if Resursive is False: filePathList = [os.path.join(inputDir, f) for f in os.listdir(inputDir) if f.endswith('.tif')] if Resursive is True: filePathList = [] for root, dirs, files in os.walk(inputDir): for file in files: if file.endswith('.tif'): filePathList.append(os.path.join(root, file))
downvote count: 0
score: 1

http://stackoverflow.com/comment/89221579
type: AnswerComment
type: Comment
has text: That works like a charm. And `df['date'].dt.year.value_counts().sort_index().plot()` will give me the life graph that I needed.
comment on: http://stackoverflow.com/a/51117677
score: 1

http://stackoverflow.com/comment/89379057
has text: @nikinlpds No, it's not clear now. But why are you putting that info here? You need to put further info into the body of your new question. Currently, it's being ignored because people can't tell what you want. But you probably saved yourself from getting downvotes because the question includes some code. If you show us a small sample of input data along with the exact expected output that matches that input then people will be able to help you. When you edit your question it will get bumped back to the front page, so many people will notice it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51086236

http://stackoverflow.com/comment/89137418
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51073860
score: 1
has text: So the data you would want to acquire is the data after the [PROFILE] and before the [VALUES] string?

http://stackoverflow.com/comment/132925315
score: 0
comment on: http://stackoverflow.com/a/59239251
type: Comment
has text: os.chdir(sys._MEIPASS) works well. Thank you!
type: AnswerComment

http://stackoverflow.com/a/51121252
has comment: http://stackoverflow.com/comment/89228036
has comment: http://stackoverflow.com/comment/89228513
has comment: http://stackoverflow.com/comment/89228154
has comment: http://stackoverflow.com/comment/89228357
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/89228910
has body: First off, building a segmentation tool of this type is a great idea!! The code you have provided only creates the trackbars using cv2.createTrackbar(). In order to use them you need to implement cv2.getTrackbarPos() to get different values as you slide the trackbar. I have made modified the same code: import cv2 import numpy as np winName = "ForeGround Segment" def foreground_segment(im, brightness, useEqualize=1, blurSize=21, th1=None): winName = "ForeGround Segment" tmp = brightness if (blurSize &gt;= 3): blurSize += (1 - blurSize % 2) tmp = cv2.GaussianBlur(tmp, (blurSize, blurSize), 0) if (useEqualize): tmp = cv2.equalizeHist(tmp) cv2.imshow('brightness preprocess', tmp) #cv2.imwrite('../BrightnessPreprocess.png', tmp) ret, tmp = cv2.threshold(tmp, th1, 255, cv2.THRESH_BINARY_INV) cv2.imshow('threshold', tmp) im2, contours, hierarchy = cv2.findContours(tmp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) dst = im.copy() #print(contours) maxDim = 0 largest = -1 for i in range(len(contours)): cv2.drawContours(dst, contours, largest, (0, 0, 255), 1) dim = len(contours[i]) if (dim &gt; maxDim): maxDim = dim largest = i img_mask = np.zeros(src.shape, np.uint8) if (largest &gt;= 0): theImg = contours[largest] cv2.polylines(dst, theImg, True, (0, 255,0), 2) cv2.drawContours(img_mask, contours, largest, 255, -1) cv2.imshow("Result Mask", img_mask) cv2.imshow("Result Contour", dst) #cv2.imwrite("../img_mask.png", img_mask) #cv2.imwrite("../result.png", dst) if __name__ == '__main__': src = cv2.imread('frontal.png') src = cv2.resize(src, (int(src.shape[0]/3), int(src.shape[1]/3)), interpolation = cv2.INTER_AREA) cv2.imshow(winName, src) dst = cv2.cvtColor(src, cv2.COLOR_BGR2HSV) hsv_planes = cv2.split(dst) brightness = hsv_planes[2] useEqualize = 1 blurSize = 21 th1 = int(33.0 * 255 / 100) cv2.createTrackbar("Equalize", winName, useEqualize, 1, foreground_segment) cv2.createTrackbar("Blur Sigma", winName, blurSize, 100, foreground_segment) cv2.createTrackbar("Threshold", win…
accepted answer of: http://stackoverflow.com/q/51120831
type: Answer
answers question: http://stackoverflow.com/q/51120831

http://stackoverflow.com/comment/89128055
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51068840
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173909/discussion-between-user15051990-and-pils19).

http://stackoverflow.com/comment/89092022
type: Comment
score: 0
has text: The problem is that the lines that begin with the "orb" can be larger. Therefore I get an error "IndexError: list index out of range". In any case, thank you very much.
comment on: http://stackoverflow.com/a/51049381
type: AnswerComment

http://stackoverflow.com/q/51034424
has comment: http://stackoverflow.com/comment/89061320
has comment: http://stackoverflow.com/comment/89061334
has comment: http://stackoverflow.com/comment/89061273
accepted answer: http://stackoverflow.com/a/51034440
type: Question
score: 8
has title: PEP8 Does Not Allow Try Except Block
tagged with: pep8
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/21553327
favorite count: 0
upvote count: 8
duplicate of: http://stackoverflow.com/q/21553327
linked to: http://stackoverflow.com/q/14797375
has answer: http://stackoverflow.com/a/51034440
duplicate of: http://stackoverflow.com/q/14797375
tagged with: python
type: AnsweredQuestion
has body: My code contains a regular try-except block. I downloaded the pycodestyle library to test pep8 on my code. I tested my code and I got the following PEP8 error: E722 do not use bare 'except' Why does this happen, and how can I fix it? Thanks.

http://stackoverflow.com/comment/89280217
comment on: http://stackoverflow.com/q/51137594
type: Comment
type: QuestionComment
has text: I think `Brad Solomon` solutions and first of mine, I am really curious if faster or not. thank you.
score: 0

http://stackoverflow.com/comment/89166211
has text: Thanks @pgngp and @Rishav for your help with this! I first tried making use of Rishav's proposed use of the pysrt library, however, after at least an hour and a half of unsuccessfully running into problems of my own trying to get a `pipenv` running to install packages like pysrt, I ran into too many problems and my own limitations working in the shell. After finally giving up on running pysrt, I was able to quickly get pgngp's solution working, I just had to add `import re` to the top as well obviously :). I've got a fully-functioning script now thanks to both your efforts!
comment on: http://stackoverflow.com/a/51073232
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51068259
accepted answer: http://stackoverflow.com/a/51068390
score: 5
tagged with: python
has title: How to {pivot|denormalize|manipulate} CSV table in Python
answer count: 4
type: AnsweredQuestion
has body: Sorry for the messy title, I didn't know how to phrase this question well. Let's say I have a table in which the first three columns are foo bar and baz. Then there are some number of arbitrary columns after. I want to manipulate the table such that these arbitrary columns are all collapsed under on column, called num. An example makes this clearer foo, bar, baz, 100, 101, 102, 103, 104, 1, 1, 1, 10, 11, 12, 13, 14, 1, 1, 2, 15, 16, 17, 18, 19, 1, 2, 1, 20, 21, 22, 23, 24, This input should transpose to: num, foo, bar, baz, value, 100, 1, 1, 1, 10, 100, 1, 1, 2, 15, 100, 1, 2, 1, 20, 101, 1, 1, 1, 11, 101, 1, 1, 2, 16, 101, 1, 2, 1, 21, 102, 1, 1, 1, 12, 102, 1, 1, 2, 17, 102, 1, 2, 1, 22, ... I wrote a custom Python solution that does this. It wasn't hard, but I feel like this is reinventing the wheel. Is there a way to accomplish this with a library like pandas or some other table manipulation module?
has answer: http://stackoverflow.com/a/51068847
type: Question
has answer: http://stackoverflow.com/a/51068390
upvote count: 5
tagged with: dataframe
has answer: http://stackoverflow.com/a/51068346
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/51068346
has answer: http://stackoverflow.com/a/51068347
favorite count: 0

http://stackoverflow.com/comment/89301375
has text: Can you let me know how? @Aankhen
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51158537

http://stackoverflow.com/comment/89213442
score: 0
type: Comment
has text: _AttributeError: 'Connection' object has no attribute 'lastrowid'_ **connection = self.engine.connect()** ist the connector not a cursor. Or did I get this wrong?
type: AnswerComment
comment on: http://stackoverflow.com/a/51113377

http://stackoverflow.com/comment/89239935
type: Comment
comment on: http://stackoverflow.com/a/51127387
score: 0
type: AnswerComment
has text: @CamGi i have provided conversion to EST, but EST is `-05:00` not `-04:00` (which is `EDT`).

http://stackoverflow.com/q/51018297
tagged with: py2exe
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/96905708
type: UnansweredQuestion
has title: Unsatisfiable Error when installing py2exe in Anaconda
answer count: 0
downvote count: 0
score: 1
has body: I want to install py2exe using conda install py2exe. However, I keep getting this error: UnsatisfiableError: The following specifications were found to be in conflict: mkl_random py2exe Could someone please tell me how to resolve this? Thanks!
type: Question
tagged with: python

http://stackoverflow.com/a/51115020
has comment: http://stackoverflow.com/comment/89218020
score: 1
accepted answer of: http://stackoverflow.com/q/51097773
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51097773
has body: Looking at how glob is implemented, it does not rely on glob(3) so it may, but is not guaranteed to yield identical results. Similar goes for POSIX compliance (apart form obviously extended functionality). There might be an overlap, but there is no guaranteed and it was apparently not the intention behind the module. You can basically rephrase the question asking yourself. What features/behavior do I really need and does glob.glob() do what I specifically need? Chances are, it does. Or am I rather looking for a compliance statement (certification even) because for instance the project/customer/our company (for reasons only they know (or do not)) requires it. For which you are out of luck with glob.glob(), unless you do the auditing/paperwork yourself or hire someone to do it (note, the code for glob is not that large). You can also (even though you said you did not want to) load glob(3) from libc.so with ctypes. Or re-implement it in Python from scratch (or based on glob for that matter) with the compatibility requirement in mind. As for the point on possible already existing alternatives, I'd defer that to further research and/or recommendations of others.
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/51126527
tagged with: regex
has answer: http://stackoverflow.com/a/51126800
possible better answer: http://stackoverflow.com/a/51126800
upvote count: 1
has body: I am trying to add multiple lines to a file (input.txt) and replace multiple lines in the same file (input.txt) but my code only inserts the lines at end of file. Do you know that how I can fix the code to get the expected output file I want? My code: import re searchtext1 = """ AB 3.483e-01 2.52e-02 ; 3.46 0.0123 """ # add these lines after searchtext1 addtext1 = """ CD 2.123e-01 1.31e-02 ; 7.25 0.0145 DE 4.896e-01 7.25e-02 ; 8.25 0.0185 """ searchtext2 = """ ; atom #atomnumber #molecule [weight] """ # replace these lines to searchtext2 changetext2 = """ ; iron #48kcal 35 mol #12 g """ with open('input.txt', 'ab+') as infile: matches1 = re.findall(r'^(\d+)\.(.*)$', searchtext1, re.MULTILINE) infile.write(addtext1) matches2 = re.findall(r'^(\d+)\.(.*)$', searchtext2, re.MULTILINE) infile.write(changetext2) input.txt: [atom] 123 [bonds] XY 4.212e-01 4.18e-02 ; 8.01 0.0487 AB 3.483e-01 2.52e-02 ; 3.46 0.0123 [molecule] 1 2 3 4 TY 0.412e-01 1.72e-02 ; 0.32 0.0455 ; atom #atomnumber #molecule [weight] calculated value is 5 kcal/mol end file expected output file: [atom] 123 [bonds] XY 4.212e-01 4.18e-02 ; 8.01 0.0487 AB 3.483e-01 2.52e-02 ; 3.46 0.0123 CD 2.123e-01 1.31e-02 ; 7.25 0.0145 DE 4.896e-01 7.25e-02 ; 8.25 0.0185 [molecule] 1 2 3 4 TY 0.412e-01 1.72e-02 ; 0.32 0.0455 ; iron #48kcal 35 mol #12 g calculated value is 5 kcal/mol end file
has title: replace and add multiple lines using findall
has answer: http://stackoverflow.com/a/51139022
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89238641
has comment: http://stackoverflow.com/comment/89238593
type: AnsweredQuestion
tagged with: findall
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51139022
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/comment/89065990
type: Comment
comment on: http://stackoverflow.com/q/51021049
score: 0
type: QuestionComment
has text: Is the ECL field always a string? Is it possible that sometimes it can be a value other than string or even null?

http://stackoverflow.com/comment/89258499
comment on: http://stackoverflow.com/a/51126675
type: AnswerComment
score: 0
type: Comment
has text: Hi,Is there a way to specify argument by referring to its name rather than the index?

http://stackoverflow.com/comment/89310171
type: Comment
type: QuestionComment
score: 0
has text: If so, place the tenderkeyword class before the tender class. example: `assigned_keywords = models.ManyToManyField(tenderKeyword, through='keywords', related_name='tkeywords', blank=True)`
comment on: http://stackoverflow.com/q/51163174

file
type: Tag
tags question: http://stackoverflow.com/q/51068339
tags question: http://stackoverflow.com/q/51045369
tags question: http://stackoverflow.com/q/51093723
tags question: http://stackoverflow.com/q/51056172
tag name: file
tags question: http://stackoverflow.com/q/51062049
tags question: http://stackoverflow.com/q/51097717
tags question: http://stackoverflow.com/q/51065960
tags question: http://stackoverflow.com/q/51061907
tags question: http://stackoverflow.com/q/51016696
tags question: http://stackoverflow.com/q/51117243
tags question: http://stackoverflow.com/q/51163425
tags question: http://stackoverflow.com/q/51157958
tags question: http://stackoverflow.com/q/51054384
tags question: http://stackoverflow.com/q/51060084
tags question: http://stackoverflow.com/q/51119621
tags question: http://stackoverflow.com/q/51156430
tags question: http://stackoverflow.com/q/51139011
tags question: http://stackoverflow.com/q/51111247

http://stackoverflow.com/q/51163088
tagged with: django-authentication
tagged with: authentication
type: Question
score: 18
has body: So, I'm fairly new to Django. Notwithstanding the fact that my code works after following the Django docs 'Customizing authentication in Django', I don't get how the self.model(...) in their example actually works, where it comes from and how it functions with 'self'. This is the example found at the bottom of the docs. from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') -&gt; user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user ...
answer count: 1
favorite count: 0
tagged with: django-users
has title: self.model() in django custom UserManager
upvote count: 18
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/96475013
has answer: http://stackoverflow.com/a/51163172
downvote count: 0
accepted answer: http://stackoverflow.com/a/51163172

http://stackoverflow.com/q/51126859
has body: I am working with python 3 and can not figure out a way to get this to work. I am trying to create a tool for my hex editor that can look at a large set of bytes and search for the headers and footers of .pdf files, etc. I know the .pdf header is 25 50 44 46 2D 31 2E and the footer is 25 25 45 4F 46 in hexadecimal. So my questions is, is there a way to search through a large set of bytes find the header and footer copy all the bytes in between, use them to create a new file that I can then open with, in this case something like adobe reader, and view it as any other .pdf? Any help would be greatly appreciated.
has comment: http://stackoverflow.com/comment/89238671
type: Question
tagged with: hex-editors
has comment: http://stackoverflow.com/comment/89273176
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89238685
tagged with: python
has title: Python carving a file from a large set of bytes
answer count: 0

http://stackoverflow.com/comment/89171351
score: 1
has text: It depends. How are the names patched?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51091541

http://stackoverflow.com/a/51071548
has body: Maya might work for you: &gt;&gt;&gt; maya.when("in 1H").datetime() datetime.datetime(2018, 6, 27, 22, 16, 42, 371621, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; maya.when("in 1 day").datetime() datetime.datetime(2018, 6, 28, 21, 16, 42, 371621, tzinfo=&lt;UTC&gt;) You may even specify arbitrary time values and not limit to only hours or days, which causes your app to be even more flexible: &gt;&gt;&gt; maya.when("now").datetime() datetime.datetime(2018, 6, 27, 21, 20, 7, 409348, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; maya.when("in 1 hour 2 minutes").datetime() datetime.datetime(2018, 6, 27, 22, 22, 7, 825372, tzinfo=&lt;UTC&gt;) P.S. Maya is powered by dateparser. Although you can use dateparser straight out of the bat to handle everything, I think Maya will prove more useful.
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/89133248
downvote count: 0
has comment: http://stackoverflow.com/comment/89133258
has comment: http://stackoverflow.com/comment/89133085
type: Answer
answers question: http://stackoverflow.com/q/51071358

http://stackoverflow.com/comment/89113505
score: 0
has text: OP asked specifically to avoid regex
comment on: http://stackoverflow.com/a/51061748
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51017258
has answer: http://stackoverflow.com/a/51017387
has comment: http://stackoverflow.com/comment/89027056
score: 0
has answer: http://stackoverflow.com/a/51017491
has title: How to eliminate items in the list of python
has comment: http://stackoverflow.com/comment/89027116
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51017491
has answer: http://stackoverflow.com/a/51017474
type: Question
has answer: http://stackoverflow.com/a/51017344
has body: I have a list in python: A=[[303 80] [390 43] [446 16] [471 16] [505 44] [557 225] [642 22] [672 15] [694 86] [702 76]] Now I want to remove the rows A[i] which have a bigger summary value than the next item in the list. A[i][0]+A[i][1] &gt; A[i+1][0] I code this lines: B=[] for i in range(len(A)-1): if A[i][0]+A[i][1]&lt;=A[i+1][0]: B.append(A[i]) B.append(A[i+1]) I got this result: B=[[303 80] [390 43] [446 16] [471 16] [505 44] [642 22] [672 15] [702 76]] Are there any other ways which are shorter and quicker than this. Thank you very much.
possible better answer: http://stackoverflow.com/a/51017387

http://stackoverflow.com/comment/89137274
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51073785
has text: nvm im just a complete idiot lol. I completely overlooked a `_` in one of my variables in the yield. So... You are right :) That's also part of the reason why I posted this question though because I felt really stupid haha
score: 0

http://stackoverflow.com/comment/89220289
type: Comment
comment on: http://stackoverflow.com/a/51116878
has text: ya, I didn't think it's difficult like that. Thanks for your time, maybe I can't finish my first crawler anytime soon.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51145193
has comment: http://stackoverflow.com/comment/89274898
has comment: http://stackoverflow.com/comment/89274680
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89275014
has body: I have the curl command: curl 'https://example.com/submit' \ -H 'Accept: */*' \ -H 'Referer: http://www.example.com/go/' \ -H 'Origin: http://www.example.com' \ -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' \ -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFkQeCsmEXjVI5SJ0' \ --data-binary $'------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\r\nContent-Disposition: form-data; name="firstName"\r\n\r\Oleg\r\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\r\nContent-Disposition: form-data; name="campaignCode"\r\n\r\n\r\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\r\nContent-Disposition: form-data; name="validation"\r\n\r\n{"firstName":"required"}\r\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0--\r\n' \ --compressed with: --data-binary $'------WebKitFormBoundary...' but my converted version to python code does not work import requests headers = { 'Accept': '*/*', 'Referer': 'http://www.example.com/go', 'Origin': 'http://www.example.com', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryFkQeCsmEXjVI5SJ0' } data = '$------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\\r\\nContent-Disposition: form-data; name="firstName"\\r\\n\\r\\Oleg\\r\\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\\r\\nContent-Disposition: form-data; name="campaignCode"\\r\\n\\r\\n\\r\\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0\\r\\nContent-Disposition: form-data; name="validation"\\r\\n\\r\\n{"firstName":"required"}\\r\\n------WebKitFormBoundaryFkQeCsmEXjVI5SJ0--\\r\\n' response = requests.post('https://example.com/submit', headers=headers, data=data) Maybe I'm missing something? how to convert --data-binary $? The curl command returns: {"success":true,"count":1}, but pycode returns: {"success":false,"count":1} Also errors: Without $ in datastring response-{"success":false,"count":0}. Using a bytes inste…
has answer: http://stackoverflow.com/a/51145417
favorite count: 0
has comment: http://stackoverflow.com/comment/89275470
has comment: http://stackoverflow.com/comment/89274692
tagged with: python
tagged with: curl
downvote count: 0
has answer: http://stackoverflow.com/a/51145409
type: UnansweredQuestion
score: 1
tagged with: python-requests
type: Question
has title: how to convert curl --data-binary to python request?

http://stackoverflow.com/q/51033366
has comment: http://stackoverflow.com/comment/89059053
has comment: http://stackoverflow.com/comment/89058984
has answer: http://stackoverflow.com/a/51033491
has comment: http://stackoverflow.com/comment/89059016
has comment: http://stackoverflow.com/comment/100869303
tagged with: enums
possible better answer: http://stackoverflow.com/a/57178871
has comment: http://stackoverflow.com/comment/89059040
has answer: http://stackoverflow.com/a/57178871
has comment: http://stackoverflow.com/comment/89059046
tagged with: nameerror
tagged with: python-2.7
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89058985
accepted answer: http://stackoverflow.com/a/51033491
downvote count: 0
has title: NameError when using super() in enum constructor
has comment: http://stackoverflow.com/comment/89059005
favorite count: 0
type: Question
answer count: 2
has body: I am using Python 2.7.10 with the enum34 library. I am trying to do the following: from enum import Enum class Foo(Enum): def __init__(self): pass class Bar(Foo): VALUE = 1 def __init__(self, value): super(Bar, self).__init__() When this code is run, I receive the error NameError: global name 'Bar' is not defined. Could someone help explain why I receive this error and if it's possible to call the parent constructor of an enum subclass? Thank you in advance! Edit: Traceback (with path names redacted) for Olivier Melançon: Traceback (most recent call last): File "/.../test.py", line 9, in &lt;module&gt; class Bar(Foo): File "/.../lib/python2.7/site-packages/enum/__init__.py", line 236, in __new__ enum_member.__init__(*args) File "/.../test.py", line 13, in __init__ super(Bar, self).__init__() NameError: global name 'Bar' is not defined Process finished with exit code 1
tagged with: python
tagged with: super
upvote count: 3
has comment: http://stackoverflow.com/comment/89059059

http://stackoverflow.com/comment/89117199
comment on: http://stackoverflow.com/a/51063269
type: AnswerComment
score: 0
type: Comment
has text: and there are a way to import everything from config.py ? because I will have to add more line in config.py

http://stackoverflow.com/q/51084825
has title: Distance between 2 pixels
type: Question
has comment: http://stackoverflow.com/comment/89158166
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/89159735
answer count: 1
tagged with: opencv
has answer: http://stackoverflow.com/a/51091479
has comment: http://stackoverflow.com/comment/89159198
upvote count: 3
tagged with: image-processing
has body: Coming from software development, i'm new to image processing. I try to get the distance between two pixels in an image that is a numpy array of shape (100, 100, 3). For example i want to find the distance between a pixel blue (0, 0, 255) and a pixel red (255, 0, 0) in the image, I tried with a for loop or np.where() ... but no success. The distance could be the some kind of difference between the two indexes in the image (possibility that there is more pixels of these colors so at least the first met in the image) Any idea how to do that ? EDIT: I'm capturing part of my screen like that: screen = np.array(pyautogui.screenshot(region=(80,120,100,100))) Now i want to find the pixel(s) of color blue and the pixel(s) of color red and the distance between them in the image
tagged with: numpy
has comment: http://stackoverflow.com/comment/89171674
has comment: http://stackoverflow.com/comment/89159691
downvote count: 0
accepted answer: http://stackoverflow.com/a/51091479
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89160080
score: 3
has comment: http://stackoverflow.com/comment/89158494
has comment: http://stackoverflow.com/comment/89159343
favorite count: 0

http://stackoverflow.com/a/55977014
score: 3
has comment: http://stackoverflow.com/comment/100469429
type: Answer
upvote count: 3
has body: Another solution -- that does not use docker-compose -- is to run the two containers on the same bridge network (created using docker network create &lt;networkname&gt;) by using the --network flag in the docker run commands for both of the containers: docker run -p 27017:27017 --name mongo1 -d --network sizijaynetwork mongo docker run -p 5000:5000 --name app1 -d --network sizijaynetwork appimage Then in your Python script you can do: from pymongo import MongoClient client = MongoClient(host = 'mongo1', port = 27017) db = client.databaseName Note that the host should be the name you assign to your Mongo container, and in case you don't use the --name flag, just use the default name for the container you can find under NAMES when you do docker ps
downvote count: 0
answers question: http://stackoverflow.com/q/51122371

http://stackoverflow.com/comment/92217221
type: Comment
comment on: http://stackoverflow.com/a/51199962
type: AnswerComment
has text: Python: I think you should add `while TRUE:` in order to request the ticks all the time, and then check that new data arrived. MT: this is an expert. Scripts are good for one-time operations, I do not think it makes sense to sleep and freeze the thread if you have experts; indicator is not good as it cannot send trade requests. About receiving candles not ticks - that is a question to the API that they provide, maybe they have different API for receiving quotes. Reqarding compilation issue: try it as script first of all, please check the updated code. it was designed for quotes not candles
score: 0

http://stackoverflow.com/q/51030872
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/51073489
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51073489
type: Question
has body: Using Tensorflow 1.8.0, we are running into an issue whenever we attempt to build a categorical column. Here is a full example demonstrating the problem. It runs as-is (using only numeric columns). Uncommenting the indicator column definition and data generates a stack trace ending in tensorflow.python.framework.errors_impl.InternalError: Unable to get element as bytes. import tensorflow as tf import numpy as np def feature_numeric(key): return tf.feature_column.numeric_column(key=key, default_value=0) def feature_indicator(key, vocabulary): return tf.feature_column.indicator_column( tf.feature_column.categorical_column_with_vocabulary_list( key=key, vocabulary_list=vocabulary )) labels = ['Label1','Label2','Label3'] model = tf.estimator.DNNClassifier( feature_columns=[ feature_numeric("number"), # feature_indicator("indicator", ["A","B","C"]), ], hidden_units=[64, 16, 8], model_dir='./models', n_classes=len(labels), label_vocabulary=labels) def train(inputs, training): model.train( input_fn=tf.estimator.inputs.numpy_input_fn( x=inputs, y=training, shuffle=True ), steps=1) inputs = { "number": np.array([1,2,3,4,5]), # "indicator": np.array([ # ["A"], # ["B"], # ["C"], # ["A", "A"], # ["A", "B", "C"], # ]), } training = np.array(['Label1','Label2','Label3','Label2','Label1']) train(inputs, training) Attempts to use an embedding fare no better. Using only numeric inputs, we can successfully scale to thousands of input nodes, and in fact we have temporarily expanded our categorical features in the preprocessor to simulate indicators. The documentation for categorical_column_*() and indicator_column() are awash in references to features we're pretty sure we're not using (proto inputs, whatever bytes_list is) but maybe we're wrong on that?
tagged with: tensorflow-estimator
has answer: http://stackoverflow.com/a/51092224
tagged with: python-2.7
upvote count: 3
accepted answer: http://stackoverflow.com/a/51092224
answer count: 2
favorite count: 0
has title: How do I load categorical data from a numpy array into an Indicator or Embedding column?

lowercase
tags question: http://stackoverflow.com/q/51027875
type: Tag
tag name: lowercase
tags question: http://stackoverflow.com/q/51165040

http://stackoverflow.com/q/51108117
has answer: http://stackoverflow.com/a/51108526
upvote count: 3
linked to: http://stackoverflow.com/q/27263805
type: Question
has answer: http://stackoverflow.com/a/51108569
downvote count: 0
possible better answer: http://stackoverflow.com/a/51108569
accepted answer: http://stackoverflow.com/a/51108526
tagged with: pandas
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51108333
has answer: http://stackoverflow.com/a/51108281
has title: pandas duplicate df rows based on day count column
tagged with: python
type: AnsweredQuestion
score: 3
has body: I have the following DF. DF qty | hold_date | day_count | qty | item | ccy | +------------+-----------+------+----------+-----+ | 2015-01-01 | 1 | 1200 | CB04 box | USD | | 2015-01-01 | 3 | 1500 | AB01 box | USD | | 2015-01-02 | 2 | 550 | CB03 box | USD | I want to increment the hold_date based on the day_count. for example item : AB01 box will add two new rows as below. so the df could look like this. DF qty | hold_date | qty | item | ccy | +------------+------+----------+-----+ | 2015-01-01 | 1200 | CB04 box | USD | | 2015-01-01 | 1500 | AB01 box | USD | | 2015-01-02 | 1500 | AB01 box | USD | | 2015-01-03 | 1500 | AB01 box | USD | | 2015-01-02 | 550 | CB03 box | USD | | 2015-01-03 | 550 | CB03 box | USD |

http://stackoverflow.com/comment/89221433
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51117323
type: QuestionComment
has text: Is there a reason you can't call show with an argument (even if just in one of the two cases, and the other uses a default)?

http://stackoverflow.com/comment/89258068
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51136890
has text: I'd recommend checking out multiprocessing instead of threading. Threading in python runs into the Global Interpreter Lock, which means it's often not what you want to be using.
score: 0

http://stackoverflow.com/comment/101998620
score: 0
comment on: http://stackoverflow.com/q/51163425
type: Comment
type: QuestionComment
has text: This is not a Python problem, as you really want to create a RAMdisk / tmpfs volume that's available to the operating system (outside of Python), since you want to run a .exe against it. There's plenty ways of doing that, depending on your OS, and you could then run that solution from Python like any other command.

http://stackoverflow.com/a/51085360
has comment: http://stackoverflow.com/comment/89159168
upvote count: 1
downvote count: 0
type: Answer
has body: IIUC: I'd use Numpy import numpy as np from numpy.core.defchararray import find a = np.array(['hello', 'there', 'you', 'are', 'up', 'date']) b = np.array(['hell', 'is', 'here', 'update']) bina = b[np.where(find(a[:, None], b) &gt; -1)[1]] ainb = a[np.where(find(b, a[:, None]) &gt; -1)[0]] np.append(bina, ainb) array(['hell', 'here', 'up', 'date'], dtype='&lt;U6')
has comment: http://stackoverflow.com/comment/89159219
answers question: http://stackoverflow.com/q/51085180
score: 1

http://stackoverflow.com/q/51087429
type: AnsweredQuestion
tagged with: aiohttp
has answer: http://stackoverflow.com/a/51087479
upvote count: 1
downvote count: 1
type: Question
has body: Using Python 3.6 and asyncio and aiohttp I wrote a simple async program: from aiohttp import ClientSession import asyncio, ssl, time base_url = 'https://my-base-url.com/api' async def fetch(session, id): query_params = {'qp1':'v1','qp2':'v2', 'id': id} async with session.get(base_url, params=query_params, ssl=ssl.SSLContext()) as response: res_json = await response.json() if response.status == 200: time.sleep(2) min_rating = res_json.get('minRating') max_rating = res_json.get('maxRating') print("id = %s, min = %s, max = %s" % (id, min_rating, max_rating)) async def run(ids): tasks = [] async with ClientSession() as session: for id in ids: task = asyncio.ensure_future(fetch(session, id)) tasks.append(task) responses = await asyncio.gather(*tasks) return responses if __name__ == '__main__': ids = [123, 456, 789] future = asyncio.ensure_future(run(ids)) event_loop = asyncio.get_event_loop() event_loop.run_until_complete(future) print("\n\ndone") The time.sleep(2) inside fetch(session, id) makes it seem like this program is not asynchronous because it gets one response, sleeps, gets another, sleeps, so on and so forth. When I remove the sleep call, it does seem to be async/concurrent because the responses come back in a random order. What is sleep doing in this case? Is it locking all threads? Why does it appear to be sequential instead of parallel?
has comment: http://stackoverflow.com/comment/89163615
linked to: http://stackoverflow.com/q/42279675
score: 0
accepted answer: http://stackoverflow.com/a/51087479
answer count: 1
has comment: http://stackoverflow.com/comment/89163506
has comment: http://stackoverflow.com/comment/89163357
tagged with: asynchronous
favorite count: 0
tagged with: python-asyncio
has title: Is async Python really asynchronous?
tagged with: python

http://stackoverflow.com/q/51139232
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.7
has answer: http://stackoverflow.com/a/51139316
tagged with: spyder
tagged with: python
type: UnansweredQuestion
upvote count: 7
has body: I have installed Anaconda on a Windows 10 machine which comes with Spyder and Python 3.6 but I wish to upgrade to Python 3.7 To create an Anaconda Environment with Python 3.7 is easy by using: conda create --name py37 python=3.7 or: conda create --name py370 python=3.7.0 --channel conda-forge However starting Spyder in this environment will throw it back to Python 3.6. I tried specifing the python.exe (for version 3.7) directly in Tools -&gt; Settings of Spyder, however upon restarting the Spyder Kernels can't be launched and will display that they need the packages: ipykernel and cloudpickle . When trying to conda install them in the environment the following appears: The following packages will be DOWNGRADED: python: 3.7.0-hea74fb7_0 --&gt; 3.6.6-hea74fb7_0 Which would downgreade python from 3.7 to 3.6 again. My final try was to use the command: conda install python==3.7 which has failed with the output Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - python-dateutil -&gt; python[version='&gt;=2.7,&lt;2.8.0a0'] - python-dateutil -&gt; six - python==3.7 Use "conda info &lt;package&gt;" to see the dependencies for each package. The question is not how to upgrade Conda to Python 3.7, but how can I get Spyder to work with Python 3.7 in its own environment
has title: How to run Spyder with Python 3.7 with Anaconda
tagged with: anaconda
score: 7

reasoner
type: Tag
tags question: http://stackoverflow.com/q/51147628
tag name: reasoner

http://stackoverflow.com/comment/89031036
score: 0
has text: There are only `1` and `0` values in column `cond` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51018739

http://stackoverflow.com/q/51059993
has comment: http://stackoverflow.com/comment/89112770
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89111481
has comment: http://stackoverflow.com/comment/89111236
type: Question
has answer: http://stackoverflow.com/a/51325546
accepted answer: http://stackoverflow.com/a/51325546
has title: How can I set up an automated import to Google Data Prep?
tagged with: google-cloud-dataprep
has comment: http://stackoverflow.com/comment/89110907
tagged with: google-cloud-platform
upvote count: 1
has body: When using Google Data Prep, I am able to create automated schedules to run jobs that update my BigQuery tables. However, this seems pointless when considering that the data used in Prep is updated by manually dragging and dropping CSVs (or JSON, xlsx, whatever) into the data storage bucket. I have attempted to search for a definitive way of updating this bucket automatically with files that are regularly updated on my PC, but there seems to be no best-practice solution that I can find. How should one go about doing this efficiently and effectively?
answer count: 1
has comment: http://stackoverflow.com/comment/89111454
favorite count: 0
has comment: http://stackoverflow.com/comment/89515588
tagged with: python
has comment: http://stackoverflow.com/comment/89576851

http://stackoverflow.com/q/51018536
has answer: http://stackoverflow.com/a/51019207
tagged with: time-series
score: 5
answer count: 3
has title: Is it possible to create a Rest API using Jupyter notebook?,if yes How to create Rest API for the following code interms of json format
has answer: http://stackoverflow.com/a/74604721
favorite count: 0
upvote count: 5
has answer: http://stackoverflow.com/a/69594990
tagged with: python
tagged with: jupyter-notebook
downvote count: 0
type: UnansweredQuestion
has body: I have built a model for the time series analysis which is going to predict the sail for the next days,the model is working fine,but i want to convert that into Rest API in JSON format using the Anaconda jupyter notebook,Please let me know the way for that .Thanks in advance. Here is the code: from pandas import Series from statsmodels.tsa.arima_model import ARIMA import numpy # create a differenced series def difference(dataset, interval=1): diff = list() for i in range(interval, len(dataset)): value = dataset[i] - dataset[i - interval] diff.append(value) return numpy.array(diff) # invert differenced value def inverse_difference(history, yhat, interval=1): return yhat + history[-interval] # load dataset series = Series.from_csv('mkr.csv', header=None) # seasonal difference X = series.values X = X.astype('float32') days_in_year = 365 differenced = difference(X, days_in_year) # fit model model = ARIMA(differenced, order=(0,0,1)) model_fit = model.fit(disp=0) # multi-step out-of-sample forecast forecast = model_fit.forecast(steps=7)[0] # invert the differenced forecast to something usable history = [x for x in X] day = 1 for yhat in forecast: inverted = inverse_difference(history, yhat,days_in_year) print('Day %d sail:= %.3f' % (month, inverted)) history.append(inverted) day += 1
type: Question
tagged with: mysql

http://stackoverflow.com/a/51125014
has body: Short Answer To make a clean install of Python 3.6.5 use: brew unlink python # ONLY if you have installed (with brew) another version of python 3 brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb If you prefer to recover a previously installed version, then: brew info python # To see what you have previously installed brew switch python 3.x.x_x # Ex. 3.6.5_1 Long Answer There are two formulas for installing Python with Homebrew: python@2 and python. The first is for Python 2 and the second for Python 3. Note: You can find outdated answers on the web where it is mentioned python3 as the formula name for installing Python version 3. Now it's just python! By default, with these formulas you can install the latest version of the corresponding major version of Python. So, you cannot directly install a minor version like 3.6. Solution With brew, you can install a package using the address of the formula, for example in a git repository. brew install https://the/address/to/the/formula/FORMULA_NAME.rb Or specifically for Python 3 brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/COMMIT_IDENTIFIER/Formula/python.rb The address you must specify is the address to the last commit of the formula (python.rb) for the desired version. You can find the commint identifier by looking at the history for homebrew-core/Formula/python.rb https://github.com/Homebrew/homebrew-core/commits/master/Formula/python.rb Python > 3.6.5 In the link above you will not find a formula for a version of Python above 3.6.5. After the maintainers of that (official) repository released Python 3.7, they only submit updates to the recipe of Python 3.7. As explained above, with homebrew you have only Python 2 (python@2) and Python 3 (python), there is no explicit formula for Python 3.6. Although those minor updates are mostly irrelevant in most cases and for most users, I will search if some…
has comment: http://stackoverflow.com/comment/96389834
has comment: http://stackoverflow.com/comment/93175146
has comment: http://stackoverflow.com/comment/115801884
has comment: http://stackoverflow.com/comment/107610272
has comment: http://stackoverflow.com/comment/138720467
has comment: http://stackoverflow.com/comment/101784460
has comment: http://stackoverflow.com/comment/102142555
has comment: http://stackoverflow.com/comment/89946781
has comment: http://stackoverflow.com/comment/98187765
has comment: http://stackoverflow.com/comment/89946738
has comment: http://stackoverflow.com/comment/102129913
accepted answer of: http://stackoverflow.com/q/51125013
has comment: http://stackoverflow.com/comment/101805549
has comment: http://stackoverflow.com/comment/107610320
score: 270
answers question: http://stackoverflow.com/q/51125013
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89907851
has comment: http://stackoverflow.com/comment/92678286
has comment: http://stackoverflow.com/comment/100686049
has comment: http://stackoverflow.com/comment/101806502
type: Answer
has comment: http://stackoverflow.com/comment/107604626
has comment: http://stackoverflow.com/comment/93719679
has comment: http://stackoverflow.com/comment/93813782
has comment: http://stackoverflow.com/comment/115795121
downvote count: 0
upvote count: 270

http://stackoverflow.com/comment/89526854
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51097035
type: Comment
has text: I found this to compute exactly number of years https://stackoverflow.com/questions/4436957/pythonic-difference-between-two-dates-in-years that at the end was the hardest part to implement (I am not a Python expert and I have difficulties with dates)

http://stackoverflow.com/comment/89189782
type: QuestionComment
comment on: http://stackoverflow.com/q/51101132
has text: You could catch the exception and return your custom message.
score: 3
type: Comment

http://stackoverflow.com/q/51114820
downvote count: 1
type: Question
answer count: 1
favorite count: 0
score: 0
tagged with: python
has body: I've tried to make a function which quits the game when'q' is entered at any time in the quiz, but it won't work, it is under the intcheck function and is the strchecker, I have another strchecker function maybe that is why it is not working. I know that it needs to break a loop and I am only a beginner to python. score = 0 def strchecker(question): valid=False while not valid: user_Name = input(question) if user_Name!="": valid=True return user_Name else: print("Please do not leave username blank") print("*********************Welcome to the Te Reo Maori Quiz************************\n" "You will be give a series of 6 questions,\nto answer you will enter an answer between 1 and 4.\n\nBest of Luck,and remember if you would like to quit the game just press enter :)\n") user_Name = strchecker("Please enter your username:\n") print("Hi", user_Name,"Here is your first question:\n") keep_going="" while keep_going=="": # List of questions in Quiz question_List = ["How do you write number 1 in Maori?\n1.Tekau 2.Tahi 3.Ono 4.Rua", "What is does tahi + tahi = ?\n1.Rua 2.Rimu 3.Ono 4.Tahi", "How do you write blue in Maori?\n1.Kakariki 2.Kikorangi 3.Whero 4.Ma", "What two colours make blue?\n1.Ma + Whero 2.Kikorangi + Kowhai 3.Whero + Pararui 4.Ma + Mangu", "Who was the god of the forest and birds?\n1.Ranginui 2.Paptuanuku 3.Tane-Mahuta 4.Tangaroa", "Who were Tane Mahutas Parents?\n1.Tangaroa + Ranguinui 2.Punga + Ranganui 3.Tangaroa + Rongo 4.Papatunuku + Ranganui"] # List of Correct Answers correct_Answer = [2, 1, 2, 2, 3, 4] # If user enters anything that is not an integer between 1 and 4 it will be an invalid input def intcheck(question, low, high): valid= False while not valid: error= "Whoops! Please enter an integer between {} and {}\n".format(low, high) try: response = int(input("Please enter your answer or press 'q' to quit")) if low &lt;= response &lt;= high: return response else: print(error) print() except ValueError: print(error) def strchecker(question): valid=False…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51115779
upvote count: 1
has title: Quit a quiz at anytime function - Python

http://stackoverflow.com/a/51146692
type: Answer
downvote count: 0
score: 1
has body: I finally found what was causing the issue, nosklo was close. The Flask-app and the virtualenviroment differed, but not due to installed version - but due to access rights! As the flask-app is handled by the user apache and the python-ldap package was installed with my own user in the virtual enviroment apache didn't have access to reading the package correctly. After adjusting accessrights it finally works. sudo chown -R apache:apache dir/
answers question: http://stackoverflow.com/q/51142585
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51142585

http://stackoverflow.com/q/51066682
accepted answer: http://stackoverflow.com/a/51077677
tagged with: ascii
upvote count: 0
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89123948
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51077677
tagged with: chr
linked to: http://stackoverflow.com/q/4523505
downvote count: 1
type: Question
has body: Via HTTP API I get array of integers, [37,80,68,70,45] - and so on, which represents ascii codes. I need to save it as pdf file. In php code is: $data = file_get_contents($url); $pdf_data = implode('', array_map('chr', json_decode($data))); file_put_contents($file_path.".pdf", $pdf_data); and it works fine. But, in python 3: http_request_data = urllib.request.urlopen(url).read() data = json.loads(http_request_data) pdf_data = ''.join(map(chr, data)) with open(file_path, 'w') as fout: fout.write(pdf_data) The result pdf file is damaged and can't be read What can be the problem? EDIT: Tried with python 2.7, file opens and it's good. Problem not solved, I need it in python 3.6 EDIT: https://stackoverflow.com/a/25839524/7451009 - this solution is ok!
has title: Python 3 - incorrect decoding ascii symbols (Python 2.7 works well)
score: -1

http://stackoverflow.com/comment/89216681
score: 0
type: AnswerComment
has text: Unfortunately he specifically looks for `str` in `name`, which won't work with a dict.
comment on: http://stackoverflow.com/a/51115238
type: Comment

http://stackoverflow.com/comment/89058783
has text: Then yes, compressing them together should reduce disk I/O, assuming the data has plenty of redundancy across the files.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51033260

http://stackoverflow.com/a/51166853
upvote count: 7
has comment: http://stackoverflow.com/comment/89316890
downvote count: 0
has comment: http://stackoverflow.com/comment/89317034
has body: Discord.py commands do not, by default, pass the context. You specify that you would like the context passed by saying so as an argument to the decorator. @bot.command(pass_context=True) async def SendMessage(ctx): await ctx.send('Hello')
type: Answer
score: 7
answers question: http://stackoverflow.com/q/51166800

http://stackoverflow.com/comment/89120154
comment on: http://stackoverflow.com/q/51064911
type: QuestionComment
has text: @Scooby `input()` in python 2 is something like `exec(raw_input())`, I don't believe a url is standard python tokens (not executable code), so the answer to your previous question is probably "no". You'll need to do what the answer suggested, or manually read from stdin.
type: Comment
score: 0

http://stackoverflow.com/a/51027498
has comment: http://stackoverflow.com/comment/89048136
has body: The gremlin-python library gives you full access to the Gremlin language which includes mutating steps like addV() for adding vertices and addE() for adding edges...so, sure, just use Gremlin to add vertices/edges in python as you would with any other language that Gremlin supports.
answers question: http://stackoverflow.com/q/51026783
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51026783
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89048367

http://stackoverflow.com/comment/89262062
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51136760
has text: it is probably native system behavior. Can you try without wxStaticBox just for testing?
score: 0

http://stackoverflow.com/comment/90552667
comment on: http://stackoverflow.com/q/51026296
score: 0
has text: If I understand your question correctly. Django REST has no idea about selection Field widget. You need to put `validator` in your field
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89153050
comment on: http://stackoverflow.com/q/51080326
has text: @ArjunBorkhatariya That is `socketIDfromOpenforPlay`, not `socketIOReqAccept`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89636715
score: 0
type: QuestionComment
type: Comment
has text: We tried on a single threaded test as well. Same problem. We switched to psycopg2, built with multithreading in mind, and have had zero issues.
comment on: http://stackoverflow.com/q/51108552

http://stackoverflow.com/a/67986398
answers question: http://stackoverflow.com/q/51121875
upvote count: 17
downvote count: 0
has body: I found Sunny Pal's answer very useful but I made the copy more specific and added the necessary environment variables and update-alternatives lines so that Java was accessible from the command line in the Python container. FROM python:3.9-slim COPY --from=openjdk:8-jre-slim /usr/local/openjdk-8 /usr/local/openjdk-8 ENV JAVA_HOME /usr/local/openjdk-8 RUN update-alternatives --install /usr/bin/java java /usr/local/openjdk-8/bin/java 1 ...
score: 17
has comment: http://stackoverflow.com/comment/124410547
type: Answer

http://stackoverflow.com/q/51119246
type: Question
tagged with: numpy
score: -2
tagged with: arrays
has title: create structured numpy array in python with strings and int
possible better answer: http://stackoverflow.com/a/51119339
has answer: http://stackoverflow.com/a/51119566
has body: i have this: &gt;&gt;&gt; matriz [['b8:27:eb:d6:e3:10', '0.428s', '198'], ['b8:27:eb:d6:e3:10', '0.428s', '232'], ['b8:27:eb:07:65:ad', '0.796s', '180'], ['b8:27:eb:07:65:ad', '0.796s', '255'], dtype='&lt;U17']` but i need the column `matriz[:, [2]] : [['198'], ['232'], ['180'], ['255']]` to be int and the other columns to be strings, i was trying with structured numpy array but i have this error message, ValueError: invalid literal for int() with base 10: 'b8:27:eb:d6:e3:10' TypeError: a bytes-like object is required, not 'str' i used matriz=np.array(matriz, dtype='U17,U17,i4') i'm using numpy version '1.12.1' for raspberry pi 3, i don't know what i'm doing wrong. thanks a lot
has answer: http://stackoverflow.com/a/51119339
has comment: http://stackoverflow.com/comment/89224333
answer count: 2
has comment: http://stackoverflow.com/comment/89224366
has comment: http://stackoverflow.com/comment/89224459
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89224445
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51119566
type: AnsweredQuestion
downvote count: 3

http://stackoverflow.com/a/51145062
answers question: http://stackoverflow.com/q/51144752
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: The exception ConnectTimeout means that the request timed out while trying to connect to the remote server. Thus, there's no response to get the status code from. it is normal that response variable is None It can be some network issue, make sure the URL you're trying to query is reachable (use curl to verify)

http://stackoverflow.com/comment/89275168
has text: thx for the answer, but this fix also returns False and count 0 instaed of 1. {"success":false,"count":0}
type: AnswerComment
comment on: http://stackoverflow.com/a/51145417
type: Comment
score: 0

http://stackoverflow.com/a/51146919
score: 2
upvote count: 2
has body: Use list comprehension [synset.lemmas(lang='ita') for synset in ll] output [[Lemma('card.n.01.carta')], [Lemma('map.n.01.carta'), Lemma('map.n.01.carta_geografica'), Lemma('map.n.01.cartina'), Lemma('map.n.01.mappa')], [Lemma('sheet.n.02.carta'), Lemma('sheet.n.02.foglio')], [Lemma('document.n.01.atto'), Lemma('document.n.01.carta'), Lemma('document.n.01.documento'), Lemma('document.n.01.incartamento'), Lemma('document.n.01.scrittura')], [Lemma('charter.n.01.carta'), Lemma('charter.n.01.statuto')], [Lemma('menu.n.01.carta'), Lemma('menu.n.01.menu'), Lemma('menu.n.01.menù')], [Lemma('paper.n.01.carta')]]
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51137946
accepted answer of: http://stackoverflow.com/q/51137946
type: Answer

http://stackoverflow.com/a/51092095
score: 13
has comment: http://stackoverflow.com/comment/89206753
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51089217
type: Answer
answers question: http://stackoverflow.com/q/51089217
upvote count: 13
has body: Following is DRF ListCreateAPIView, as you can see *args, **kwargs are directly passing down from standard post method: class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Now, talking about overriding create from CreateModelMixin, you can simply override it as: from rest_framework import generics class YourWonderfulView(generics.ListCreateAPIView): queryset = YourModelClass.objects.all() serializer_class = YourSerializer def create(self, request, *args, **kwargs): # don't need to `self.request` since `request` is available as a parameter. # your custom implementation goes here return Response(response) # `response` is your custom response – e.g. dict, list, list of dicts etc Hope it helps :)
has comment: http://stackoverflow.com/comment/89202128

http://stackoverflow.com/q/51095432
has title: Python code to recursively create a zip file within a zip file for 'n' iterations
tagged with: http://stackoverflow.com/tag/zip
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51096067
has body: I'm trying (and failing) to create a Python function that essentially zips up some text, then zips the archive up again and again (the number based on a parameter). So we'd end up with file1.zip containing file2.zip which in turn contains file3.zip. i.e (file1.zip(file2.zip(file3.zip))). Hope that's articulated well enough. import io import zipfile import gzip hexdata = "5a69702054657374" def zip_it(filename, depth): zip_buffer = io.BytesIO() for i in range(0, depth): with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file: zip_file.writestr(filename + str(i), bytes.fromhex(hexdata).decode("utf-8")) with open(filename + ".zip", "wb") as f: f.write(zip_buffer.getvalue()) if __name__ == '__main__': zip_it("testfile", 3) The above code is what I have so far, it's not quite right, it creates 1 compressed file with the 3files all at the same level and not within each other. I figure this is a recursive problem. Also i'd probably want to do the same with gzip, rar etc - just saying in case if effects any help i get. Thanks
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51096067
tagged with: python

http://stackoverflow.com/a/51013111
type: Answer
upvote count: 2
downvote count: 1
has body: I think need numpy.select what is use for avoid multiple np.where: low = 300 high = 500 m1 = df.Amount &gt; high #inclusive = True is by default, so omited m2 = df['Amount'].between(low, high) a = 100 - (df.Amount - high)/100 b = 100 - (low - df.Amount)/100 df['score'] = np.select([m2, m1], [100,a], default=b) print (df) orderID Amount score 0 0 340 100.0 1 1 200 99.0 2 2 10 97.1 3 3 500 100.0 4 4 700 98.0
score: 1
answers question: http://stackoverflow.com/q/51013059
accepted answer of: http://stackoverflow.com/q/51013059
type: AcceptedAnswer

http://stackoverflow.com/comment/89185031
type: QuestionComment
type: Comment
has text: Do you mean "connect to original website but not connect to the redirected website", or "not even create a connection at all"? The later one is impossible.
comment on: http://stackoverflow.com/q/51098782
score: 0

http://stackoverflow.com/q/51124618
has comment: http://stackoverflow.com/comment/89236437
has answer: http://stackoverflow.com/a/51124947
has comment: http://stackoverflow.com/comment/89234475
has comment: http://stackoverflow.com/comment/89234387
upvote count: 4
has answer: http://stackoverflow.com/a/51127231
favorite count: 0
has answer: http://stackoverflow.com/a/51124950
has comment: http://stackoverflow.com/comment/89234368
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89234321
has title: Regular expression with different number of characters
has comment: http://stackoverflow.com/comment/89234296
linked to: http://stackoverflow.com/q/1155617
tagged with: python
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/51124776
has body: I need to create a regular expression to validate strings. The strings can have only few characters and each character can be repeated only a few number of times. The regular expression should check below conditions. The string can have only a, b, c, d, e as characters. The character 'a' can appear a maximum of 2 times. The character 'b' can appear maximum of 3 times. The character 'c' can appear maximum of 3 times. The character 'd' can be appear maximum of 1 time. The character 'e' can be appear maximum of 1 time. I know that this can be achieved by string functions. But I am trying to do it with regular expressions. Any help on this is highly appreciated.
has comment: http://stackoverflow.com/comment/89238492
has comment: http://stackoverflow.com/comment/89234474
has comment: http://stackoverflow.com/comment/89234283
downvote count: 1
has comment: http://stackoverflow.com/comment/89234349
type: Question
score: 3

http://stackoverflow.com/q/51045716
tagged with: google-cloud-firestore
has comment: http://stackoverflow.com/comment/89108849
tagged with: python
tagged with: amazon-elastic-beanstalk
has answer: http://stackoverflow.com/a/57518507
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41812497
has body: I'm attempting to access Firestore from within an AWS Elastic Beanstalk deployment. The EB application is written using Flask in Python, and everything works correctly locally. But, when I try to deploy to EB, only the first database request succeeds-- the second one freezes my application during the call to .get(). I'm not sure if this is a permissions thing on EB, a Firestore issue, or what! Since no exception is thrown, I can't even deny the request and move on. I do get the following in the logs: [Tue Jun 26 11:29:16.964989 2018] [core:error] [pid 3914] [client 172.31.17.165:22711] Script timed out before returning headers: application.py ... but that's because the script is timing out due to the call to .get() never returning. Here's my full code for this test app: import os from flask import Flask, url_for, redirect, render_template import mimetypes import time import google import firebase_admin from firebase_admin import credentials from firebase_admin import firestore print("=====================================================") print("initializing app") cred = credentials.Certificate("/my/actual/path/to/credentials/is/here.json") firebase_admin.initialize_app(cred) print("done.") print("initializing firestore") db = firestore.client() print("done.") print("initializing flask") application = Flask(__name__) print("done.") @application.route('/doc/&lt;docId&gt;') def doc(docId): docId = docId.lower() documents_ref = db.collection(u'documents') doc_ref = documents_ref.document(docId) print("getting doc") doc = None try: doc = doc_ref.get() except google.cloud.exceptions.NotFound: print("not found.") return render_template('doc.html', message="This document no longer exists .") print("done.") # Here is where I'd normally use the DB snapshot data, but omitted for the question creatorStr = "Someone" timeStr = "a time" docMessage = creatorStr + " sent you a document dated " + timeStr + "." return render_template('doc.html', docMessage=docMessage) if __name__ == …
tagged with: firebase
has comment: http://stackoverflow.com/comment/89127084
has title: Firebase Firestore get() snapshot freezes on second query
has comment: http://stackoverflow.com/comment/89090910
type: Question
has comment: http://stackoverflow.com/comment/89198272
has comment: http://stackoverflow.com/comment/89109038
answer count: 1
has comment: http://stackoverflow.com/comment/89108777
has comment: http://stackoverflow.com/comment/101504569
tagged with: flask
score: 0

http://stackoverflow.com/a/51077649
has comment: http://stackoverflow.com/comment/89144378
downvote count: 0
has comment: http://stackoverflow.com/comment/89144111
has comment: http://stackoverflow.com/comment/89144065
score: 1
has comment: http://stackoverflow.com/comment/89144506
answers question: http://stackoverflow.com/q/51077280
has comment: http://stackoverflow.com/comment/89144446
has comment: http://stackoverflow.com/comment/89144464
has comment: http://stackoverflow.com/comment/89144258
upvote count: 1
type: Answer
has body: The issue you seem to be having is not checking if you found anything before using your result @app.route('/api/update/&lt;lastqnid&gt;') def check_new_entries(lastqnid): result = Trades.query.filter_by(id=lastqnid).first() # Here result may very well be None, so we can make an escape here if result == None: # You may not want to do exactly this, but this is an example print("No Trades found with id=%s" % lastqnid) return redirect(request.referrer) new_entries = Trades.query.filter(Trades.time_recorded &gt; result.time_recorded).all()

http://stackoverflow.com/comment/89051000
comment on: http://stackoverflow.com/q/51028364
has text: df['P'] and adding it to df['V_comb'] for each row.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/51142970
has title: Python C-API: How to use the returned python dictionary in Objective-C?
has answer: http://stackoverflow.com/a/51143451
upvote count: 1
tagged with: ios
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89270235
tagged with: python
tagged with: objective-c
type: UnansweredQuestion
tagged with: cpython
has comment: http://stackoverflow.com/comment/89270119
has body: My Python script app.py has this function for example: def testmethod(x): return {"steps":["hello","world"]} I am using Python C-API in Objective-C as follows: Py_Initialize(); PyObject *pName = PyUnicode_DecodeFSDefault("app"); PyObject* pModule = PyImport_Import(pName); Py_DECREF(pName); PyObject* myFunction = PyObject_GetAttrString(pModule,(char*)"testmethod"); PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(223.22)); PyObject* myResult = PyObject_CallObject(myFunction, args); NSLog(@"Check for dict: %d",PyDict_Check(myResult)); // Prints true!!!!!!!!!!!! So definitely a dictionary After this, I am not really sure how I can convert the myResult to retrieve my dictionary. For doubles and strings, we usually use the PyFloat_AsDouble and PyUnicode_AsUTF8String, PyBytes_AsString functions but I can't seem to find a PyBLAHBLAH_AsDict or equivalent method. double result = PyFloat_AsDouble(myResult); NSLog(@"Result: %f",result);*/ PyObject* pStrObj = PyUnicode_AsUTF8String(myResult); char* zStr = PyBytes_AsString(pStrObj); NSLog(@"String: %@",[NSString stringWithUTF8String:zStr]); I don't have much experience with Objective-C so maybe I am not looking at the right place. How can I convert the PyObject to a NSDictionary? I am basically looking for a C way of accessing the dictionary first (a map for example) which I can then use Objective-C methods to convert to NSDictionary. Similar to how I used PyUnicode_AsUTF8String, PyBytes_AsString and stringWithUTF8String all combined together to get a NSString out of the Python String. Looking for something similar for dictionaries. I have figured out a way to achieve this but I don't know if this is the best possible way of doing this. I modified my python script to use json.dumps to return a string representation of the dictionary. Then in my Objective-C code, I first get the string, then use JSONObjectWithData to convert the json string to a NSDictionary. This works for now but I am curious if there is a better way of doing…
type: Question
has comment: http://stackoverflow.com/comment/89270172
score: 0

http://stackoverflow.com/comment/89273159
has text: @xxbidiao fyi, you can treat local code as library code if it is installed as a package, in which case you can have the same import statements no matter where you are. You can emulate this behavior during development by working with [an editable install](https://stackoverflow.com/questions/35064426/when-would-be-e-editable-option-useful-with-pip-install?lq=1) of your code.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51143997

http://stackoverflow.com/comment/89132394
has text: Possible duplicate of [How can I read inputs as integers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51071281

http://stackoverflow.com/comment/89059467
type: QuestionComment
has text: `const request = async() => {` - you're not **return**ing anything here ... so `}).then((tables) => {` `tables` will be undefined here ... and fetch is usually like `fetch(....).then(response => response.text()).then(result => here is the result of the fetch)`
score: 0
comment on: http://stackoverflow.com/q/51033646
type: Comment

http://stackoverflow.com/a/51145886
accepted answer of: http://stackoverflow.com/q/51141436
has body: Here is the simple solution which i have tried, df['column1'] = df['column1'].str.replace(r'town$','') df['column1'] = df['column1'].str.replace(r'city$','') Likewise for column2 also df['column2'] = df['column2'].str.replace(r'town$','') df['column2'] = df['column2'].str.replace(r'city$','') Output will look like this, column1 column2 abc city efg abc town efg efg abc city efg abc town
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51141436

http://stackoverflow.com/comment/89180724
type: Comment
type: QuestionComment
has text: @AmiHollander i m able to upload files from my own computer i.e local host but unable to do from computers in same network
comment on: http://stackoverflow.com/q/51096434
score: 0

http://stackoverflow.com/q/51012793
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/54938196
has answer: http://stackoverflow.com/a/51013304
has comment: http://stackoverflow.com/comment/89018816
has comment: http://stackoverflow.com/comment/89018702
type: Question
tagged with: normal-distribution
has body: I want to generate normal distribution in the order of the bell. I used this code to generate the numbers: import numpy as np mu,sigma,n = 0.,1.,1000 def normal(x,mu,sigma): return ( 2.*np.pi*sigma**2. )**-.5 * np.exp( -.5 * (x-mu)**2. / sigma**2. ) x = np.random.normal(mu,sigma,n) #generate random list of points from normal distribution y = normal(x,mu,sigma) #evaluate the probability density at each point x,y = x[np.argsort(y)],np.sort(y) #sort according to the probability density which is a code proposed in : Generating normal distribution in order python, numpy but the numbers are not following the bell form. Any ideas? Thank you very much
upvote count: 5
has title: Python : Generate normal distribution in the order of the bell
accepted answer: http://stackoverflow.com/a/51013304
has comment: http://stackoverflow.com/comment/89018652
linked to: http://stackoverflow.com/q/39675085
answer count: 2
score: 5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/54938196
tagged with: python
has comment: http://stackoverflow.com/comment/89018480

http://stackoverflow.com/q/51122141
linked to: http://stackoverflow.com/q/13223633
type: Question
linked to: http://stackoverflow.com/q/1048232
has comment: http://stackoverflow.com/comment/89229827
has title: How to create a custom template tags in Django?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51122280
tagged with: templatetags
has comment: http://stackoverflow.com/comment/89229839
has answer: http://stackoverflow.com/a/76550947
has comment: http://stackoverflow.com/comment/89229466
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89229698
has body: I am new to Django and I am trying to create custom tags in django my custom tag file templatetag/custom_tag.py from django import template from model_file.models import my_Model register = template.Library() @register.simple_tag def get_custom_tag_fn(): return my_Model.objects.all() my html file {% load custom_tag %} {% get_custom_tag_fn as queries %} {% for query in queries %} {{query.json_my_model_data}} {% endfor %} I am not getting any output or error from this code. Can anyone point where I went wrong. for extra information my model.py looks like from django.db import models from jsonfield import JSONField class my_Model(models.Model): json_my_model_data = JSONField()
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89229772
has comment: http://stackoverflow.com/comment/89229927
tagged with: django-templates
has comment: http://stackoverflow.com/comment/89229485

http://stackoverflow.com/q/51125082
tagged with: django
accepted answer: http://stackoverflow.com/a/51125111
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: pandas
score: 3
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89235123
favorite count: 0
has title: How to convert pandas DataFrame to json for django model?
has answer: http://stackoverflow.com/a/51125111
has comment: http://stackoverflow.com/comment/89235093
has body: I have the Pandas DataFrame below and need to convert it to json format with the df.columns wrapped in a Django model name and "fields" fieldname. See below example of how the json should look. How should I do this? df: +-----------------+---------+------+ | Artist | Title | Year | +-----------------+---------+------+ | Michael Jackson | Beat it | 1988 | | Britney Spears | Lucky | 2012 | | Justin Bieber | Baby | 2006 | +-----------------+---------+------+ Json file output: [ { "model": "profiles.track", "fields": { "artist": "Michael Jackson", "title": "Beat it", "year": "1988", } }, { "model": "profiles.track", "fields": { "artist": "Britney Spears", "title": "Lucky", "year": "2012", } }, { "model": "profiles.track", "fields": { "artist": "Justin Bieber", "title": "Baby", "year": "2006", } } ]
tagged with: python
has comment: http://stackoverflow.com/comment/89235106
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/89142133
has text: Any idea how I can handle inputs (`b`) that are smaller than all values in `a`, i.e. for which there is no index? For `b = np.asarray([12, 25, 31, 9])` the result is `array([0, 1, 2, 3])` which is the same as if the last value in `b` (9) was > 40.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51076443

http://stackoverflow.com/q/51057673
has title: Authorization From Command Line Using Token
has comment: http://stackoverflow.com/comment/89105909
upvote count: 1
has comment: http://stackoverflow.com/comment/89106226
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89112613
has comment: http://stackoverflow.com/comment/89107180
score: 1
has answer: http://stackoverflow.com/a/51061547
type: Question
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51061547
tagged with: python
tagged with: google-drive-api
has body: I can get authorization from browser,I use example from site and it's working. SCOPES = 'https://www.googleapis.com/auth/drive' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_id.json', SCOPES) creds = tools.run_flow(flow, store) DRIVE = discovery.build('drive', 'v2', http=creds.authorize(Http())) But I want use it on remote server, after executing above code it show message that I can use "command-line parameter" but I don't know how to use it? I use example from this page: Google Developers

http://stackoverflow.com/q/51157258
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51159779
has comment: http://stackoverflow.com/comment/89297936
type: Question
has answer: http://stackoverflow.com/a/51159779
answer count: 3
accepted answer: http://stackoverflow.com/a/51174043
downvote count: 0
tagged with: keras
has title: No module named 'keras_text_summarization' when running keras-text-summarization
favorite count: 0
has answer: http://stackoverflow.com/a/55426993
tagged with: python
has comment: http://stackoverflow.com/comment/89299995
upvote count: 3
has body: I have cloned keras-text-summarization, then was running according to README.md python seq2seq_train.py and I get: (testenv1) ➜ demo git:(master) python seq2seq_train.py Traceback (most recent call last): File "seq2seq_train.py", line 5, in &lt;module&gt; from keras_text_summarization.library.utility.plot_utils import plot_and_save_history ModuleNotFoundError: No module named 'keras_text_summarization' Note I have installed requirements.txt dependencies with: (testenv1) ➜ keras-text-summarization git:(master) conda install --yes --file requirements.txt Solving environment: done ==&gt; WARNING: A newer version of conda exists. &lt;== current version: 4.4.8 latest version: 4.5.4 Please update conda by running $ conda update -n base conda All requested packages already installed. I was expecting it to run as the documentation said: (this is what the documentation said, I used conda to install) pip install requirements.txt cd demo python seq2seq_train.py which is exactly what I did (except that I used conda instead of pip for the dependencies installation). python env: (testenv1) ➜ keras-text-summarization git:(master) python --version Python 3.6.5 :: Anaconda, Inc. Here is the content of requirements.txt: requirements.txt: scikit-learn keras tensorflow pandas numpy scipy h5py matplotlib I'm not using python on any regular basis maybe I'm missing something very basic?
has answer: http://stackoverflow.com/a/51174043

http://stackoverflow.com/q/51052632
tagged with: bcrypt
tagged with: python
has comment: http://stackoverflow.com/comment/89097796
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89097263
downvote count: 0
has comment: http://stackoverflow.com/comment/89096379
type: Question
has comment: http://stackoverflow.com/comment/89096346
has title: Bcrypt Hash Returns TypeError("Unicode-objects must be encoded before hashing") and Invalid Salt
tagged with: salt-cryptography
tagged with: flask
score: 4
has comment: http://stackoverflow.com/comment/89096278
has comment: http://stackoverflow.com/comment/89096732
has body: I've looked at all the StackOverflow questions related to this but I just cannot seem to figure this out. When I hash a password, and check it against itself, it returns the TypeError "Unicode-objects must be encoded before hashing" with the current code: from scripts import tabledef from flask import session from sqlalchemy.orm import sessionmaker from contextlib import contextmanager import bcrypt (Unrelated Python code...) def hash_password(password): return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt()) def credentials_valid(username, password): with session_scope() as s: user = s.query(tabledef.User).filter( tabledef.User.username.in_([username])).first() if user: return bcrypt.checkpw(password.encode('utf8'), user.password) else: return False When I try and fix this error by setting user.password= user.password.encode('utf8'), I get "Invalid Salt". What is wrong with this code? UPDATE: I am storing the passwords through Flask input from the user: import json import sys import os import plotly import pandas as pd import numpy as np import plotly.graph_objs as go from scripts import tabledef from scripts import forms from scripts import helpers from flask import Flask, redirect, url_for, render_template, request, session, flash, Markup from flask_socketio import SocketIO, emit @app.route('/', methods=['GET', 'POST']) def login(): if not session.get('logged_in'): form = forms.LoginForm(request.form) if request.method == 'POST': username = request.form['username'].lower() password = request.form['password'] if form.validate(): if helpers.credentials_valid(username, password): session['logged_in'] = True session['username'] = username session['email'] = request.form['email'] session['password'] = request.form['password'] return json.dumps({'status': 'Login successful'}) return json.dumps({'status': 'Invalid user/pass'}) return json.dumps({'status': 'Both fields required'}) return render_template('login.html', form=form) user = helpers.get_user() return re…
has comment: http://stackoverflow.com/comment/89097200
has comment: http://stackoverflow.com/comment/89098158
answer count: 1
has comment: http://stackoverflow.com/comment/89096981
has answer: http://stackoverflow.com/a/51054047
favorite count: 0
accepted answer: http://stackoverflow.com/a/51054047
has comment: http://stackoverflow.com/comment/89096411

http://stackoverflow.com/a/51080475
downvote count: 0
score: 1
has body: First take the data for one month and calculate the average of HS for 48 hours periods (starting at 00:00 hours on day 1 up to 24:00 hours on day 2, and so on [note the last period may be less than 48 hours], then repeat this for the next month and so on. To get the average per month take the average for all of the 48 hour periods per month (there will be either 14, 15 or 16 depending on the month). Having said that, would it not be much simpler to take the average of the data for one month, I am not sure why you want to have it first grouped by 48 hours?
answers question: http://stackoverflow.com/q/51079947
upvote count: 1
type: Answer

http://stackoverflow.com/q/51016179
upvote count: 2
tagged with: cyclic
tagged with: python
accepted answer: http://stackoverflow.com/a/51031575
type: AnsweredQuestion
score: 2
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/51016180
possible better answer: http://stackoverflow.com/a/51016250
tagged with: function
has answer: http://stackoverflow.com/a/51016250
has title: Cyclically reduce a list of operands to a single result
has answer: http://stackoverflow.com/a/51031575
answer count: 3
downvote count: 0
favorite count: 0
has body: (This is a rehashed, self-answered version of another question which has been closed because it was not asked well.) I have a list of integers: numbers = [1, 2, 3, 4, 5, 6] My goal is to alternatively apply the sum and multiplication operators successively on these numbers to get a single result. For example, for this input, the result is to be ((1 + 2) * 3 + 4) * 5 + 6 Which reduces to 71. Essentially, this can be broken down into: t1 = 1 + 2 t2 = t1 * 3 t3 = t2 + 4 ... and so on. Bonus: A solution that can generalise to more than two cyclical operations would be welcome.

http://stackoverflow.com/comment/89080936
type: Comment
comment on: http://stackoverflow.com/a/51043919
has text: Maybe you should first put 1 image in 1 file before training because when training a neural network, you have to make sure the images in each batch is randomly sampled from the whole dataset.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89256239
type: Comment
type: QuestionComment
has text: @Dave I added a 3rd argument in exec and it returns 1(one).
comment on: http://stackoverflow.com/q/51134952
score: 0

http://stackoverflow.com/q/51026643
favorite count: 0
tagged with: python-3.x
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has title: Pandas datetime: find the correct year for the first date after a datetime
score: 1
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51026780
tagged with: pandas
downvote count: 0
answer count: 1
has body: I started with a dataframe as follows: In [24]: df = pd.DataFrame( ...: {'date1': ['10/02/2012', '10/02/2012', 'NA/NA/2014', 'NA/NA/2014', '01/02/2014'], ...: 'date2': ['10-Nov', '19-Oct', '26-Nov', '23-Oct', '14-Oct'], ...: 'date3': ['30/06/2011', '30/06/2011', '30/06/2013', '30/06/2013', 'NA']}) ...: In [25]: df Out[25]: date1 date2 date3 0 10/02/2012 10-Nov 30/06/2011 1 10/02/2012 19-Oct 30/06/2011 2 NA/NA/2014 26-Nov 30/06/2013 3 NA/NA/2014 23-Oct 30/06/2013 4 01/02/2014 14-Oct NA I have managed to convert the dates into datetime objects. Therefore I have the following dataframe: In [26]: df["date1"] = pd.to_datetime(df["date1"], errors="coerce", dayfirst=True, infer_datetime_format=True) ...: df["date3"] = pd.to_datetime(df["date3"], errors="coerce", dayfirst=True, infer_datetime_format=True) ...: df["date2"] = pd.to_datetime(df["date2"], errors="coerce", dayfirst=True, format="%d-%b") ...: df ...: Out[26]: date1 date2 date3 0 2012-02-10 1900-11-10 2011-06-30 1 2012-02-10 1900-10-19 2011-06-30 2 NaT 1900-11-26 2013-06-30 3 NaT 1900-10-23 2013-06-30 4 2014-01-02 1900-10-14 NaT Because date2 had no year encoding set all the year values to 1900. However, I need the first date in date2 that was reached AFTER date3 and this datetime's associated year. ALSO NOTE: When date3 is NaT I need to look backwards from date1 to fill in the year of date2. This can be seen in df.iloc[4,:] So I want the output dateframe to be: date1 date2 date3 0 2012-02-10 2011-11-10 2011-06-30 1 2012-02-10 2011-10-19 2011-06-30 2 NaT 2013-11-26 2013-06-30 3 NaT 2013-10-23 2013-06-30 4 2014-01-02 2013-10-14 NaT This is harder than just using date3.year because sometimes date3 is late in the year (e.g. 30/12/2013 -> 2013-12-30) and so date2 will be the first date in the next year (i.e. 14-Oct -> 1900-10-14 -> 2014-10-14). Furthermore, when this returns nan I need my datetime to be robust enough to return NaT. So I need to find the next following year AFTER date3 which matches the day-month in da…
accepted answer: http://stackoverflow.com/a/51026780

http://stackoverflow.com/a/51043625
has comment: http://stackoverflow.com/comment/89131556
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89123736
has body: Looks as if your JSON is actually a dict. You can create an instance of Region easily, since the dict properties and the instance attributes have the same name, by unpacking the dict item with two **: regions = [] for item in data['Output']['Rect']: regions.append( Region(**item) ) for region in regions: print( region ) Output: {"x"=34, "y"=51, "width"=100, "height"=100} {"x"=14, "y"=40, "width"=4, "height"=6} ( after I have changed your __str__ to: ) def __str__(self): return '{{"x"={}, "y"={}, "width"={}, "height"={}}}'.format(self.x, self.y, self.width, self.height)
type: Answer
score: 5
answers question: http://stackoverflow.com/q/51043464
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51043464

http://stackoverflow.com/q/51114186
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51114278
tagged with: datetime
tagged with: python
has body: i am working on a project where i need to match the given date(taken from user) with today and i need to run the code only the date is greater than today i tried various ways but it is reflecting some conversion errors and i used below code where i am getting the same output as false even if i enter the days previous to today and also after today .. i think i gone wrong through the conversion i think . i think i am comparing the two strings . but i cant get the expected output for the same even if i tried various ways . please help me to solve the problem here is the sample code that i tired in my project from datetime import date today = date.today().strftime('%d-%m-%y') examdate=input('enter date in dd-mm-yy') print(examdate&gt;today) input and outputs (current date is 30-06-18) enter date in dd-mm-yy29-06-18 False enter date in dd-mm-yy29-06-18 False enter date in dd-mm-yy06-06-96 False enter date in dd-mm-yy20-05-20 False
has title: match the given date taken from user with current date
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89214683
type: Question
accepted answer: http://stackoverflow.com/a/51114278
has comment: http://stackoverflow.com/comment/89214627
score: 0
answer count: 1
tagged with: string

http://stackoverflow.com/a/51062884
has body: Like @timgeb mentioned, in Python versions before 3.6, dictionary order is effectively random. If you want to still use a comprehension in Python 3.5 and below, you can use a list comprehension of tuples instead: OrderedDict([(k, v) for k, v in dict_cg.items() if not np.isnan(v[1])])
answers question: http://stackoverflow.com/q/51062644
has comment: http://stackoverflow.com/comment/89116535
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/51102120
answers question: http://stackoverflow.com/q/51101834
downvote count: 0
score: 1
type: Answer
has body: You could use very long and rather unreadable lambda function: get_middle = (lambda s: (s[int(len(s)/2)]) if len(s)%2 == 1 else (s[int(len(s)/2)-1] + s[int(len(s)/2)])) but, it is significantly better not to find target in shorten every function. Readability counts.
upvote count: 1

http://stackoverflow.com/comment/89271344
has text: @James , I have been struggling for days now, need help!
score: 0
comment on: http://stackoverflow.com/q/51141762
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51136581
downvote count: 0
has answer: http://stackoverflow.com/a/59155822
favorite count: 0
has title: How do I create a normal distribution in pytorch?
has answer: http://stackoverflow.com/a/62919933
upvote count: 25
has answer: http://stackoverflow.com/a/51136932
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/111267312
tagged with: python
score: 25
linked to: http://stackoverflow.com/q/44328530
tagged with: normal-distribution
has body: I want to create a random normal distribution with a given mean and std.
has answer: http://stackoverflow.com/a/79381895
tagged with: pytorch
has answer: http://stackoverflow.com/a/58401290
has answer: http://stackoverflow.com/a/51139265
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/78752307
has answer: http://stackoverflow.com/a/55202492

http://stackoverflow.com/comment/89354087
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51156542
has text: The project will quickly grow in size, with more and more classes, and other scripts will eventually come to the `project/` dir level. That would be a mess.
type: QuestionComment

http://stackoverflow.com/comment/101690725
comment on: http://stackoverflow.com/q/51076943
type: Comment
type: QuestionComment
score: 1
has text: I have this exact same issue; did you ever get it resolved @Suge?

http://stackoverflow.com/comment/89203551
has text: @OregonJim I am seeing the issue in here roughly for every 200,000 times. I am running it on embedded equipment. I am not seeing this issue when I run on QEMU. Do you think there are some hardware factors that can effect the subprocess.PIPE?
comment on: http://stackoverflow.com/q/51105517
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51105841
has body: I have a bit of code that runs many thousands of times in my project: def resample(freq, data): output = [] for i, elem in enumerate(freq): for _ in range(elem): output.append(data[i]) return output eg. resample([1,2,3], ['a', 'b', 'c']) => ['a', 'b', 'b', 'c', 'c', 'c'] I want to speed this up as much as possible. It seems like a list comprehension could be faster. I have tried: def resample(freq, data): return [item for sublist in [[data[i]]*elem for i, elem in enumerate(frequencies)] for item in sublist] Which is hideous and also slow because it builds the list and then flattens it. Is there a way to do this with one line list comprehension that is fast? Or maybe something with numpy? Thanks in advance! edit: Answer does not necessarily need to eliminate the nested loops, fastest code is the best
has comment: http://stackoverflow.com/comment/89199488
has comment: http://stackoverflow.com/comment/89198824
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89198846
tagged with: python
has answer: http://stackoverflow.com/a/51105929
has comment: http://stackoverflow.com/comment/89198861
has comment: http://stackoverflow.com/comment/89198822
has comment: http://stackoverflow.com/comment/89198981
score: 4
has title: Faster Python List Comprehension
has comment: http://stackoverflow.com/comment/89198881
answer count: 3
has comment: http://stackoverflow.com/comment/89198770
downvote count: 1
has answer: http://stackoverflow.com/a/51105894
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89198904
has answer: http://stackoverflow.com/a/51105941
linked to: http://stackoverflow.com/q/3633140

http://stackoverflow.com/a/51053647
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51053579
upvote count: 1
has body: Just use two separate list comprehensions with conditional statements In [518]: d = {'a': 1, 'b':2, 'c': 3, 'D':4, 'E': 5} In [519]: arr = ' a b c 1125' In [520]: list1 = [d[a] for a in arr.split() if a in d] In [521]: list1 Out[521]: [1, 2, 3] In [522]: list2 = [a for a in arr.split() if a not in d] In [523]: list2 Out[523]: ['1125'] Note that the contents of list2 will be of type str unless you explicitly cast them to an int. This is because arr is of type str which can be achieved like so: list2 = [int(a) for a in arr.split() if a not in d]

http://stackoverflow.com/q/51056745
tagged with: socket.io
type: Question
tagged with: javascript
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/51056920
answer count: 1
has title: Error while connecting on Flask socketio app
linked to: http://stackoverflow.com/q/24058157
type: UnansweredQuestion
tagged with: python
tagged with: heroku
has body: I have a Flask socket.io app (backend) hosted on Heroku. I have frontend with the JS code to connect to the host at my local machine. I am getting the following error while trying to connect to the server. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://deploy-appp.herokuapp.com/socket.io/? EIO=3&amp;transport=polling&amp;t=MH05dP-. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://deploy-appp.herokuapp.com/socket.io/? EIO=3&amp;transport=polling&amp;t=MH05f5A. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Link to the backend application JS code for socket connection: &lt;script type="text/javascript"&gt; var socket = io.connect('https://deploy-appp.herokuapp.com/'); socket.on('connect', function() { console.log('connected'); }); socket.on('message', function(msg) { document.getElementById('messages').append('&lt;li&gt;'+msg+'&lt;/li&gt;'); console.log('Received message'); }); function send() { console.log(document.getElementById('myMessage').value) socket.send(document.getElementById('myMessage').value) }; &lt;/script&gt;

http://stackoverflow.com/comment/89050905
score: 0
type: Comment
has text: I am unsure ... normally answers should contain more then one line of code - thats what comments are for ...
type: AnswerComment
comment on: http://stackoverflow.com/a/51029253

http://stackoverflow.com/a/56243141
has body: My solution is try to using this code plt.savefig('pic.png',bbox_inches='tight') , instead of using plt.show()
score: 0
answers question: http://stackoverflow.com/q/51111216
type: Answer
has comment: http://stackoverflow.com/comment/99105038

http://stackoverflow.com/comment/89256777
has text: @a_guest you are correct, i found a similar answer...the real thing i wanted to achieve was train the input as well by assuming there was a layer before it, since i dont know how to do that, i decided to encode the input as weights and train them
comment on: http://stackoverflow.com/q/51133972
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89100677
comment on: http://stackoverflow.com/q/51054397
type: Comment
type: QuestionComment
has text: @joran, just ignore what I previously have. if I have 3 profile pictures, and click on one of them, I want it to redirect to that profile
score: 0

http://stackoverflow.com/a/55042458
downvote count: 0
has body: Import sys does not give you direct access to any of the names inside sys itself To access those you need to prefix them with sys: sys.argv sys.exit() If you want use argv instead sys.argv try from sys import *
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51112761
type: Answer

http://stackoverflow.com/comment/89133914
has text: Yea, was the return True. Thanks :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51071746

http://stackoverflow.com/q/51037433
favorite count: 0
has answer: http://stackoverflow.com/a/51037535
has title: Why does pandas 2min bucket print NaN although all my row values are numbers (not NaN)?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51037535
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
has body: I know that in my data response_bytes column does not have NaN values because when I run: data[data.response_bytes.isna()].count() I get as a result 0. When I then run 2 min bucket mean and then head I get NaN: print(data.reset_index().set_index('time').resample('2min').mean().head()) index identity user http_code response_bytes unknown time 2018-01-31 09:26:00 0.5 NaN NaN 200.0 264.0 NaN 2018-01-31 09:28:00 NaN NaN NaN NaN NaN NaN 2018-01-31 09:30:00 NaN NaN NaN NaN NaN NaN 2018-01-31 09:32:00 NaN NaN NaN NaN NaN NaN 2018-01-31 09:34:00 NaN NaN NaN NaN NaN NaN Why do response byte time bucketing mean have NaN values? I wanted to experiment and learn how time bucketing works in pandas. So I used the log file: http://www.cs.tufts.edu/comp/116/access.log as input data, then loaded it into pandas DataFrame and then applied time bucket 2 min (for the first time in my life) and ran mean(), I wasn't expecting to see any NaN in the response_bytes column because all values are not NaN. Here is my full code: import urllib.request import pandas as pd import re from datetime import datetime import pytz pd.set_option('max_columns',10) def parse_str(x): """ Returns the string delimited by two characters. Example: `&gt;&gt;&gt; parse_str('[my string]')` `'my string'` """ return x[1:-1] def parse_datetime(x): ''' Parses datetime with timezone formatted as: `[day/month/year:hour:minute:second zone]` Example: `&gt;&gt;&gt; parse_datetime('13/Nov/2015:11:45:42 +0000')` `datetime.datetime(2015, 11, 3, 11, 45, 4, tzinfo=&lt;UTC&gt;)` Due to problems parsing the timezone (`%z`) with `datetime.strptime`, the timezone will be obtained using the `pytz` library. ''' dt = datetime.strptime(x[1:-7], '%d/%b/%Y:%H:%M:%S') dt_tz = int(x[-6:-3])*60+int(x[-3:-1]) return dt.replace(tzinfo=pytz.FixedOffset(dt_tz)) # data = pd.read_csv(StringIO(accesslog)) url = "http://www.cs.tufts.edu/comp/116/access.log" accesslog = urllib.request.urlopen(url).read().decode('utf-8') fields = ['host', 'identity', '…

http://stackoverflow.com/comment/89238468
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51126737
score: 0
has text: Hi Matthew, I'm already using entry points to register my implementation packages. However, I don't know how to approach a mapping of those imports, so developers would always every use that one api package to import from. In ```Application A``` they should then automatically use ```Implementation A```, while in ```Application B``` the scripts should always use ```Implementation B```.

http://stackoverflow.com/q/51136836
upvote count: 3
type: Question
tagged with: ticker
tagged with: stocks
tagged with: dataframe
has answer: http://stackoverflow.com/a/51136988
tagged with: pandas
answer count: 1
downvote count: 0
has title: separating each stock data into individual dataframe
has comment: http://stackoverflow.com/comment/89277813
favorite count: 0
has body: I took historical data of 100 stocks. It is a single file with all tickers with corresponding data. How to loop such that each ticker data gets separated in dataframe with its own name? I've tried this but this doesnt work. for ticker in stocks: print(ticker) tick=pd.DataFrame(data.loc[(data.ticker==ticker)]) tick['returns']=tick.close.pct_change() value='daily_returns_'+str(ticker) value=tick'date' value['returns']=tick['returns'] print(value) ex=str(value)+'.csv' value.to_csv(ex)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89277800
tagged with: python
score: 3

http://stackoverflow.com/q/51017114
favorite count: 0
accepted answer: http://stackoverflow.com/a/51017167
upvote count: 1
tagged with: python
tagged with: module
type: AnsweredQuestion
score: 1
has body: Following code will find roots of a polynomial: import numpy as np print("Roots of the first polynomial:") print(np.roots([1, -2, 1])) But i cannot get output for roots if use: import numpy as np print("Roots of the first polynomial:") print(roots([1, -2, 1])) I assume since roots is a sub module, we need to access roots using alias of numpy ie np; I could not find in detail about roots, please share your thoughts on the same.
tagged with: import
has title: Finding roots of a polynomial using numpy
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51017167

http://stackoverflow.com/comment/89091836
score: 2
has text: The original list referred to by `lst` will only get garbage-collected if there are no other references to it, so this is not always true
type: Comment
comment on: http://stackoverflow.com/a/51050368
type: AnswerComment

http://stackoverflow.com/q/51073309
possible better answer: http://stackoverflow.com/a/75865177
has body: I was trying to replicate this camera calibration code. When I run my script, the calibration process won't stop for about 30 minutes (I expected the intrinsic camera matrix for the output). What is wrong with my code? Why does the calibration process take so long? This is my code import os import cv2 import numpy as np # DUMMY TEST FilepathCalib = './data' # Declaring global variable img_calib_set = [] points_3d_sample = np.zeros((6*7,3), np.float32) points_3d_sample[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2) points_2d = [] points_3d = [] # Loading calibration image dataset for img_calib in os.listdir(FilepathCalib): img_calib = cv2.imread(FilepathCalib + '/' + img_calib, 0) img_calib_set.append(img_calib) # Finding checkerboard corners pattern in image dataset for img in img_calib_set: ret_val, corner = cv2.findChessboardCorners(img, (7,9), None) if ret_val == True: points_3d.append(points_3d_sample) points_2d.append(corner) # Extracting camera parameters ret_val, intrinsic_mat, dist_coef, rot_vector, tran_vector = cv2.calibrateCamera(points_3d, points_2d, img_calib_set[0].shape[::-1], None, None) print(intrinsic_mat) And here's my sample calibration image
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/51075677
downvote count: 0
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/51075677
has answer: http://stackoverflow.com/a/75865177
tagged with: python
has answer: http://stackoverflow.com/a/74354972
tagged with: computer-vision
tagged with: camera-calibration
has title: Why does the camera calibration in opencv-python takes more than 30 minutes?
tagged with: opencv
type: AnsweredQuestion
upvote count: 5

http://stackoverflow.com/q/51144869
downvote count: 0
duplicate of: http://stackoverflow.com/q/12994442
has answer: http://stackoverflow.com/a/51144975
answer count: 3
has answer: http://stackoverflow.com/a/51144999
has body: I am trying to read and write a json file using python script(I have embedded this python block inside a shell script) test.json { "environments": ["dev", "qa", "load", "prod"], "region": ["asia", "europe", "americas", "asia-pacific"], "product": ["mobile", "internet", "kiosk", "branch"], "ID": ["mobile:111", "internet:222", "kiosk:333", "branch:444"] } I am trying to add region(uk), before that I want to check and add if it is not avilable in list. Below is my python code and I am able to update the value reg_val="uk" a_dict = {} try: with open('test.json') as data_file: data = json.load(data_file) temp_list = [] for dicObj in data["region"]: temp_list.append(dicObj) temp_list.append(reg_val) data["region"] = temp_list a_dict["region"] = data["region"] with open('test.json','w') as f: f.write(json.dumps(a_dict, indent=4, sort_keys=True, encoding="utf-8")) except IOError as io: print "ERROR: ", io I was able to update the json file, but it removes the other lists.The output I see is { "region": [ "asia", "europe", "americas", "asia-pacific", "uk" ] }
favorite count: 0
possible better answer: http://stackoverflow.com/a/51144999
has comment: http://stackoverflow.com/comment/89274202
tagged with: python
accepted answer: http://stackoverflow.com/a/51144975
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
has answer: http://stackoverflow.com/a/51144976
type: Question
has title: Write json file using python
linked to: http://stackoverflow.com/q/12994442

http://stackoverflow.com/a/51021667
upvote count: 1
has comment: http://stackoverflow.com/comment/89036083
has comment: http://stackoverflow.com/comment/89036935
answers question: http://stackoverflow.com/q/51021497
type: Answer
has comment: http://stackoverflow.com/comment/89036194
downvote count: 0
score: 1
has body: You may use r'(?m)^[A-Z]+\r?\n\S+\s+(\d+)(?:\r?\n\S+\s+\1)+$' See the regex demo. Details (?m) - enable re.MULTILINE mode to make ^ / $ match start and end of lines respectively ^ - start of a line [A-Z]+ - 1+ uppercase ASCII letters (adjust as you see fit) \r?\n - a line break like CRLF or LF \S+ - 1+ non-whitespace chars \s+ - 1 whitespaces (or use \t if a tab is the field separator) (\d+) - Capturing group 1, one or more digits (?:\r?\n\S+\s+\1)+ - one or more repetitions of a line break followed with 1+ non-whitespaces, 1+ whitespaces and the same value as in Group 1 since \1 is a backreference to the value stored in that group $ - end of line. In Python, use re.finditer: for m in re.finditer(r'(?m)^[A-Z]+\r?\n\S+\s+(\d+)(?:\r?\n\S+\s+\1)+$', text): print(m.group()) See the Python demo.

http://stackoverflow.com/q/51035731
has comment: http://stackoverflow.com/comment/89063566
has answer: http://stackoverflow.com/a/51035794
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51035791
has comment: http://stackoverflow.com/comment/89063605
has comment: http://stackoverflow.com/comment/89063650
upvote count: 3
duplicate of: http://stackoverflow.com/q/2960772
linked to: http://stackoverflow.com/q/1225637
has comment: http://stackoverflow.com/comment/89063729
has comment: http://stackoverflow.com/comment/89063704
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51035794
answer count: 3
linked to: http://stackoverflow.com/q/2960772
has comment: http://stackoverflow.com/comment/89063610
has comment: http://stackoverflow.com/comment/89063513
has comment: http://stackoverflow.com/comment/89063598
tagged with: variables
tagged with: string
has comment: http://stackoverflow.com/comment/89063638
has comment: http://stackoverflow.com/comment/89063651
has answer: http://stackoverflow.com/a/51035752
favorite count: 0
duplicate of: http://stackoverflow.com/q/1225637
accepted answer: http://stackoverflow.com/a/51035791
has title: Insert Repeated Variables into String
has body: Is there a better way to insert variables into a string? Something, say, less repetitive than... with open('zlog.txt', 'a') as log: log.write('[ %s ] Finished scrolling.\n[ %s ] #%s clicks.\n[ %s ] Number of Elements: %s\n' % (finish_time, finish_time, str(x), finish_time, str(len(elements)))) I am constantly reusing finish_time in order to timestamp entries in a log. ... % (finish_time, finish_time, str(x), finish_time, str(len(elements)))
tagged with: python

http://stackoverflow.com/comment/132553513
type: Comment
has text: Try x.geoms[0] (see [here](https://shapely.readthedocs.io/en/latest/reference/shapely.MultiPoint.html) )
comment on: http://stackoverflow.com/a/51060918
score: 5
type: AnswerComment

http://stackoverflow.com/comment/89063164
score: 1
comment on: http://stackoverflow.com/q/51035654
type: Comment
type: QuestionComment
has text: What have you tried so far and what went wrong?

http://stackoverflow.com/a/51101942
answers question: http://stackoverflow.com/q/51101834
type: Answer
has body: You don't need the 2nd return : return s[int(len(s)/2)] if len(s)%2 == 1 else s[int(len(s)/2)-1] + s[int(len(s)/2)] The inline if else is the same as the ternary operator you can find in other languages, and you can use it to affect a variable
score: 0

http://stackoverflow.com/q/51143814
favorite count: 0
duplicate of: http://stackoverflow.com/q/2922185
tagged with: python
has title: Python3/Windows: module 'os' has no attribute 'mkfifo'
tagged with: python-3.x
tagged with: subprocess
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: mkfifo
type: Question
score: 3
tagged with: pipe
has comment: http://stackoverflow.com/comment/89272074
linked to: http://stackoverflow.com/q/2922185
has body: I'm currently on Windows 10 using Python 3.6, and I've hit a snag on getting this following code to work which can be found here: https://github.com/Kautenja/gym-super-mario-bros/blob/master/gym_super_mario_bros/nes_env.py: if not os.path.exists(self._pipe_in_name): os.mkfifo(self._pipe_in_name) I'm looking at other questions,s and mkfifo is Linux. Is there an equivalent where I can open up that specific path from Windows without a headache?
downvote count: 0

http://stackoverflow.com/comment/89136139
score: 0
type: AnswerComment
has text: f-strings are a way to dynamically format python strings - https://realpython.com/python-f-strings/
type: Comment
comment on: http://stackoverflow.com/a/51073019

http://stackoverflow.com/a/51056330
has comment: http://stackoverflow.com/comment/89127332
has comment: http://stackoverflow.com/comment/89127746
has comment: http://stackoverflow.com/comment/89126062
score: 1
has comment: http://stackoverflow.com/comment/89125998
has comment: http://stackoverflow.com/comment/89170303
has comment: http://stackoverflow.com/comment/89126343
has body: First of all this is a apple to orange comparison. Scrapy parsing is just in memory parsing at client side, while selenium is a browser controlling, your get actual rendered dom html and ofcourse it is way slower than scrapy in that case The thing is anything that loads JS/CSS/Images will be much slower than the ones which just do parse the main html file. When you do whatever = response.xpath('//whatever') You have no overhead, it is just runs the xpath on the html document in memory. When you do whatever = browser.find_elements_by_xpath('//whatever') It is JSON RPC command, so you have http http/socket your code ----&gt; browser agent ------------&gt; browser This has a much high overhead. Also browser is always slower then just downloading the html and parsing it
downvote count: 0
has comment: http://stackoverflow.com/comment/89166129
has comment: http://stackoverflow.com/comment/89126228
type: Answer
has comment: http://stackoverflow.com/comment/89127466
has comment: http://stackoverflow.com/comment/89166180
answers question: http://stackoverflow.com/q/51055025
upvote count: 1

http://stackoverflow.com/q/51154452
accepted answer: http://stackoverflow.com/a/51171849
type: Question
has body: I am trying to deploy a python application and I am receiving the following error message: ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section. My app.yaml is: runtime: python runtime_config: python_version: 3 env: flex service: newservice handlers: - url: / script: hello.py manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 I believe the problem is related to the yaml file, since I have deployed a sample application previously with no problems (using entrypoint on my yaml), then when I added a new python script and referred to it on the yaml file (using the handlers, to run my message block) I started to get this error. Edit: after GAEFan's answer my hello has included a handler for readiness_check as: def post(): self.response.headers['Content-Type'] = 'application/json' obj = { 'status': 200, } self.response.out.write(json.dumps(obj)) webapp2.WSGIApplication([ ('/readiness_check', post()) ], debug=True)
has comment: http://stackoverflow.com/comment/89307862
has title: Error while deploying python in Google App Engine
has answer: http://stackoverflow.com/a/51171849
linked to: http://stackoverflow.com/q/45842772
answer count: 2
has answer: http://stackoverflow.com/a/51156604
downvote count: 0
tagged with: deployment
favorite count: 0
upvote count: 2
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/89307977
tagged with: python
has comment: http://stackoverflow.com/comment/89308055
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/51156604
tagged with: cgi

http://stackoverflow.com/comment/89057699
score: 0
has text: Wen, yes quantiles
type: QuestionComment
comment on: http://stackoverflow.com/q/51032552
type: Comment

http://stackoverflow.com/comment/89115607
has text: Hi @SaeedBabashahi, I need to validate the incoming data, how can I use serializers here?
type: QuestionComment
comment on: http://stackoverflow.com/q/51062823
score: 0
type: Comment

http://stackoverflow.com/comment/89089493
has text: I think i understand. Tkank you, i will try it.
comment on: http://stackoverflow.com/q/51048776
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89210835
score: 2
type: Comment
comment on: http://stackoverflow.com/q/51111992
type: QuestionComment
has text: What is "first number"(first digit or the entire number)? Should the commas or the decimals also be extracted?

http://stackoverflow.com/comment/89037727
has text: please show the code that you have tried. You can edit your question to add it
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51022504

http://stackoverflow.com/q/51120020
tagged with: matplotlib
tagged with: scatter-plot
answer count: 2
tagged with: pandas
has title: Matplotlib scatter plot gives ValueError(msg.format(c.shape, x.size, y.size)) when specifying colors
score: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: Im stuck on an assignment where they have us use data from https://raw.githubusercontent.com/Geoyi/Cleaning-Titanic-Data/master/titanic_original.csv Using matplotlib I need to: Create a scatterplot with the Fare paid and the Age, differ the plot color by gender. So far I am having trouble getting the color to be plotted by the gender. So far this is what I have: import pandas as pd import matplotlib.pyplot as plt titanic = pd.read_csv('https://raw.githubusercontent.com/Geoyi/Cleaning-Titanic-Data/master/titanic_original.csv') plt.scatter(titanic['age'],titanic['fare'],alpha=0.5) plt.show() When I tried this: plt.scatter(titanic['age'],titanic['fare'], alpha=0.5,c=titanic['sex']) plt.show() it gave me a raise ValueError(msg.format(c.shape, x.size, y.size))
possible better answer: http://stackoverflow.com/a/61628759
upvote count: 2
has answer: http://stackoverflow.com/a/51120062
has answer: http://stackoverflow.com/a/61628759
downvote count: 1
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/51120062

http://stackoverflow.com/q/51059479
tagged with: python
has title: wxpython flexgridSizer button bottom right corner
type: AnsweredQuestion
type: Question
has body: I would like to put the "Enregistrer" button to the bottom right corner: Here is my code : sizer = wx.FlexGridSizer(10, 6, 10, 10) # here i had all the other stuff an put it in the sizer # self refere to a wx.panel # SPACE for v in range(0, 40): sizer.Add(10,10,wx.EXPAND) btn = wx.Button(self, wx.ID_ANY, "Enregistrer") btn.Bind(wx.EVT_BUTTON, self.save) sizer.Add(btn, 2, wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT) self.SetSizer(sizer) I can't fiqure it out why the button dosen't goes to the corner. Can you please help me ?
tagged with: wxwidgets
score: 0
has answer: http://stackoverflow.com/a/51060820
accepted answer: http://stackoverflow.com/a/51060820
answer count: 1
tagged with: user-interface
tagged with: wxpython

http://stackoverflow.com/comment/89121386
has text: @edyvedy13 - It seems I ma lost. :( Sorry. What is expected output for more columns (maybe next 6) ?
type: AnswerComment
comment on: http://stackoverflow.com/a/51065103
score: 0
type: Comment

http://stackoverflow.com/q/51070622
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51070785
upvote count: 1
tagged with: python
has body: I have two lists with just one element as follows(each of these two lists always contains only one element): Vnew = [600] Newoints2 = [(2447,3480)] I'm trying to bring both of them together using the following code sample: for i, key in enumerate(Vnew2): pos3[key] = newpoints2[i] But this returns an error as IndexError: list assignment index out of range I actually did this one for other lists which have more than one element. It worked fine and got the output as {0:(1245,674),1:(2457,895),...} Can someone find the mistake here?
tagged with: enumerate
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89131491
has comment: http://stackoverflow.com/comment/89131269
type: Question
has answer: http://stackoverflow.com/a/51070785
has comment: http://stackoverflow.com/comment/89131335
has title: Enumerate - Python loop
downvote count: 0
answer count: 1
score: 1
favorite count: 0

http://stackoverflow.com/a/51153911
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51153797
has comment: http://stackoverflow.com/comment/89291158
has body: You are passing a single string as parameter to the function pymysql.connect(), but it expects 3 parameters at least: host, user, db. So the string db_file gets loaded as the first parameter (host), nothing gets in the other two, generating the error. The correct way is something like this: host = '127.0.0.1', user ='python' db ='test' db_conn = pymysql.connect(host, user, db) UPDATE: if you want to use a connection file directly try using Option Files: https://dev.mysql.com/doc/connector-python/en/connector-python-option-files.html
answers question: http://stackoverflow.com/q/51153797
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89291730

http://stackoverflow.com/a/51214327
has comment: http://stackoverflow.com/comment/89452201
has comment: http://stackoverflow.com/comment/89436791
type: Answer
answers question: http://stackoverflow.com/q/51163326
has comment: http://stackoverflow.com/comment/89488218
upvote count: 1
has comment: http://stackoverflow.com/comment/89492078
has body: Christopher Jones' answer led me to salvation, but the reality is that the problem was far more subtle than this. I wound up creating the sqlnet.ora files in the home directories of two machines - one that did work and one that didn't. I noticed a striking difference in the log files. The "good" box had this entry: 2018-07-06 09:59:36.726 : nnftrne:Using tnsnames.ora address (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = my.oracle.db.host)(PORT = 1521)) (CONNECT_DATA = (SID = my_sid))) for name ENV_CONNECTION The "bad" box had this entry: 2018-07-06 10:02:12.879 : nnftrne:Using tnsnames.ora address (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = my.oracle.db.host)(PORT = 1521 for name ENV_CONNECTION What this wound up translating to was one of the silliest and most surprising whitespace limitations I've ever encountered. Remember that the wallet being used (along with its corresponding tnsnames.ora file) is used in Java as well. My assumption was that both Python and Java would behave similarly when reading from this shared resource in that they would disregard newlines and whitespace where necessary. I was clearly wrong. The "good" box had entries that looked like this: ENV_CONNECTION = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = my.oracle.db.host)(PORT = 1521)) (CONNECT_DATA = (SID = my_sid) ) ) The "bad" boxes have entries that look like this: ENV_CONNECTION = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = my.oracle.db.host)(PORT = 1521 )) (CONNECT_DATA = (SID = my_sid) ) ) The difference is subtle enough, but obvious to Python: if the tnsnames.ora file is not properly formatted, cx_Oracle will fail to parse it, whereas Java is fine with this. This feels like a bug on its own right, but fixing the formatting allows Python to connect again.
score: 1
downvote count: 0

http://stackoverflow.com/comment/89104620
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51056871
type: Comment
has text: https://gyazo.com/b6f8ca38c069476cc6522cf7bfaf181e - thank you, it looks pretty barbaric but it works, 50 links with 8 threads in 16 seconds, amazing, with one thread it'd take ~80 seconds! I'll keep playing with it.

http://stackoverflow.com/q/51025540
tagged with: windows
tagged with: python
type: UnansweredQuestion
has body: I am trying to figure out why my output was ending early when listing directories on from my hard drive to a website. I removed the error message for debugging mode and got this error: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\Huang.LabTech2\\Desktop\\Images\\2017 Data\\Air Tractor 402/Air Tractor 402/5-10-2017/IR Filter' I'm not sure why it is looking for the second Air Tractor 402 folder when running, but this happens with other folders as well: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\Huang.LabTech2\\Desktop\\Images\\2017 Data\\UAV/UAV/Bobby_Hardin/8-16' My code: from flask import Flask, abort, send_file, render_template, render_template_string import os import remoteSensingData app = Flask(__name__) @app.route('/', defaults={'req_path': ''}) @app.route('/&lt;path:req_path&gt;') def dir_listing(req_path): BASE_DIR = os.path.abspath(r'C:/Users/Huang.LabTech2/Desktop/Images/2017 Data/') # Joining the base and the requested path abs_path = os.path.join("c:", BASE_DIR, req_path) # Return 404 if path doesn't exist # if not os.path.exists(abs_path): # return render_template('404.html'), 404 # Check if path is a file and serve # if os.path.isfile(abs_path): # return send_file(abs_path) # Show directory contents files = os.listdir(abs_path) files = [os.path.join(req_path, file) for file in files] # return render_template('files.html', files=files) return render_template_string(""" &lt;ul&gt; {% for file in files %} &lt;li&gt;&lt;a href="{{ file }}"&gt;{{ file }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; """, files=files) if __name__ == '__main__': app.run(debug=True)
has title: Python: FileNotFoundError: [WinError 3] The system cannot find the path specified:
has answer: http://stackoverflow.com/a/51026993
type: Question
answer count: 1
tagged with: flask
score: 0

http://stackoverflow.com/a/51112908
type: Answer
has body: For that, you need to output your CSS and JS file directly to the HTML file. For example, if you have the folder structure as follows: | Root App |__ assets | |__ css | |_______style.css | |__ Js | |_______ myjs.js |__ bin | |__app.py | |__ templates |___________maintemplate.html |___________demoform.html You can create a route to output the file by reading it, Please check following code in your app.py file import web import os routs = ( '/','index', '/staticFiles','loadStatic' ) app = web.application(routs, globals()) render = web.template.render('templates/',base="maintemplate") class index(object): def GET(self): return render.demoform() class loadStatic(object): def GET(self): form = web.input(fileName='',filePath='') fileName=form.file filePath=form.folder script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in rel_path = ("../assets/%s/%s" % (filePath,fileName)) abs_file_path = os.path.join(script_dir, rel_path) temp = open(abs_file_path,'r').read() return temp In your maintemplate.html $def with (content) SAMPLE CODE $:content How It Works In app.py, like all CDN CSS/JS links, we are reading the file and returning output to the browser as a HTTP request.
score: 3
accepted answer of: http://stackoverflow.com/q/51112634
upvote count: 3
answers question: http://stackoverflow.com/q/51112634
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89239209
type: QuestionComment
has text: Sorry I haven't been able to do more work on this, but I just added a little more info to the end of my answer.
score: 1
comment on: http://stackoverflow.com/q/51117776
type: Comment

http://stackoverflow.com/q/51046290
favorite count: 0
has title: EOFError on input()
downvote count: 5
has comment: http://stackoverflow.com/comment/89083772
has body: I found this code and I try to use it on python 3 but it doesn't work on geeks IDE list=input('racecar:') if (list==list[::-1]): print ("It is a palindrome") else: print("it is not palindrome") I'm getting : list=input('racecar:') EOFError: EOF when reading a line
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89084045
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89083874
score: -4
has comment: http://stackoverflow.com/comment/89083658
type: Question
has answer: http://stackoverflow.com/a/51047382
has answer: http://stackoverflow.com/a/51046722
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/89083671
has comment: http://stackoverflow.com/comment/89083903
has comment: http://stackoverflow.com/comment/89083830
answer count: 2
upvote count: 1
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/89083760
has comment: http://stackoverflow.com/comment/89083872

http://stackoverflow.com/comment/91803606
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51082296
type: AnswerComment
has text: Nope if you are to use collections you should use Counter directly not reimplement it

http://stackoverflow.com/a/51161334
answers question: http://stackoverflow.com/q/51160354
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89313095
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89341075
has body: Edit: Here is how you can achieve the matrix multiplication you asked about. Disclaimer: This might not be feasible for a very large corpus. Sklearn: from sklearn.feature_extraction.text import CountVectorizer Doc1 = 'Wimbledon is one of the four Grand Slam tennis tournaments, the others being the Australian Open, the French Open and the US Open.' Doc2 = 'Since the Australian Open shifted to hardcourt in 1988, Wimbledon is the only major still played on grass' docs = [Doc1, Doc2] # Instantiate CountVectorizer and apply it to docs cv = CountVectorizer() doc_cv = cv.fit_transform(docs) # Display tokens cv.get_feature_names() # Display tokens (dict keys) and their numerical encoding (dict values) cv.vocabulary_ # Matrix multiplication of the term matrix token_mat = doc_cv.toarray().T @ doc_cv.toarray() Gensim: import gensim as gs import numpy as np cp = [[(0, 2), (1, 1), (2, 1), (3, 1), (4, 11), (7, 1), (11, 2), (13, 3), (22, 1), (26, 1), (30, 1)], [(4, 31), (8, 2), (13, 2), (16, 2), (17, 2), (26, 1), (28, 4), (29, 1), (30, 1)]] # Convert to a dense matrix and perform the matrix multiplication mat_1 = gs.matutils.sparse2full(cp[0], max(cp[0])[0]+1).reshape(1, -1) mat_2 = gs.matutils.sparse2full(cp[1], max(cp[0])[0]+1).reshape(1, -1) mat = np.append(mat_1, mat_2, axis=0) mat_product = mat.T @ mat For words that appear consecutively, you could prepare a list of bigrams for a set of documents and then use python's Counter to count the bigram occurrences. Here is an example using nltk. import nltk from nltk.util import ngrams from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from collections import Counter stop_words = set(stopwords.words('english')) # Get the tokens from the built-in collection of presidential inaugural speeches tokens = nltk.corpus.inaugural.words() # Futher text preprocessing tokens = [t.lower() for t in tokens if t not in stop_words] word_l = WordNetLemmatizer() tokens = [word_l.lemmatize(t) for t in tokens if t.isalpha()] # Cre…
accepted answer of: http://stackoverflow.com/q/51160354
has comment: http://stackoverflow.com/comment/89312044
upvote count: 2

http://stackoverflow.com/q/51085553
type: Question
has title: scikit learn: 5 fold cross validation & train test split
tagged with: data-science
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/51086207
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has body: I am wondering when I do train test split (20% test, 80% 80%) and then I apply 5 fold cross validation does that mean all data has been in the test set once? or is it randomly choosed each time that, in each fold the same events were possibly included in the test more than once and some possibly were never included in test set? #20% of the data will be used as test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed) cv_results= cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51086207

http://stackoverflow.com/a/51042942
type: Answer
has comment: http://stackoverflow.com/comment/89077125
has comment: http://stackoverflow.com/comment/89078115
has body: The issue is that when you do below in your code username= self.username1.get() Python creates a local variable in the scope of the function and when the function ends the variable is no longer there. So you have multiple was to solved this. One is to define username in __init__ of App self.username = None And in your function use self.username = self.username1.get() And in later you can use print(app.username) Another option is to use global variables (NOT RECOMMENDED) username = None class App ..... global username username= self.username1.get() .... print(username)
has comment: http://stackoverflow.com/comment/89078022
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51042659
has comment: http://stackoverflow.com/comment/89077079

http://stackoverflow.com/q/51071926
has body: Given the following dataset: "";"M_001";"M_002";"M_003";"M_004" "2011-01-01 00:00:00";4,45;3,5467;3,197;12,098 "2011-02-01 00:00:00";18,40;0,124;174,36;11,098 "2011-03-01 00:00:00";25,789;27,67;19,76;34,66 "2011-04-01 00:00:00";19,08;11,078;23,34;67,45 "2011-05-01 00:00:00";13,06;06,078;10,34;21,45 "2011-06-01 00:00:00";13,06;06,078;10,34;21,45 "2011-06-21 00:00:00";13,06;06,078;10,34;21,45 "2011-07-01 00:00:00";9,06;06,078;9,34;21,45 "2011-07-14 00:00:00";9,06;06,078;9,34;21,45 "2011-08-01 00:00:00";22,06;45,078;21,34;21,45 "2011-08-11 00:00:00";22,06;45,078;21,34;21,45 "2011-08-12 00:00:00";22,06;45,078;21,34;21,45 "2011-09-01 00:00:00";76,06;32,078;10,34;21,45 "2011-09-23 00:00:00";76,06;32,078;10,34;21,45 "2011-09-25 00:00:00";76,06;32,078;10,34;21,45 "2011-10-01 00:00:00";17,06;18,078;108,34;21,45 "2011-11-01 00:00:00";12,06;45,078;107,34;21,45 "2011-12-01 00:00:00";7,06;60,078;83,34;21,45 "2011-12-21 00:00:00";7,06;60,078;83,34;21,45 "2012-01-01 00:00:00";4,45;3,5467;3,197;12,098 "2012-02-01 00:00:00";18,40;0,124;174,36;11,098 "2012-03-01 00:00:00";25,789;27,67;19,76;34,66 "2012-03-11 00:00:00";25,789;27,67;19,76;34,66 "2012-03-20 00:00:00";25,789;27,67;19,76;34,66 "2012-03-30 00:00:00";25,789;27,67;19,76;34,66 Could anyone tell me how to modify the function calc() to select the rows from the dataset in order that I can get separately the rows about both the winter season (from 21 december to 20 march) and the summer season (from 21 june to 23 september) from read_csv? I have already tried on writing this code, but it doesn't work well. import pandas as pd def calc(): filename = 'mydataset/dataset.csv' mySeries = pd.read_csv(filename, header=0, index_col=0, parse_dates=[0], sep=";", decimal=",") return mySeries if __name__ == '__main__': df = calc() print("Winter season measures: ") print(df.ilocx in range(12, 3) for x in df.index.month) print("Winter season measures: ") print(df.ilocx in range(6, 10) for x in df.index.month) Thank you in advance!
has answer: http://stackoverflow.com/a/51072629
accepted answer: http://stackoverflow.com/a/51072629
type: Question
has title: Getting seasons from dataset by using Pandas
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/22898824
tagged with: pandas
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89233841
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51123015
type: Comment
has text: I tried ngrok.io but received SSL error. I'm not sure if I'm using it right. When I create public key I put a domain name that ngrok gave me as Common Name and set webhook with url from ngrok + /token/

http://stackoverflow.com/q/51148526
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89281181
favorite count: 0
has comment: http://stackoverflow.com/comment/89281138
possible better answer: http://stackoverflow.com/a/51148663
has comment: http://stackoverflow.com/comment/89281377
tagged with: python
has title: Pandas - Merge multiple columns and sum
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51148663
has answer: http://stackoverflow.com/a/51148650
accepted answer: http://stackoverflow.com/a/51148650
has body: I have a main df like so: index A B C 5 1 5 8 6 2 4 1 7 8 3 4 8 3 9 5 and an auxiliary df2 that I want to add to the main df like so: index A B 5 4 2 6 4 3 7 7 1 8 6 2 Columns A &amp; B are the same name, however the main df contains many columns that the secondary df2 does not. I want to sum the columns that are common and leave the others as is. Output: index A B C 5 5 7 8 6 6 7 1 7 15 4 4 8 9 11 5 Have tried variations of df.join, pd.merge and groupby but having no luck at the moment. Last Attempt: df.groupby('index').sum().add(df2.groupby('index').sum()) But this does not keep common columns. pd.merge I am getting suffix _x and _y

http://stackoverflow.com/comment/89255275
has text: Works, but prints all CSV file names. Not the one causing the error
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51135588

http://stackoverflow.com/a/51119435
has body: Try this: import math def first_two(d): return (d // 10 ** (int(math.log(d, 10)) - 1)) df1['F'] = df1.D.apply(first_two) output: In [212]: df1 Out[212]: A B C D E F 0 1 8 69 1663 Married 16 1 1 4 82 8818 Single 88 2 1 3 8 9232 Single 92 3 4 1 25 9643 Divorced 96 4 5 1 56 4900 Widow(er) 49 5 3 6 79 8568 Single 85 6 3 4 98 4975 Married 49 7 4 6 68 8938 Divorced 89 8 1 9 49 7513 Married 75 9 4 8 82 1515 Widow(er) 15 Most of the SO solutions use string slicing - this will use math to do the "slice". or with lambda function df1['F'] = df1.D.apply(lambda d: d // 10 ** (int(math.log(d, 10)) - 1)) efficiency... Didn't include the setup - but it is as described above #string slice method In [255]: print(t.timeit(100)) 3.3840187825262547e-06 #'first_two' method In [252]: print(t.timeit(100)) 1.8120044842362404e-06 #'lambda' method In [249]: print(t.timeit(100)) 1.9049621187150478e-06 It is odd that calling the method is faster than the lambda (?)
upvote count: 1
answers question: http://stackoverflow.com/q/51119308
has comment: http://stackoverflow.com/comment/89230611
accepted answer of: http://stackoverflow.com/q/51119308
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/51154080
tagged with: python
score: 0
has title: IntelliJ cannot import module but works fine from command line
has body: I am using Ubuntu and trying to run a simple Python script: from fipy import Grid1D nx = 50 dx = 1. mesh = Grid1D(nx=nx, dx=dx) print(mesh) If I run this from command line everything is fine: dario@dario-X750JB:~$ /home/dario/anaconda2/envs/panaxea/bin/python /home/dario/phdCode/fipy/example.py UniformGrid1D(dx=1.0, nx=50) dario@dario-X750JB:~$ However, if I run this from within IntelliJ it cannot load the module: /home/dario/anaconda2/envs/panaxea/bin/python /home/dario/phdCode/fipy/example.py Traceback (most recent call last): File "/home/dario/phdCode/fipy/example.py", line 1, in &lt;module&gt; from fipy import Grid1D ImportError: cannot import name Grid1D Process finished with exit code 1 Note that the python venv and the script which are being executed are exactly the same, so I do not understand why the difference in results. Anybody has come across something similar? Note Fipy is definitely installed: dario@dario-X750JB:~$ which python /home/dario/anaconda2/envs/panaxea/bin/python dario@dario-X750JB:~$ pip list Package Version ---------- --------- certifi 2018.4.16 FiPy 3.1.3 future 0.16.0 numpy 1.14.5 pip 10.0.1 pyglet 1.3.2 scipy 1.1.0 setuptools 39.2.0 wheel 0.31.1 dario@dario-X750JB:~$
tagged with: intellij-idea
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89303182
tagged with: fipy
has comment: http://stackoverflow.com/comment/89302826
type: Question

http://stackoverflow.com/a/51089054
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89180826
type: Answer
answers question: http://stackoverflow.com/q/51084114
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51084114
score: 1
has body: Did you name your program pptx.py by any chance? Python would preferentially load that module instead of the library version. You can find out what module was loaded with this at the Python prompt: &gt;&gt;&gt; import pptx &gt;&gt;&gt; pptx.__file__ '/somedir/.../python-pptx/pptx/__init__.pyc' That may help narrow things down.

http://stackoverflow.com/a/51082968
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89154569
type: Answer
accepted answer of: http://stackoverflow.com/q/51082873
has comment: http://stackoverflow.com/comment/89154477
answers question: http://stackoverflow.com/q/51082873
score: 4
has body: Since you've saved the form with commit=False, you need to call the form's save_m2m() method to save the many-to-many data after you have saved the instance. def form_valid(self, form): instance = form.save(commit=False) instance.created_by = self.request.user instance.save() form.save_m2m() # Apparently you can only add M2M relationships saves after first # saving instance.users.add(self.request.user) return HttpResponseRedirect(reverse('group_list')) Note that I've changed the line to instance = form.save(commit=False) to make it clearer that save() returns an instance, and so that you still have access to the form.

http://stackoverflow.com/q/51085067
has comment: http://stackoverflow.com/comment/89367334
has comment: http://stackoverflow.com/comment/89443734
upvote count: 5
has comment: http://stackoverflow.com/comment/89441135
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51232885
has comment: http://stackoverflow.com/comment/89239763
has title: Using scrapy-splash clicking a button
tagged with: python
has comment: http://stackoverflow.com/comment/89444116
type: AnsweredQuestion
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/51232885
has body: I am trying to use Scrapy-splash to click a button on a page that I'm being redirected to. I have tested manually clicking on the page, and I am redirected to the correct page after I have clicked the button that gives my consent. I have written a small script to click the button when I am redirected to the page, but this is not working. I have included a snippet of my spider below - am I missing something in my code?: from sys import path import os dir_path = os.path.dirname(os.path.realpath(__file__)) path.append(dir_path) import scrapy from scrapy_splash import SplashRequest script=""" function main(splash) splash:wait(1) splash:runjs('document.querySelector("form.consent-form").submit()') splash:wait(1) return { html = splash:html(), } end """ class FoobarSpider(scrapy.Spider): name = "foobar" def start_requests(self): urls = ['https://uk.finance.yahoo.com/quote/ANTO.L?p=ANTO.L'] for url in urls: yield SplashRequest(url=url, callback=self.parse, endpoint='render.html', args={'wait': 3}, meta = {'yahoo_url': url } ) def parse(self, response): url = response.url with open('temp.html', 'wb') as f: f.write(response.body) if 'https://guce.' in url: print('About to attempt to authenticate ...') yield SplashRequest( url, callback = self.get_price, endpoint = 'execute', args = {'lua_source': script, 'timeout': 5}, meta = response.meta ) else: self.get_price(response) def get_price(self, response): print("Get price called!") yahoo_price = None try: # Get Price ... temp1 = response.css('div.D\(ib\).Mend\(20px\)') if temp1 and len(temp1) &gt; 1: temp2 = temp1[1].css('span') if len(temp2) &gt; 0: yahoo_price = temp2[0].xpath('.//text()').extract_first().replace(',','') if not yahoo_price: val = response.css('span.Trsdu\(0\.3s\).Trsdu\(0\.3s\).Fw\(b\).Fz\(36px\).Mb\(-4px\).D\(b\)').xpath('.//text()').extract_first().replace(',','') yahoo_price = val except Exception as err: pass print("Price is: {0}".format(yahoo_price)) def handle_error(self, failure): pass How do I fix thi…
type: Question
has comment: http://stackoverflow.com/comment/89409416
score: 5

http://stackoverflow.com/comment/89070211
comment on: http://stackoverflow.com/q/51039164
type: Comment
type: QuestionComment
has text: if you won't import a particular class or method in a program, that program will not have access to it.
score: 0

http://stackoverflow.com/a/51114912
answers question: http://stackoverflow.com/q/51114294
type: Answer
accepted answer of: http://stackoverflow.com/q/51114294
has body: I think you might have mixed up two variable names: this number1 = number1.get() should probably be that: number1 = entry1.get()
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89138472
has text: Sometimes there are these kind of limitations between OS's. I am off for the night but I will look into it when I get to work tomorrow.
comment on: http://stackoverflow.com/a/51065493
type: AnswerComment
score: 0
type: Comment

extra
tag name: extra
tags question: http://stackoverflow.com/q/51150898
type: Tag

http://stackoverflow.com/q/51089713
has answer: http://stackoverflow.com/a/51193629
tagged with: go
score: 0
answer count: 1
has body: I am trying to create a Python package that depends on a library that is compile from Go source. I am following the instructions specified at: Python setuptools/distutils custom build for the `extra` package with Makefile The idea is to compile Go code to create the library, then provide that library to setup tools to build a Python extension. The library is compiled from a make rule, just like in the link above. I am getting this error when compiling: vendor/golang.org/x/sys/unix/syscall_linux_gc.go:10:6: missing function body
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89195131
tagged with: python
has title: Python setuptools/distutils custom build for the `extra` package from GO source
tagged with: installation
linked to: http://stackoverflow.com/q/41169711
type: Question
has comment: http://stackoverflow.com/comment/89167861

http://stackoverflow.com/comment/89100278
type: Comment
type: QuestionComment
has text: Could you attach some images to show where you're getting undesired matches?
score: 0
comment on: http://stackoverflow.com/q/51050047

http://stackoverflow.com/q/51046454
linked to: http://stackoverflow.com/q/77859473
has comment: http://stackoverflow.com/comment/95742109
has answer: http://stackoverflow.com/a/75830761
has answer: http://stackoverflow.com/a/76121044
has answer: http://stackoverflow.com/a/79244722
has answer: http://stackoverflow.com/a/78843900
has comment: http://stackoverflow.com/comment/95475205
has answer: http://stackoverflow.com/a/77137085
tagged with: python
possible better answer: http://stackoverflow.com/a/61157968
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61157968
has answer: http://stackoverflow.com/a/70199426
score: 77
has comment: http://stackoverflow.com/comment/89086949
accepted answer: http://stackoverflow.com/a/54077842
has answer: http://stackoverflow.com/a/77713038
tagged with: selenium
has answer: http://stackoverflow.com/a/77469934
linked to: http://stackoverflow.com/q/54327654
downvote count: 1
type: Question
upvote count: 78
has answer: http://stackoverflow.com/a/74089119
has body: I want to use Selenium Webdriver of Chrome in colab.research.google.com for fast processing. I was able to install Selenium using !pip install selenium but the webdriver of chrome needs a path to webdriverChrome.exe. How am I suppose to use it? P.S.- colab.research.google.com is an online platform which provides GPU for fast computational problems related to deep learning. Please refrain from solutions such as webdriver.Chrome(path).
has answer: http://stackoverflow.com/a/51049417
has answer: http://stackoverflow.com/a/75634596
has comment: http://stackoverflow.com/comment/100471924
tagged with: google-colaboratory
linked to: http://stackoverflow.com/q/50566186
has title: How can we use Selenium Webdriver in colab.research.google.com?
has answer: http://stackoverflow.com/a/62929397
has answer: http://stackoverflow.com/a/69465005
has answer: http://stackoverflow.com/a/54077842
answer count: 15
favorite count: 0

http://stackoverflow.com/comment/89320907
type: Comment
comment on: http://stackoverflow.com/q/51132151
has text: @GrahamDumpleton Now it the hook executes the commands without any modifications, maybe it was a company cluster issue, not sure. However the changes won't persist in the final pod, which would be my original concern. How can I execute commands during deployment which output will persist in the deployed pod?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89131350
type: Comment
comment on: http://stackoverflow.com/a/51045263
score: 1
type: AnswerComment
has text: Got it working with this: df.loc[df.select_dtypes(include='O').stack().str.contains('text', na=False, regex=False, case=False).unstack().any(1)]

http://stackoverflow.com/comment/89177222
type: Comment
type: QuestionComment
has text: @TerryJanReedy Thanks for your input. I was actually impressed by the simplicity of IDLE for debugging. No major dependency / tweaking. I hope the enthusiastic developers fix this bug.
comment on: http://stackoverflow.com/q/51059584
score: 0

http://stackoverflow.com/q/51164448
has comment: http://stackoverflow.com/comment/89312164
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51165745
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
possible better answer: http://stackoverflow.com/a/51164583
accepted answer: http://stackoverflow.com/a/51164533
has answer: http://stackoverflow.com/a/51164583
type: Question
score: 3
has answer: http://stackoverflow.com/a/51164755
has answer: http://stackoverflow.com/a/58051375
has title: Remove all Adjacent duplicates using a loop
has comment: http://stackoverflow.com/comment/89312217
has comment: http://stackoverflow.com/comment/89322118
downvote count: 0
has answer: http://stackoverflow.com/a/51164533
has body: I'm trying to solve this problem. I have seen other solutions that involve lists and using recursion but I'm interested in learning how to solve this with loops and my problem is I can't get the last char to print out since it equals an empty variable. input:abbabd expected output:aabd Code: answer = input("enter a string: ") new_answer = "" p = "" repeat = "" len_answer = len(answer) run = False for c in answer: if c != p and run == False: new_answer += p p = c run = False elif c == p: p = c run = True elif run == True and c != p: p = c run = False else: new_answer += p print(new_answer)
favorite count: 0
has comment: http://stackoverflow.com/comment/89312136
has comment: http://stackoverflow.com/comment/89312176

http://stackoverflow.com/comment/89032147
type: QuestionComment
has text: I tried to do it but he gives me this error : ** AttributeError: 'list' object has no attribute 'strip'
comment on: http://stackoverflow.com/q/51018483
score: 0
type: Comment

http://stackoverflow.com/q/51080415
tagged with: curve-fitting
tagged with: python
has body: I have the necessity to check if two splines are close enough with a certain tolerance to each other. the first spline: spl_psi=scipy.interpolate.UnivariateSpline(t,psi,k=4,s=0) is the "data input" one used to check the second, which is: def fr1(x,y,z): return z def fr2(t,r1,r2): return ((K_1*spl_delta(t)+(K_1*T_3)*spl_delta1(t)-(T_1*T_2)*r2-r1)/(T_1+T_2)) for i in range(0,len(T2)-1,1): k1=h*fr1(T2[i],r1[i],r2[i]) l1=h*fr2(T2[i],r1[i],r2[i]) k2=h*fr1(T2[i]+0.5*h,r1[i]+0.5*k1,r2[i]+0.5*l1) l2=h*fr2(T2[i]+0.5*h,r1[i]+0.5*k1,r2[i]+0.5*l1) k3=h*fr1(T2[i]+0.5*h,r1[i]+0.5*k2,r2[i]+0.5*l2) l3=h*fr2(T2[i]+0.5*h,r1[i]+0.5*k2,r2[i]+0.5*l2) k4=h*fr1(T2[i]+h,r1[i]+k3,r2[i]+l3) l4=h*fr2(T2[i]+h,r1[i]+k3,r2[i]+l3) r1[i+1]=r1[i]+(k1+2*k2+2*k3+k4)/6 r2[i+1]=r2[i]+(l1+2*l2+2*l3+l4)/6 spl_r1_n2=scipy.interpolate.UnivariateSpline(T2,r1,k=5,s=0) spl_psi_n2=scipy.interpolate.UnivariateSpline.antiderivative(spl_r1_n2) spl_psi_n2 is my second spline that must be close to spl_psi, and T_1,T_2,T_3,K_1 are my parameters. This method is called Runge-Kutta and it's used to solve differential equation such as mine. Now, I want to find the parameters that make the best spline and then save them in an array called "res". This is my code: def fr1(x,y,z): return z def fr2(x,y,z): return ((K*spl_delta(x)+(K*(t_3/4))*spl_delta1(x)-((t_1/4)+(t_2/4))*z-y)/(t_1*t_2/(16) )) r1_0=spl_psi1(0) r2_0=spl_psi2(0) h=T2[2]-T2[1] r1=np.array( [r1_0]*len(T2)) r2=np.array( [r2_0]*len(T2)) toll=0.5 res=[] for t_1 in range (2,200,1): for t_2 in range (2,50,1): for t_3 in range (2,50,1): for i in range(0,len(T2)-1,1): k1=h*fr1(T2[i],r1[i],r2[i]) l1=h*fr2(T2[i],r1[i],r2[i]) k2=h*fr1(T2[i]+0.5*h,r1[i]+0.5*k1,r2[i]+0.5*l1) l2=h*fr2(T2[i]+0.5*h,r1[i]+0.5*k1,r2[i]+0.5*l1) k3=h*fr1(T2[i]+0.5*h,r1[i]+0.5*k2,r2[i]+0.5*l2) l3=h*fr2(T2[i]+0.5*h,r1[i]+0.5*k2,r2[i]+0.5*l2) k4=h*fr1(T2[i]+h,r1[i]+k3,r2[i]+l3) l4=h*fr2(T2[i]+h,r1[i]+k3,r2[i]+l3) r1[i+1]=r1[i]+(k1+2*k2+2*k3+k4)/6 r2[i+1]=r2[i]+(l1+2*l2+2*l3+l4)/6 spl_r1_n2=scipy.int…
answer count: 0
score: 1
has title: checking the proximity of two splines in python
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89150030
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: cycle

http://stackoverflow.com/q/51109089
favorite count: 0
has title: Python Twilio making a call with Client
tagged with: twilio
has answer: http://stackoverflow.com/a/51124466
tagged with: python
upvote count: 4
downvote count: 0
type: UnansweredQuestion
type: Question
has body: I am trying to make a call using twilio and python with the code below: account_sid = "***" auth_token = "***" client = Client(account_sid, auth_token) call = client.calls.create(to=phone_number, from_="+***", record=True, url="https://handler.twilio.com/twiml/***") print call.sid Here is my xml on that url: Hi, Thanks for accepting our call! The call connects, but after the xml triggers, the call ends. Can someone point me out what I am doing wrong? I can successfully make a call by doing the approach below, but I need the callsid right after dial for storing the callsid in the database to retrieve the recording later: resp = VoiceResponse() dial = Dial(caller_id='+1***', record="record-from-ringing") dial.number(phone_number, url="https://handler.twilio.com/twiml/***") resp.append(dial) return HttpResponse(resp, mimetype='text/xml') The url above is the same as the first example, but after playing the SAY tag, the call connects. Doing this approach doesn't allow me to get the callsid. Any ideas?
score: 4
answer count: 1

http://stackoverflow.com/q/51137863
answer count: 0
has comment: http://stackoverflow.com/comment/92332063
has comment: http://stackoverflow.com/comment/92434873
type: UnansweredQuestion
upvote count: 1
tagged with: coremltools
type: Question
has body: I've trained a model in keras using the following structure. model = Sequential() model.add(TimeDistributed(Convolution2D(16, 3, 3, border_mode="same", activation='relu'), input_shape=(None, image_height, image_width, 3))) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(32, 3, 3, activation='relu'))) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(64, 3, 3, activation='relu'))) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(128, 3, 3, activation='relu'))) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Flatten(), name='out1')) model.add(LSTM(256, name='lstm')) model.add(Dense(1, activation='sigmoid', name='out')) The model works great, but I need to convert it to CoreML. When I attempt that I get the following error. 0 : time_distributed_1_input, &lt;keras.engine.topology.InputLayer object at 0x7f05c8711390&gt; 1 : time_distributed_1, &lt;keras.layers.wrappers.TimeDistributed object at 0x7f05c8711450&gt; Traceback (most recent call last): File "converter.py", line 92, in &lt;module&gt; coreml_model = coremltools.converters.keras.convert(loaded_model, input_names=["image"], output_names=["out1"]) File "/usr/local/lib/python2.7/dist-packages/coremltools/converters/keras/_keras_converter.py", line 752, in convert custom_conversion_functions=custom_conversion_functions) File "/usr/local/lib/python2.7/dist-packages/coremltools/converters/keras/_keras_converter.py", line 550, in convertToSpec custom_objects=custom_objects) File "/usr/local/lib/python2.7/dist-packages/coremltools/converters/keras/_keras2_converter.py", line 311, in _convert converter_func(builder, layer, input_names, output_names, keras_layer) File "/usr/local/lib/python2.7/dist-packages/coremltools/converters/keras/_layers2.py", line 284, in convert_convolution output_blob_shape = list(filter(None, keras_layer.output_…
downvote count: 0
tagged with: ios
score: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/92418907
has title: Coremltools converting CNN + LSTM issues
tagged with: python
has comment: http://stackoverflow.com/comment/92458665

http://stackoverflow.com/q/51144993
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I'm reading this blog https://smist08.wordpress.com/2016/10/04/the-road-to-tensorflow-part-10-more-on-optimization/ where it mentions all the tensorflow's learning rates optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) optimizer = tf.train.AdadeltaOptimizer(starter_learning_rate).minimize(loss) optimizer = tf.train.AdagradOptimizer(starter_learning_rate).minimize(loss) # promising optimizer = tf.train.AdamOptimizer(starter_learning_rate).minimize(loss) # promising optimizer = tf.train.MomentumOptimizer(starter_learning_rate, 0.001).minimize(loss) # diverges optimizer = tf.train.FtrlOptimizer(starter_learning_rate).minimize(loss) # promising optimizer = tf.train.RMSPropOptimizer(starter_learning_rate).minimize(loss) # promising It says that the learning rate you input is only the starter learning rate. Does that mean that if you change the learning rate in the middle of training, that change will have no effect because it's not using the starter learning rate anymore? I tried looking at the API docs and it doesn't specify this.
tagged with: machine-learning
tagged with: tensorflow
type: Question
upvote count: 2
tagged with: deep-learning
answer count: 1
favorite count: 0
has title: Tensorflow: Is the learning rate you set in Adam and Adagrad just the initial learning rate?
has answer: http://stackoverflow.com/a/51145579
tagged with: python
accepted answer: http://stackoverflow.com/a/51145579

http://stackoverflow.com/comment/89192544
score: 0
has text: What's the problem with `execfile()`?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51102161

http://stackoverflow.com/comment/89174749
has text: your comment is "# <--- doesn't print out value or write it to file" but I copied your code, stripped out the file part and uncommented the print statement in receiver and you code ran fine for me. I would suggest you simplify your code, get it working just using prints and then add your file write back in
comment on: http://stackoverflow.com/q/51093085
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51149055
has comment: http://stackoverflow.com/comment/89281994
type: Question
answer count: 2
has title: How to make name be a variable in python?
has comment: http://stackoverflow.com/comment/89281959
score: -1
has comment: http://stackoverflow.com/comment/89281962
downvote count: 1
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0
has answer: http://stackoverflow.com/a/51149113
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has answer: http://stackoverflow.com/a/51149105
has comment: http://stackoverflow.com/comment/89282017
has comment: http://stackoverflow.com/comment/89282645
has body: How should I do if I want to output "name[0] = 6" instead of "t"?
upvote count: 0
has comment: http://stackoverflow.com/comment/89282145
has comment: http://stackoverflow.com/comment/89282819

http://stackoverflow.com/comment/89274008
type: QuestionComment
has text: Nowhere in the question does it specify a Python version that recent. It's such a common mistake to assume the order remains that I think it's very important to mention it works only since 3.6.
score: 1
comment on: http://stackoverflow.com/q/51144717
type: Comment

http://stackoverflow.com/comment/89224357
score: 0
type: QuestionComment
has text: I didn't give you that code
type: Comment
comment on: http://stackoverflow.com/q/51119074

http://stackoverflow.com/comment/89028762
type: QuestionComment
comment on: http://stackoverflow.com/q/51018048
has text: Please read [How to Create a Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve).
score: 0
type: Comment

http://stackoverflow.com/q/51075917
score: 0
duplicate of: http://stackoverflow.com/q/13704860
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/51075970
has answer: http://stackoverflow.com/a/51075963
possible better answer: http://stackoverflow.com/a/51075955
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51075955
tagged with: loops
linked to: http://stackoverflow.com/q/13704860
type: Question
has answer: http://stackoverflow.com/a/51075970
has title: Matched looping in python
has answer: http://stackoverflow.com/a/51075956
has body: This is probably a very easy thing to solve in Python, but I would appreciate anyone's help. I have two lists where I want to loop through but only for matched items: lista = ['a', 'b', 'c'] listb = ['a1', 'b1', 'c1'] for a in lista: for b in listb: print 'my first item is:', a, 'and my second item is:', b This will print my first item is: a and my second item is: a1 my first item is: a and my second item is: b1 my first item is: a and my second item is: c1 my first item is: b and my second item is: a1 my first item is: b and my second item is: b1 my first item is: b and my second item is: c1 my first item is: c and my second item is: a1 my first item is: c and my second item is: b1 my first item is: c and my second item is: c1 How can I make it print only: my first item is: a and my second item is: a1 my first item is: b and my second item is: b1 my first item is: c and my second item is: c1

http://stackoverflow.com/a/51081532
downvote count: 0
answers question: http://stackoverflow.com/q/51081183
type: Answer
accepted answer of: http://stackoverflow.com/q/51081183
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89208232
has body: Here: for all in All: if all.retName() == delVar: print(all.retName()) all = '' you are not deleting anything, you are just rebinding the local name all to the empty string. To delete the item from the list, you would have to use All.remove(item): for all in All: if all.retName() == delVar: All.remove(all) break Note that if you have more than one item with the same name, this will only remove the first one... Also note that modifying a list you're iterating upon can lead to unexpected results. It's safe in this case since we immediatly break out of the loop but it's usually something to avoid. Another solution which is safer and will remove all matching items is to filter out the list and replace the original with the result: All[:] = [item for item in All if item.name != delVar] Oh and yes too, your retName method is totally useless, name is a public attribute of your class.
type: AcceptedAnswer

http://stackoverflow.com/q/51059536
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51063000
type: Question
downvote count: 0
tagged with: difflib
answer count: 1
has title: Python Difflib's SequenceMatcher does not find Longest Common Substrings
favorite count: 0
tagged with: longest-substring
has answer: http://stackoverflow.com/a/51063000
has body: I want to use difflib.SequenceMatcher to extract longest common substrings from two strings. I'm not sure whether I found a bug or misunderstood the documentation of find_longest_match. This is the point that I find confusing: In other words, of all maximal matching blocks, return one that starts earliest in a, and of all those maximal matching blocks that start earliest in a, return the one that starts earliest in b. (https://docs.python.org/3.5/library/difflib.html#difflib.SequenceMatcher.find_longest_match) Comparing the strings X this is a test and this is a test X, the substring X is in fact a maximal block: it can't be extended (i.e., it is inclusion-maximal). Also, it is the first such maximal block in text A. But it is certainly not a longest common substring. I strongly suspect this is not what find_longest_match is supposed to find. In fact, in this example, find_longest_match does find a longest common substring: &gt;&gt;&gt; l = len("X this is a test") &gt;&gt;&gt; matcher = difflib.SequenceMatcher(None, "X this is a test", "this is a test X") &gt;&gt;&gt; matcher.find_longest_match(0, l, 0, l) Match(a=2, b=0, size=14) However, it seems like with some other strings, I can provoke the "find the first maximal block"-behavious described above (sorry for the long strings, if I shorten them, the example somehow breaks): &gt;&gt;&gt; s1 = "e-like graph visualization using a spanning tree-driven layout technique with constraints specified by layers and the ordering of groups of nodes within layers. We propose a new method of how the orde" &gt;&gt;&gt; s2 = "itree graph visualization using a spanning tree-driven layout technique with constraints speci ed by layers and the ordering of groups of nodes within layers. We propose a new method of how the drivin" &gt;&gt;&gt; matcher = difflib.SequenceMatcher(None, s1, s2) &gt;&gt;&gt; matcher.find_longest_match(1, 149, 5, 149) Match(a=1, b=47, size=1) In this case, it matches the first - in s1[1] to the - in s2[47], a…
tagged with: python
score: 11
upvote count: 11

http://stackoverflow.com/a/51049054
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51048544
answers question: http://stackoverflow.com/q/51048544
upvote count: 3
has body: You can easily do that. In your MongoDBPipeline you need to do something like below del item['html'] If that impacts the item in another pipeline then use copy.deepcopy and create a copy of item object and then delete html before inserting into mongodb
has comment: http://stackoverflow.com/comment/89089352

http://stackoverflow.com/a/51143795
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89271836
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51143769
has body: In createBlog method, post object gets created only when request.method == 'POST'. But when the method is GET it wont be created. So you would hit the error local variable 'post' referenced before assignment
answers question: http://stackoverflow.com/q/51143769
type: AcceptedAnswer

http://stackoverflow.com/comment/89113489
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51061386
has text: Only the first occurence. See the documentation for find. You could expand the find clause with the style tags to do so.

http://stackoverflow.com/comment/89181050
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51096704
has text: Deleting all migrations is almost never the right thing to do. Why have you done it?
type: Comment

http://stackoverflow.com/q/51024135
has comment: http://stackoverflow.com/comment/89040735
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51024245
favorite count: 0
tagged with: python
has title: How to change the width or height of a tkinter entry field
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
has body: I've been making a script for checking grammar. Now I've updated it to be in a gui using Tkinter. The problem is that I'm trying to indicate the row where the grammar is wrong, and when I use an entry field to input the text everything is in one row. My question is how do you expand the entry field? This is my code: import re from tkinter import * window = Tk() window.minsize(width=300, height= 20) wr = [] def work(): x = e1.get() print(x) BigLetterSearcher = re.compile(r'\. .|\n') mo = BigLetterSearcher.findall(e1.get()) x = 1 y = 0 v = 0 z = "" wr = [] for i in mo: if i == '\n': x += 1 elif i != i.upper(): v = 1 if x != y: z = "Row", x wr.append(z) wr.append(i) y = x if v == 0: wr.append ("Congratulations none of your grammar was wrong!") l1.configure(text=wr) l1 = Label(window, text="example") e1 = Entry(window, text="Enter text here: ") b1 = Button(window, text="Work", command=work) leb = [l1, e1, b1] for all in leb: all.pack() window.mainloop()
score: 1
possible better answer: http://stackoverflow.com/a/51031005
type: Question
has answer: http://stackoverflow.com/a/51031005
accepted answer: http://stackoverflow.com/a/51024245

http://stackoverflow.com/q/51047956
tagged with: python
accepted answer: http://stackoverflow.com/a/51047976
tagged with: python-decorators
possible better answer: http://stackoverflow.com/a/51048307
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17330160
has answer: http://stackoverflow.com/a/51047976
has comment: http://stackoverflow.com/comment/89086963
type: Question
has answer: http://stackoverflow.com/a/51048307
answer count: 2
score: 5
downvote count: 0
has body: I am trying to use a property setter as below. I'm following the example here: How does the @property decorator work? class Contact: def __init__(self): self._funds = 0.00 @property def funds(self): return self._funds @funds.setter def funds(self, value): self._funds = value The getter works fine &gt;&gt;&gt; contact = Contact() &gt;&gt;&gt; contact.funds 0.0 but I'm missing something about the setter: &gt;&gt;&gt; contact.funds(1000.21) Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run compileflags, 1) in test.globs File "&lt;doctest __main__.Contact[2]&gt;", line 1, in &lt;module&gt; contact.funds(1000.21) TypeError: 'str' object is not callable What am I doing wrong here?
favorite count: 0
upvote count: 5
has title: Error "'str' object is not callable" when using property setter

http://stackoverflow.com/comment/89147149
score: 0
has text: Can you show your version?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51078910

variables
tag name: variables
tags question: http://stackoverflow.com/q/51086065
tags question: http://stackoverflow.com/q/51073785
tags question: http://stackoverflow.com/q/51046057
tags question: http://stackoverflow.com/q/51118006
type: Tag
tags question: http://stackoverflow.com/q/51140271
tags question: http://stackoverflow.com/q/51118785
tags question: http://stackoverflow.com/q/51065298
tags question: http://stackoverflow.com/q/51071742
tags question: http://stackoverflow.com/q/51107701
tags question: http://stackoverflow.com/q/51035731
tags question: http://stackoverflow.com/q/51074710
tags question: http://stackoverflow.com/q/51154179

http://stackoverflow.com/q/51144708
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51144755
linked to: http://stackoverflow.com/q/696047
linked to: http://stackoverflow.com/q/16414744
type: Question
has title: Re-raising exception, in a way agnostic to Python 2 and Python 3
duplicate of: http://stackoverflow.com/q/16414744
has answer: http://stackoverflow.com/a/51144755
has body: I have a script in Python 3, which re-raises an exception using the 'from' keyword (as demonstrated in the answer to this Stackoverflow question: Re-raise exception with a different type and message, preserving existing information ) I have to go back now and make the script compatible with Python 2.7. The 'from' keyword can not be used this way in Python 2.7. I found that in Python 2, the way to re-raise an exception is as follows: try: foo() except ZeroDivisionError as e: import sys raise MyCustomException, MyCustomException(e), sys.exc_info()[2] However, while this syntax works in Python 2.7, it does not work for Python 3. Is there an accepted way to re-raise exceptions in Python which work for both Python 2.7 and Python 3?
tagged with: python-2.7
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89292695
score: 0
comment on: http://stackoverflow.com/q/51154674
type: QuestionComment
has text: What do you mean by "I want to know if there is something that can be helpful to access child using a variable"?. Do you want to get a single child out of `all` children? – thanks.
type: Comment

http://stackoverflow.com/q/51160798
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51160975
has comment: http://stackoverflow.com/comment/89311353
score: 7
possible better answer: http://stackoverflow.com/a/51160975
has answer: http://stackoverflow.com/a/51164038
tagged with: python-2.7
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89305959
favorite count: 0
has body: In python I can use a template with from string import Template templ = Template('hello ${name}') print templ.substitute(name='world') how can I define a default value in the template? And call the template without any value. print templ.substitute() Edit And when I call without parameters get the default value, example print templ.substitute() &gt;&gt; hello name
has title: python template with default value
has answer: http://stackoverflow.com/a/51162695
tagged with: python
accepted answer: http://stackoverflow.com/a/51164038
upvote count: 7
has comment: http://stackoverflow.com/comment/89305337
has comment: http://stackoverflow.com/comment/89311166
type: Question

http://stackoverflow.com/comment/89196075
comment on: http://stackoverflow.com/q/51061059
has text: Yes @JafferWilson but that implies different (much harder) approach. Generally, this is a big thing to do on MT platforms and you are better off going to professional platforms - like JForex - as MT is (IMO) a playground for beginners (stating after years of experience with it). As much as I'd like to help you and receive the bounty - it's not worth the effort. I work on this field for years now - having my own algo trading platform integrated with JForex API.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51165008
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89313361
score: 2
answers question: http://stackoverflow.com/q/51164989
has comment: http://stackoverflow.com/comment/89313424
downvote count: 0
has body: You can use itertools.groupby: import itertools da_list = [{'Surface':'APPLE','BaseForm':'apple','PN':0.5}, {'Surface':'BANANA','BaseForm':'banana','PN':0.4}, {'Surface':'ORANGE','BaseForm':'orange','PN':-0.1}, {'Surface':'APPLE','BaseForm':'apple','PN':0.5}, {'Surface':'BANANA','BaseForm':'banana','PN':0.4}] new_result = [list(b) for _, b in itertools.groupby(sorted(da_list, key=lambda x:x['Surface']), key=lambda x:x['Surface'])] final_result = [{**i[0], 'Frequency':len(i)} for i in new_result] Output: [{'Surface': 'APPLE', 'BaseForm': 'apple', 'PN': 0.5, 'Frequency': 2}, {'Surface': 'BANANA', 'BaseForm': 'banana', 'PN': 0.4, 'Frequency': 2}, {'Surface': 'ORANGE', 'BaseForm': 'orange', 'PN': -0.1, 'Frequency': 1}]

http://stackoverflow.com/comment/89303127
score: 3
has text: @Nearoo you keep repeating this assertion but you are incorrect, string numbers are sorted lexically - not numerically, i.e. `max('2', '10') == '2'`
comment on: http://stackoverflow.com/q/51159785
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89075289
comment on: http://stackoverflow.com/q/51042007
type: QuestionComment
has text: definitely right. i just updated to 2.2.2 and it works
score: 0
type: Comment

http://stackoverflow.com/comment/89262580
comment on: http://stackoverflow.com/a/51138776
score: 0
type: AnswerComment
has text: hi, just saw the answer, thanks! i will evaluate if it works in all my use cases but it looks promising
type: Comment

http://stackoverflow.com/comment/108757049
has text: This is the best answer IMHO but lacks the (important) ability to set default values for properties that aren't specified when the class is instantiated. See my answer for a tweak to allow that.
comment on: http://stackoverflow.com/a/61191878
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89041638
type: QuestionComment
has text: @jasonharper Thank for your comment. Yeah, that makes sense. But, as I mentioned, I am new to PIL, thus I have no idea how to actually clear it. Is there anyway you can post an answer showing how to clear it?
comment on: http://stackoverflow.com/q/51024386
score: 0
type: Comment

http://stackoverflow.com/comment/89128018
score: 0
type: AnswerComment
type: Comment
has text: I believe if you get rid of the `RequestParser.add_argument` code that you aren't showing above, then Swagger UI will generate input fields for each of your API model fields.
comment on: http://stackoverflow.com/a/51044663

http://stackoverflow.com/comment/89045697
type: Comment
type: AnswerComment
has text: @Jordan, Can't replicate. I ran this code straight after `factor_table = pd.DataFrame(df)` as you've defined it.
score: 0
comment on: http://stackoverflow.com/a/51026610

http://stackoverflow.com/comment/89169942
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51050663
type: AnswerComment
has text: @EvanBenn: Python explicitly calls `flush` when the file is closed. The whole point of `flush` is to force the data to be written to the file.

http://stackoverflow.com/comment/89091582
score: 1
comment on: http://stackoverflow.com/q/51050082
type: Comment
type: QuestionComment
has text: The problem with using `.{5}` is that this matches 5 of *any* character, so if you had `cpd067;cpd00129;` then the first match would be `cpd067;c`.

http://stackoverflow.com/a/51087069
type: Answer
upvote count: 4
has body: As mentioned in the comments you could use something similar to the following: YourName = input("Please enter your name: ") while True: if YourName.isalpha(): break else: print("Must enter string") print("Please type in your name") YourName = input("Please enter your name: ") continue isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As @SiHa said this SO question has a great response. As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following: import re YourName = input("Please enter your name: ") while True: if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None: break else: print("Must enter string") print("Please type in your name") YourName = input("Please enter your name: ") continue Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug. What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters. If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using: all([x.isalpha() | x.isspace() for x in YourName]) however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.
has comment: http://stackoverflow.com/comment/89164423
accepted answer of: http://stackoverflow.com/q/51086772
downvote count: 0
has comment: http://stackoverflow.com/comment/89163564
score: 4
has comment: http://stackoverflow.com/comment/98036675
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98145539
answers question: http://stackoverflow.com/q/51086772

http://stackoverflow.com/comment/89177927
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [AWS Lambda Task timed out after 6.00 seconds](https://stackoverflow.com/questions/47594168/aws-lambda-task-timed-out-after-6-00-seconds)
comment on: http://stackoverflow.com/q/51094961

http://stackoverflow.com/q/51031235
has body: I am not able to use SMOTE with imblearn. below is what i am doing in my jupyter notebook. Any suggestions? pip install -U imbalanced-learn #installs successfully !python -V #2.7.6 imblearn.__version__ #0.3.0 from imblearn.over_sampling import SMOTE sm = SMOTE() here it throws the error: TypeError Traceback (most recent call last) &lt;ipython-input-73-0715e331ee1b&gt; in &lt;module&gt;() 1 from imblearn.over_sampling import SMOTE ----&gt; 2 sm = SMOTE() /home/pradeep/Envs/nyraml/local/lib/python2.7/site-packages/imblearn/over_sampling/smote.pyc in __init__(self, ratio, random_state, k, k_neighbors, m, m_neighbors, out_step, kind, svm_estimator, n_jobs) 164 svm_estimator=None, 165 n_jobs=1): --&gt; 166 super(SMOTE, self).__init__(ratio=ratio, random_state=random_state) 167 self.kind = kind 168 self.k = k TypeError: super(type, obj): obj must be an instance or subtype of type enter code here
downvote count: 0
tagged with: imblearn
tagged with: scikit-learn
tagged with: inheritance
tagged with: python-2.7
has answer: http://stackoverflow.com/a/53962747
has comment: http://stackoverflow.com/comment/89061806
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to use Smote with imblearn?
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51052506
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51052536
has answer: http://stackoverflow.com/a/51053070
tagged with: python-3.x
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51052536
has title: Removing Empty Dataframes with pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51053070
type: Question
tagged with: dataframe
has body: I have written the following code to use regex to request pages, and look for strings that resemble interest rates. The overall code works; however, it is creating multiple empty dataframes and I can't get the code to drop the empty frames to clean up my output. I have been trying to use .dropna, .drop, and .empty to try and deprecate the dataframes but the output remains unchanged and keeps printing the empty dataframes with the information I have already. Is there an method I am not aware of that could get rid of these empty frames. Code and output below: plcompetitors = ['https://www.lendingclub.com/loans/personal-loans', 'https://www.marcus.com/us/en/personal-loans', 'https://www.discover.com/personal-loans/'] #cycle through links in array until it finds APR rates/fixed or variable using regex for link in plcompetitors: cdate = datetime.date.today() l = r.get(link) l.encoding = 'utf-8' data = l.text soup = bs(data, 'html.parser') paragraph = soup.find_all(text=re.compile('[0-9]%')) for n in paragraph: matches = [] matches.extend(re.findall('(?i)\d+(?:\.\d+)?%\s*(?:to|-)\s*\d+(?:\.\d+)?%', n.string)) sint = pd.Series(matches) qdate = pd.Series([datetime.datetime.now()]*len(sint)) slink = pd.Series([link]*len(sint)) df = pd.concat([qdate,sint,slink],axis=1) df.columns = ['Date','Interest Rate', 'URL'] print(df) Output: ... 0 ... 1 ... [2 rows x 3 columns] ... 0 ... [1 rows x 3 columns] ... 0 ... 1 ... 2 ... 3 ... [4 rows x 3 columns] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] ... 0 ... [1 rows x 3 columns] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: [] Empty DataFrame Columns: [Date, Interest Rate, URL] Index: []
score: 0
answer count: 2

http://stackoverflow.com/comment/89093028
has text: Look here: https://stackoverflow.com/questions/40489162/draw-time-radius-around-lat-long-on-map
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/51047722
type: Comment

http://stackoverflow.com/q/51055009
tagged with: python-import
has title: Importing model from other app causes problems
answer count: 1
has comment: http://stackoverflow.com/comment/89100918
tagged with: python
linked to: http://stackoverflow.com/q/4379042
type: UnansweredQuestion
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/51055149
has body: I have two apps... let's call them tiger and bird. At first, I was using models from tiger in the bird app. This is how I did the importing in bird/models.py: from django.db import models from tiger.models import TigerClass, AnotherTigerClass This worked well. There is no problem with me importing the TigerClass and OtherTigerClass into the bird app. Now, I want to also do the opposite. So in the tiger app I want to import a model from the bird app. As far as I can find in the manual, there are no restrictions on this and I should be able to use the same syntax. So this is what I do in tiger/models.py: from django.db import models from bird.models import BirdClass However, the moment I do this, my app throws a very odd error: web_1 | Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fac830d1730&gt; web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception web_1 | raise _exception[1] web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute web_1 | autoreload.check_errors(django.setup)() web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate web_1 | app_config.import_models() web_1 | File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import…
duplicate of: http://stackoverflow.com/q/744373
has comment: http://stackoverflow.com/comment/89100901
score: 0

http://stackoverflow.com/comment/89097004
comment on: http://stackoverflow.com/q/51052921
type: Comment
type: QuestionComment
has text: given the sample OP put up, there is most definitely a better solution. Exceptions/Errors etc are for actual errors and neither fit that use case.
score: 1

http://stackoverflow.com/q/51147269
tagged with: dlib
type: AnsweredQuestion
tagged with: webcam
type: Question
answer count: 1
has body: I am trying to build a python application involving facial detection in real time using webcam with the help of dlib library. I wish to create a simple python GUI for controlling the webcam stream. I tried to search for Tkinter or PyQt GUIs but could not find one. Please suggest me some code snippet or site where I can find one.
has answer: http://stackoverflow.com/a/51208984
score: 0
has comment: http://stackoverflow.com/comment/89280258
tagged with: user-interface
has comment: http://stackoverflow.com/comment/89278789
has title: How to create a quick python GUI for controlling webcam input to be used for the purpose of facial detection?
tagged with: python
accepted answer: http://stackoverflow.com/a/51208984

http://stackoverflow.com/comment/89227897
comment on: http://stackoverflow.com/a/51120804
type: AnswerComment
has text: Out of interest, you can easily generate good fake data using [faker](http://faker.readthedocs.io/en/master/)
type: Comment
score: 1

http://stackoverflow.com/comment/89253407
comment on: http://stackoverflow.com/q/51132151
type: Comment
type: QuestionComment
score: 1
has text: It is covered across a couple of chapters at least. Lifecycle hooks are covered in chapter on application lifecycle management. For doing stuff in the container, need to look at chapter Customising Source-to-Image Builds, but you really need to read chapters before to properly understand.

http://stackoverflow.com/comment/89237234
type: Comment
type: QuestionComment
has text: where are you using seaborn here? Also, I used your code exactly as you put it (except for the imports) and I got the legend in the plot ok.
comment on: http://stackoverflow.com/q/51125571
score: 0

http://stackoverflow.com/q/51094522
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89179842
has comment: http://stackoverflow.com/comment/89177706
has body: I have model called Company. The model pretty simple as you can see. In project I use postgres database. I have strange problem when try to create new entry by Django admin. First I add 5 entry in database by sql request from terminal. They have id from 1 to 5. In database client I see them. Now when I try to add new company by admin it raise next error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "company_pkey" DETAIL: Key (id)=(5) already exists. Can someone say how to fix this problem? models.py: class Company(models.Model): name = models.CharField() admin.py: class CompanyAdmin(admin.ModelAdmin): search_fields = ('name',) admin.site.register(Company, CompanyAdmin)
score: 0
has answer: http://stackoverflow.com/a/51096535
has title: Can't create new entry by admin
answer count: 1
has comment: http://stackoverflow.com/comment/89177474
has comment: http://stackoverflow.com/comment/89241056
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89177557
has comment: http://stackoverflow.com/comment/89177691
tagged with: python
has comment: http://stackoverflow.com/comment/89179855

http://stackoverflow.com/comment/89365591
comment on: http://stackoverflow.com/a/51168438
has text: I provided a official-docs based answer. You didn't state you read anything in the field before attempting - so there is no reason not to post such a answer. You wanted an answer from officlal/credible sources so that's what I'm posting. Stating it's not officially possible is not a quality answer for you?
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/51152810
answers question: http://stackoverflow.com/q/51152023
score: 35
has comment: http://stackoverflow.com/comment/128513125
type: Answer
upvote count: 35
downvote count: 0
has body: I actually found a way to do it! It's solution 1, a way to handle a binary file. The solution is to wrap a TextIOWrapper around the binary file and decode it and pass that to the DictReader. import csv import io with io.TextIOWrapper(fileobj, encoding='utf-8') as text_file: reader = csv.DictReader(text_file, delimiter=',') for row in reader: if row and 'caption' in row.keys(): yield (reader.line_num, '', row['caption'], '')
has comment: http://stackoverflow.com/comment/111537851
has comment: http://stackoverflow.com/comment/113868408

opencv
tags question: http://stackoverflow.com/q/51127792
type: Tag
tags question: http://stackoverflow.com/q/51139822
tags question: http://stackoverflow.com/q/51116739
tags question: http://stackoverflow.com/q/51028456
tags question: http://stackoverflow.com/q/51111626
tags question: http://stackoverflow.com/q/51047861
tags question: http://stackoverflow.com/q/51052268
tags question: http://stackoverflow.com/q/51087390
tags question: http://stackoverflow.com/q/51076116
tags question: http://stackoverflow.com/q/51124738
tags question: http://stackoverflow.com/q/51072238
tags question: http://stackoverflow.com/q/51145460
tags question: http://stackoverflow.com/q/51084602
tags question: http://stackoverflow.com/q/51036169
tags question: http://stackoverflow.com/q/51141638
tags question: http://stackoverflow.com/q/51084028
tags question: http://stackoverflow.com/q/51145691
tags question: http://stackoverflow.com/q/51129425
tags question: http://stackoverflow.com/q/51034209
tags question: http://stackoverflow.com/q/51086577
tags question: http://stackoverflow.com/q/51097725
tags question: http://stackoverflow.com/q/51077327
tags question: http://stackoverflow.com/q/51139234
tags question: http://stackoverflow.com/q/51113129
tags question: http://stackoverflow.com/q/51135543
tags question: http://stackoverflow.com/q/51014439
tags question: http://stackoverflow.com/q/51092720
tags question: http://stackoverflow.com/q/51084825
tags question: http://stackoverflow.com/q/51135332
tags question: http://stackoverflow.com/q/51048691
tags question: http://stackoverflow.com/q/51085435
tags question: http://stackoverflow.com/q/51056148
tags question: http://stackoverflow.com/q/51093366
tag name: opencv
tags question: http://stackoverflow.com/q/51143340
tags question: http://stackoverflow.com/q/51113895
tags question: http://stackoverflow.com/q/51090459
tags question: http://stackoverflow.com/q/51164713
tags question: http://stackoverflow.com/q/51039271
tags question: http://stackoverflow.com/q/51097659
tags question: http://stackoverflow.com/q/51146573
tags question: http://stackoverflow.com/q/51095013
tags question: http://stackoverflow.com/q/51052614
tags question: http://stackoverflow.com/q/51132674
tags question: http://stackoverflow.com/q/51133545
tags question: http://stackoverflow.com/q/51058911
tags question: http://stackoverflow.com/q/51098001
tags question: http://stackoverflow.com/q/51104612
tags question: http://stackoverflow.com/q/51077990
tags question: http://stackoverflow.com/q/51114826
tags question: http://stackoverflow.com/q/51094806
tags question: http://stackoverflow.com/q/51129840
tags question: http://stackoverflow.com/q/51039275
tags question: http://stackoverflow.com/q/51022381
tags question: http://stackoverflow.com/q/51120831
tags question: http://stackoverflow.com/q/51133962
tags question: http://stackoverflow.com/q/51065287
tags question: http://stackoverflow.com/q/51077912
tags question: http://stackoverflow.com/q/51020105
tags question: http://stackoverflow.com/q/51084648
tags question: http://stackoverflow.com/q/51128826
tags question: http://stackoverflow.com/q/51025692
tags question: http://stackoverflow.com/q/51164645
tags question: http://stackoverflow.com/q/51117956
tags question: http://stackoverflow.com/q/51050047
tags question: http://stackoverflow.com/q/51025204
tags question: http://stackoverflow.com/q/51050784
tags question: http://stackoverflow.com/q/51059843
tags question: http://stackoverflow.com/q/51089781
tags question: http://stackoverflow.com/q/51073309
tags question: http://stackoverflow.com/q/51146306
tags question: http://stackoverflow.com/q/51120850
tags question: http://stackoverflow.com/q/51129269
tags question: http://stackoverflow.com/q/51116016
tags question: http://stackoverflow.com/q/51031733
tags question: http://stackoverflow.com/q/51084289
tags question: http://stackoverflow.com/q/51093667
tags question: http://stackoverflow.com/q/51121978
tags question: http://stackoverflow.com/q/51080896

http://stackoverflow.com/comment/89258639
type: AnswerComment
has text: Gotcha thanks, that fixed a lot of it, I edited my question because there's another weird error, but thank you that was helpful!
comment on: http://stackoverflow.com/a/51137231
type: Comment
score: 0

http://stackoverflow.com/q/51106832
type: AnsweredQuestion
downvote count: 0
score: 1
has title: How to scraping data from multiple pages in one web, I'm using Python and BeautifulSoup
tagged with: loops
tagged with: web-crawler
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51118894
accepted answer: http://stackoverflow.com/a/51118894
favorite count: 0
tagged with: beautifulsoup
has body: # -*- coding: utf-8 -*- """ Created on Fri Jun 29 10:38:46 2018 @author: Cinthia """ from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq array = ['146-face', '153-palettes-sets', 'https://www.sociolla.com/147-eyes', 'https://www.sociolla.com/150-lips', 'https://www.sociolla.com/149-brows', 'https://www.sociolla.com/148-lashes'] base_url='https://www.sociolla.com/142-face' uClient = uReq(base_url) page_html = uClient.read() uClient.close() #html parsing page_soup = soup(page_html, "html.parser") #grab the product kosmetik = page_soup.findAll("div", {"class":"col-md-3 col-sm-6 ipad-grid col-xs-12 productitem"}) print(len(kosmetik)) I want to scrape data from that website, that code above just take how much product on the base url. I don't know how that array will work, so it can take data from the product such as description, image, price from all the pages I make in the array. I'm new to Python and don't know much about loops yet.
tagged with: web-scraping
tagged with: python

package
tags question: http://stackoverflow.com/q/51040840
tag name: package
tags question: http://stackoverflow.com/q/51096887
tags question: http://stackoverflow.com/q/51112761
type: Tag
tags question: http://stackoverflow.com/q/51068015
tags question: http://stackoverflow.com/q/51156893
tags question: http://stackoverflow.com/q/51094388
tags question: http://stackoverflow.com/q/51149987
tags question: http://stackoverflow.com/q/51105876
tags question: http://stackoverflow.com/q/51078959
tags question: http://stackoverflow.com/q/51097380

http://stackoverflow.com/q/51112168
tagged with: python
has body: So I want to use python shell inside eclipse. When I click django shell environement in eclipse I get the following prompt: https://i.sstatic.net/00yri.jpg Now I assume it wants the path to the settings.py file? I so, based on my folder structure (please check the image above!) the path should be rango.settings.py right? I've tried that but I get the ModuleNotFoundError: No module named 'app1' What am I doing wrong? please help!
has answer: http://stackoverflow.com/a/51112368
type: UnansweredQuestion
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/4324502
has title: Django Eclipse: How to setup settings module in eclipse (trying to use django shell)?
tagged with: eclipse
has comment: http://stackoverflow.com/comment/89211573
answer count: 1
score: 0

http://stackoverflow.com/comment/89120359
score: 0
comment on: http://stackoverflow.com/q/51065046
has text: This is just an example. ignore formatting. But each header has the info below in the masterdata
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51032147
tagged with: ethernet
has comment: http://stackoverflow.com/comment/89057097
type: UnansweredQuestion
tagged with: sockets
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/89057649
has body: I want to implement a client server over 2 raspberry pis connected directly to eachother via ethernet. I want to send a message via socket from the PI #1 to PI #2 to tell PI#2 to take a image via the camera module. How much delay is there from time I send message, to the PI receiving the message(and then taking the image)? I need less than 20 milliseconds hopefully.
has comment: http://stackoverflow.com/comment/89057557
downvote count: 3
has answer: http://stackoverflow.com/a/51032545
type: Question
tagged with: raspberry-pi
upvote count: 0
has comment: http://stackoverflow.com/comment/89056993
answer count: 1
favorite count: 0
has title: How much delay when sending message over socket

http://stackoverflow.com/comment/89019591
comment on: http://stackoverflow.com/a/51013361
score: 0
type: AnswerComment
has text: What does 'close to the mean' mean? How close? BTW that wasn't what you asked in your question.
type: Comment

http://stackoverflow.com/a/51041623
type: Answer
has comment: http://stackoverflow.com/comment/89075156
upvote count: 1
answers question: http://stackoverflow.com/q/51041004
has body: You can try to wait 1 or 2 sec if the error appear: import requests from bs4 import BeautifulSoup url = "https://www.telegraph.co.uk/world-cup/2018/06/26/world-cup-2018-fixtures-complete-schedule-match-results-far/" try: response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") except: print("Connection refused by the server..") print("Let me sleep for 2 seconds") time.sleep(2) print("Continue...") continue I couldn't test it, so maybe it will not work like this.
downvote count: 0
score: 1

http://stackoverflow.com/a/51079863
accepted answer of: http://stackoverflow.com/q/51079683
answers question: http://stackoverflow.com/q/51079683
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: I think you're approaching this the wrong way. If you need an attribute c that is always the sum of a and b, then it's that attribute that needs to be a property: @property def c(self): return self.a + self.b and you don't need properties for a or b at all. This also solves the problem of making it non-settable; if you don't define a setter for c, it can't be set directly.

http://stackoverflow.com/comment/89237285
comment on: http://stackoverflow.com/a/51109026
type: AnswerComment
score: 0
has text: @RohanSaxena Thanks for the edits :-) Yes, VGG16 variables are defined as trainable, so you should be able to retrain the model
type: Comment

http://stackoverflow.com/q/51152245
type: Question
has answer: http://stackoverflow.com/a/51152411
tagged with: python
has answer: http://stackoverflow.com/a/51152375
score: 0
has answer: http://stackoverflow.com/a/51152328
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89288112
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89288036
has comment: http://stackoverflow.com/comment/89288019
has answer: http://stackoverflow.com/a/51152360
has answer: http://stackoverflow.com/a/51152344
has comment: http://stackoverflow.com/comment/89287893
favorite count: 0
has title: Removing duplicate results from the loop output in Python
has body: My data from a loop generates a series of strings which are sentences retrieved from a database. However, my data structure in the database needs to have duplicates but I want to omit the duplicates in the output. Assuming my loop and results is as follow: for text in document: print(text) Output: He goes to school. He works here. we are friends. He goes to school. they are leaving us alone. .......... How can I set up a condition so that the program reads all the output generated and if find duplicate results (eg. He goes to school) it will only show one record of to me instead of multiple similar records?

http://stackoverflow.com/a/51022111
accepted answer of: http://stackoverflow.com/q/51021907
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: ModalName2.objects.get() should return only one object. Otherwise it raise the error. As for your problem you don't need ModalName2.objects.get() queryset actually. Since obj argument is ModelName instance you can just do following: def email_verified(self,obj): return obj.username.modelname2.email_verified Note you can access OneToOneField backwards using lowercased model name modelname2. Also since username attribute returning User instance, it would be better to rename it to user: class ModelName1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Also I recommend you to join ModelName and ModelName1 as one model and use single OneToOneField instead of two.
answers question: http://stackoverflow.com/q/51021907

http://stackoverflow.com/comment/89243330
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51129215
has text: Please post a sample of your data. Is it about numpy arrays? Or pandas dataframes?
score: 1

http://stackoverflow.com/q/51052203
linked to: http://stackoverflow.com/q/41803853
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41505926
upvote count: 2
tagged with: tensorflow
type: Question
tagged with: indexing
has body: I'm working on masking r-cnn and I have a problem with indexing the masks according to labels. Here's what I want to achieve: I have a tensor (?,28,28,c), where ? is unknown batch_size, "28x28" are 2d coordinates and c stands for different labels, then I have a list of indices (basically my label predictions) (?,) of int32. Now I want to extract the masks for a given label according to batch index -> make it a (?,28,28,1) tensor. I tried self.masks_sigmoids = tf.gather(self.final_conv, self.label_predictions, axis=3), but the shape remained the same. I also looked at tf.gather_nd here http://www.riptutorial.com/tensorflow/example/29069/how-to-use-tf-gather-nd, and I guess this is the right path, but I don't know how to incorporate that I want the indices according to batch index (in numpy (b_i,:,:,c_i)) I also get a feeling that my question is somewhat similar to Batched 4D tensor Tensorflow indexing, though my problem seems less complicated. However, that question is old in terms of the quick development of tensorflow, so I'm asking for a possibly better, more clear solution. EDIT: Even a dirty solution might beneficial as I didn't get the question in the linked SO (already wrote a comment asking to clarify the question), thus I don't get much from the only answer. It might be beneficial for the community as well, because this question is simpler, which means it would demonstrate the solution more clearly.
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51064001
has title: Tensorflow - indexing according to batch position
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51064001

http://stackoverflow.com/a/51122656
score: 2
accepted answer of: http://stackoverflow.com/q/51122641
answers question: http://stackoverflow.com/q/51122641
has comment: http://stackoverflow.com/comment/89230437
has comment: http://stackoverflow.com/comment/89230561
has comment: http://stackoverflow.com/comment/89230645
has comment: http://stackoverflow.com/comment/89230644
has comment: http://stackoverflow.com/comment/89230446
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: I believe need for each group shift all values by DataFrameGroupBy.shift: df['open_next_year'] = df.groupby('ticker')['open'].shift() print (df) fiscalYear ticker open open_next_year 0 2017 FINL 17.488 NaN 1 2017 AAPL 17.488 NaN 2 2016 FINL 16.488 17.488 3 2016 AAPL 16.488 17.488 4 2015 FINL 15.488 16.488 5 2015 AAPL 15.488 16.488 Changed sample for unique open values: print (df) fiscalYear ticker open 0 2017 FINL 17.4881 1 2017 AAPL 17.4882 2 2016 FINL 16.4883 3 2016 AAPL 16.4884 4 2015 FINL 15.4885 5 2015 AAPL 15.4886 df['open_next_year'] = df.groupby('ticker')['open'].shift() print (df) fiscalYear ticker open open_next_year 0 2017 FINL 17.4881 NaN 1 2017 AAPL 17.4882 NaN 2 2016 FINL 16.4883 17.4881 3 2016 AAPL 16.4884 17.4882 4 2015 FINL 15.4885 16.4883 5 2015 AAPL 15.4886 16.4884
type: Answer

http://stackoverflow.com/a/51131008
downvote count: 0
has comment: http://stackoverflow.com/comment/89247171
has comment: http://stackoverflow.com/comment/89247084
type: Answer
has comment: http://stackoverflow.com/comment/89247289
score: 1
has comment: http://stackoverflow.com/comment/89247086
has comment: http://stackoverflow.com/comment/89247454
upvote count: 1
answers question: http://stackoverflow.com/q/51130886
has body: You can use executemany in PSQL to insert multiple records at once as follows: conn=psycopg2.connect("dbname='db_name' user='db_user' password='db_pass'") data = [{"col1":"data11", "col2":"data21"}, {"col1":"data12", "col2":"data22"}, {"col1":"data13", "col2":"data23"}] cur = conn.cursor() cur.executemany("""INSERT INTO bar(col1,col2) VALUES (%(col1)s, %(col2)s)""", data) If you do not have dict structure, you need to make sure that data is in correct sequences of your columns in your table as : cur.executemany( """INSERT INTO bar(col1,col2) VALUES (%s,%s)""", data) and data should be format : data = [['data11', 'data21'], ['data12', 'data22']] Is that what you are trying to do? Let me know, it works.

http://stackoverflow.com/comment/89294065
has text: Have you tried to add what I mentioned at the end of the forward method?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51145527

http://stackoverflow.com/comment/89024761
comment on: http://stackoverflow.com/q/51015997
type: Comment
type: QuestionComment
has text: my bad, my example wasn't right. I edited it, label isnt self closing, mynewtag has to be inside it.
score: 0

http://stackoverflow.com/q/51158854
accepted answer: http://stackoverflow.com/a/51159141
tagged with: python-3.6
has title: django 2 - User and userprofile models, how to obtain all fields in a single query?
score: 0
answer count: 1
has body: Update and solution below. I've been looking for a solution but I'm not finding anything that sticks out. I've created a Profile model which is linked to the standard User model via one-to-one field which is working in admin. I want to pull all fields/data for both models into a single queryset. I'm trying to create a user editing form and I want to pull in all fields for User and Profile based on the current logged in user and display those fields which I will have a page to edit and save those fields. What are the best options to achieve this, simple is better. class Profile(models.Model): address = models.blablabla user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') def profile_edit(request): form = UserProfileForm(request.POST or None) instance = Profile.objects.all().filter(user__username=request.user).values # This is the place I need to create a single queryset. if request.method == "POST" and form.is_valid(): form = UserProfileForm(request.POST, instance=instance) user_form = form.save() print("POST event") else: form = UserProfileForm(instance=instance) print(form) return render(request, 'frontend/profile_edit.html', {'form': form}) I'm manually creating the forms in the template so I would like to have something like {{ form.username }} {{ form.profile.address }} or something like that. I'm likely doing things poorly, I'm new to django. UPDATE Complete solution Complete steps to gain access to user and profile models in code and template. I decided not to replace the User model with my own in case I missed out on features provided by django. It also seemed to complicate things that might hurt later on. So I've gone with the separate UserProfile model and attached it to the User model. Here is what I did for future readers. models.py from django.db.models.signals import post_save class UserProfile(models.Model): #take note of the related_name='profile' this is used to reference the fields in code and template. #Each field of …
tagged with: django-2.0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51159141
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/51141248
has answer: http://stackoverflow.com/a/55418419
accepted answer: http://stackoverflow.com/a/55418419
upvote count: 8
type: Question
answer count: 2
has body: I am on a mac, using vagrant in the terminal. I am trying to run a program in python that uses psycopg2. I kept getting an error that psychopg2 module didn't exist when I would run 'python3 sample.py'. So I ran 'pip3 install psycopg2'. Now I get the error below and despite reading documentation in multiple places, I cannot solve this issue. So now my programs won't run. /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: &lt;http://initd.org/psycopg/docs/install.html#binary-install-from-pypi&gt;. """)
has comment: http://stackoverflow.com/comment/91622576
downvote count: 1
favorite count: 0
has title: Python Program Won't Run - psycopg2 rename warning
tagged with: python
tagged with: psycopg2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52548656
has answer: http://stackoverflow.com/a/52548656
score: 7

http://stackoverflow.com/comment/89307187
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51161620
has text: Then figure out why `y>o` or check whether the formula should be `y-o` and not `o-y`. Or maybe elements in `X` and `w` align with signs in this particular way? Dude, it's your exercise, I'm throwing hints here.

http://stackoverflow.com/q/51076102
has body: I am writing a scrapy code, which takes the url, the tags where my data to be scraped is stored from a csv file. That tag I am assigning to a temporary variable like z(having h1), av(having title), an(having td) etc. When I am using that variable in xpath , it does not extract anything out of that tag. Can anyone help me ? import pandas as pd import requests from scrapy.http import TextResponse x=pd.read_csv(r'C:\Users\ndewan\Desktop\pattern-swage.csv', encoding="utf-8") x=x.replace('&lt;','',regex=True).replace('&gt;','',regex=True) url=str(x.iloc[0,0]) r = requests.get(url) response = TextResponse(r.url, body=r.text, encoding='utf-8') z=x.iloc[0,1] s=x.iloc[0,2] an=x.iloc[0,3] av=x.iloc[0,4] part=response.xpath('//av//text()').extract() print(part) print(url) print(z)
has answer: http://stackoverflow.com/a/51092927
score: 1
tagged with: scrapy
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: xpath
type: UnansweredQuestion
has title: how to use a variable which has tag info in xpath to extract
upvote count: 1
tagged with: python

awk
tag name: awk
tags question: http://stackoverflow.com/q/51167007
tags question: http://stackoverflow.com/q/51067634
type: Tag
tags question: http://stackoverflow.com/q/51089235

http://stackoverflow.com/comment/89204809
type: AnswerComment
score: 0
type: Comment
has text: Thanks. The intersection changes for each date instance, which is making it more difficult. So i need to loop through each grouped-by date dataframe with the specific intersection for that time period. Does that make sense?
comment on: http://stackoverflow.com/a/51108743

http://stackoverflow.com/q/51132989
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am trying to write unit testcase of Restplus-Flask application. @deployment.route('/abc/xyz') class Depl(Resource): @deployment.expect(depl_arg, validate=True) @deployment.expect(depl_arguments, validate=True) @deployment.response(description='deployment',code=200) @deployment.marshal_with(depl_model) def get(self, **kwargs): request_args = depl_arguments.parse_args(strict=True) name = request_args['name'] print(name) Here is my unit testcase: def testfunc(self): parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=False) res = Depl(args).get() self.assertIsNone(res) But I am not able to find a proper way to send the req_arg to 'get' function. can anybody help me out here how to pass name argument from a unit testcase.
has title: sending parameter from unit testcase for reqparse.RequestParser in python
answer count: 0
score: 1
tagged with: flask-restful
upvote count: 1
tagged with: unit-testing
type: Question
downvote count: 0

http://stackoverflow.com/a/51143307
accepted answer of: http://stackoverflow.com/q/51091969
score: 0
type: AcceptedAnswer
has body: The problem is that the sort method orders the data and that transformation is irreversible, the previous solution uses a proxy, this orders the visual part but not the data, so in the end in the case of the other solution it is enough to avoid reordering and show the original data. import numpy as np from qtpy import QtCore, QtGui, QtWidgets data = np.random.random((10, 3))*10 -9 app = QtWidgets.QApplication(['']) class SimpleModel(QtCore.QAbstractTableModel): headers = 'Col 1', 'Col 2', 'Col 3' def __init__(self, *args, **kwargs): super(SimpleModel, self).__init__(*args, **kwargs) table.setSortingEnabled(True) self.order = np.arange(data.shape[0]) self.layoutChanged.emit() def rowCount(self, index=None): return 10 def columnCount(self, index=None): return 3 def data(self, index, role=QtCore.Qt.DisplayRole): if role == QtCore.Qt.DisplayRole: col = index.column() row = index.row() return str(data[self.order[row], col]) def headerData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole : if orientation == QtCore.Qt.Horizontal : return self.headers[section] elif orientation == QtCore.Qt.Vertical : return section return None class SortProxyModel(QtCore.QSortFilterProxyModel): def lessThan(self, left_index, right_index): left_var = self.sourceModel().data(left_index) right_var = self.sourceModel().data(right_index) return float(left_var) &lt; float(right_var) table = QtWidgets.QTableView() model = SimpleModel() proxy = SortProxyModel() proxy.setSourceModel(model) table.setModel(proxy) table.show() cornerButton = table.findChild(QtWidgets.QAbstractButton) cornerButton.clicked.connect(lambda: proxy.sort(-1)) app.exec_()
type: Answer
answers question: http://stackoverflow.com/q/51091969

http://stackoverflow.com/comment/121612834
type: AnswerComment
comment on: http://stackoverflow.com/a/68813136
type: Comment
has text: Add `from random import *` to the top of that file, or rename it.
score: 0

http://stackoverflow.com/q/51164285
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51165225
downvote count: 0
score: 1
has body: I have three [MySQL] tables: Person, Role, PersonRole class Person(Base): __tablename__ = 'people' id = Column(INTEGER(unsigned=True), primary_key=True) full_name = Column(String(120), nullable=False) email = Column(String(128)) username = Column(String(50)) last_modified = Column(TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')) created = Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP')) roles = relationship('Role', secondary='person_role', primaryjoin="and_(Person.id==PersonRole.person_id," "Role.active==True," "PersonRole.active==True)", back_populates='people') def __repr__(self): """String representation.""" return '''&lt;Person(id='%s', full_name='%s')&gt;''' % ( str(self.id), str(self.full_name) ) class Role(Base): __tablename__ = 'role' id = Column(INTEGER(unsigned=True), Sequence('role_id_seq'), primary_key=True) role_name = Column(String(16)) active = Column(Boolean, default=True) last_modified = Column(TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')) created = Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP')) users = relationship('Person', secondary='person_role', primaryjoin="and_(Role.id==PersonRole.role_id," "Role.active==True," "PersonRole.active==True)", back_populates='roles') def __repr__(self): """String representation.""" return '''&lt;Role(role_id='%s', role_name='%s')&gt;''' % ( str(self.role_id), str(self.role_name) ) class PersonRole(Base): __tablename__ = 'person_role' ds_id = Column(INTEGER(unsigned=True), ForeignKey('person.id'), primary_key=True) role_id = Column(INTEGER(unsigned=True), ForeignKey('role.id'), primary_key=True) active = Column(Boolean, default=True) last_modified = Column(TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')) created = Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP')) Retrieving a Person like so: ...session setup as s... person = s.query(Pers…
tagged with: sqlalchemy
type: Question
has title: SQLAlchemy: Relationship Field Values
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/89096585
score: 0
type: Comment
has text: No, just the one
type: AnswerComment
comment on: http://stackoverflow.com/a/51051025

http://stackoverflow.com/q/51054253
score: 1
tagged with: dataframe
upvote count: 1
linked to: http://stackoverflow.com/q/51034307
type: Question
possible better answer: http://stackoverflow.com/a/51054354
has answer: http://stackoverflow.com/a/51054354
has answer: http://stackoverflow.com/a/51054357
downvote count: 0
answer count: 2
tagged with: pandas
has body: Question: How do you group a df based on a variable, make a computation using a for loop? The task is to make a conditional computation based on the value in a column. But the computational constants are dependent upon the value in the reference column. Given this df: In [55]: df = pd.DataFrame({ ...: 'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'], ...: 'col2' : [2, 1, 9, 8, 7, 4], ...: 'col3': [0, 1, 9, 4, 2, 3], ...: }) In [56]: df Out[56]: col1 col2 col3 0 A 2 0 1 A 1 1 2 B 9 9 3 NaN 8 4 4 D 7 2 5 C 4 3 I've used the solution here to insert a 'math' column that takes the balance from col3 and adds 10. But now I want to iterate over a list to set the computational variable dependent upon the values in col1. Here's the result: In [57]: items = ['A', 'D'] In [58]: for item in items: ...: df.loc[:, 'math'] = df.loc[df['col1'] == item, 'col3'] ...: In [59]: df Out[59]: col1 col2 col3 math 0 A 2 0 NaN 1 A 1 1 NaN 2 B 9 9 NaN 3 NaN 8 4 NaN 4 D 7 2 2.0 5 C 4 3 NaN The obvious issue is that the df is over written on each iteration. The math column for index 0 and 1 computed values on the first iteration, but they are removed on the second iteration. The resulting df only considers the last element of the list. I could go through and add coding to iterate through each index value - but that seems more pathetic than pythonic. Expected Output for the .mul() example In [100]: df Out[100]: col1 col2 col3 math 0 A 2 0 0.0 1 A 1 1 10.0 2 B 9 9 NaN 3 NaN 8 4 NaN 4 D 7 2 20.0 5 C 4 3 NaN
favorite count: 0
accepted answer: http://stackoverflow.com/a/51054357
has title: Modify values in a column based on condition from another
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89306823
comment on: http://stackoverflow.com/a/51161260
score: 0
type: AnswerComment
has text: Got another error for both member and non member of server ID. error code updated above. that id i replaced with fake Id here.
type: Comment

http://stackoverflow.com/comment/89182710
type: Comment
type: QuestionComment
has text: You shouldn't call that a matrix because matrix is a rectangular array of numbers. It's just a 2D array.
score: 1
comment on: http://stackoverflow.com/q/51097526

http://stackoverflow.com/a/51146679
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89277524
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89277552
has body: If you want to test if a string can be passed to int, use str.isdecimal. Both str.isnumeric and str.isdigit include decimal-like characters that aren't compatible with int. And as @abarnert has mentioned in the comments, the most guaranteed way to test if a string can be passed to int is to simply do it in a try block. On the other hand, '⒍' can be converted to an actual digit with the help of the unicodedata module, e.g. print(unicodedata.digit('⒍')) would output 6.
accepted answer of: http://stackoverflow.com/q/51146660
answers question: http://stackoverflow.com/q/51146660
has comment: http://stackoverflow.com/comment/89277442
type: Answer
has comment: http://stackoverflow.com/comment/89277616
score: 2

http://stackoverflow.com/a/72334878
upvote count: 2
has body: Currently, pipenv does not support this. One workaround adds a script like the following to the end of Pipfile: [scripts] install = "sh -c 'pipenv install ; pip install --no-deps aiopg'" With this script, calling pipenv run install installs all dependencies from the [packages] section, including aiopg but excluding its dependencies.
answers question: http://stackoverflow.com/q/51046150
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/108165021
type: AnswerComment
has text: @Arne bro, what configuration for Sphinx do you use? I can't achieve attributes documentation generation, like in your third example.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51131941

java
tags question: http://stackoverflow.com/q/51134686
tags question: http://stackoverflow.com/q/51034490
tags question: http://stackoverflow.com/q/51045578
tags question: http://stackoverflow.com/q/51121875
tags question: http://stackoverflow.com/q/51048972
tags question: http://stackoverflow.com/q/51164215
tags question: http://stackoverflow.com/q/51153046
tags question: http://stackoverflow.com/q/51055495
tags question: http://stackoverflow.com/q/51150260
tag name: java
tags question: http://stackoverflow.com/q/51116140
tags question: http://stackoverflow.com/q/51111626
tags question: http://stackoverflow.com/q/51134084
tags question: http://stackoverflow.com/q/51144228
type: Tag
tags question: http://stackoverflow.com/q/51029685
tags question: http://stackoverflow.com/q/51038762
tags question: http://stackoverflow.com/q/51110497

http://stackoverflow.com/comment/89267560
has text: Definitely better, thanks!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51141366
type: Comment

http://stackoverflow.com/comment/89224918
score: 2
has text: You should post the structure of your code, that way people can help you faster. Anyway take a look over here: https://stackoverflow.com/questions/49238583/flask-run-vs-python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51119495

http://stackoverflow.com/q/51077487
accepted answer: http://stackoverflow.com/a/51077812
favorite count: 0
has title: Pandas: How to subset (and sum) top N observations within subcategories?
has comment: http://stackoverflow.com/comment/89146015
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89145988
has comment: http://stackoverflow.com/comment/89146069
type: Question
has comment: http://stackoverflow.com/comment/89144455
has comment: http://stackoverflow.com/comment/89144173
has body: In a pandas dataframe such as this: year month passengers 0 1949 January 112 1 1949 February 118 2 1949 March 132 3 1949 April 129 4 1949 May 121 5 1949 June 135 . . . 137 1960 June 535 138 1960 July 622 139 1960 August 606 140 1960 September 508 141 1960 October 461 142 1960 November 390 143 1960 December 432 How can I subset (and do calculations on) the 3 months with the most passengers within each year? The very same dataframe can be reproduced from a seaborn dataset: import pandas as pd import seaborn as sns df = sns.load_dataset('flights') df Here's what I've tried: Following a suggestion in the comments from this post I found out that I could subset the dataframe using nlargest() after reindexing the dataframe: df = df.set_index(['year', 'month']) df2 = df.groupby(level=0)['passengers'].nlargest(3) df2 output: year year month 1949 1949 July 148 August 148 September 136 1950 1950 July 170 August 170 But for some reason the year index is duplicated, and I'd still have to reindex, group the dataframe by year and sum the results. This is already starting to get messy, so is there no better way of doing this? Here's the whole thing for an easy copy-paste: import pandas as pd import seaborn as sns df = sns.load_dataset('flights') df = df.set_index(['year', 'month']) df2 = df.groupby(level=0)['passengers'].nlargest(3) And here is the shape of the desired output: # Sum of top 3 months for each year (no index other than default pandas dataframe index) year sum 0 1949 600 (the sum is made up) 1 1950 600 . . . 10 1960 600 Thank you for any suggestions! EDIT: System info: Python 3.6.0 Pandas 0.19.2 Windows 7
upvote count: 3
has comment: http://stackoverflow.com/comment/89144589
tagged with: pandas
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/43472125
has answer: http://stackoverflow.com/a/51077812

http://stackoverflow.com/comment/89128500
type: Comment
comment on: http://stackoverflow.com/a/51068963
has text: Thanks, it worked! The main reason I was confused is because when I ran it locally the site worked perfectly, URL's and all.
type: AnswerComment
score: 0

http://stackoverflow.com/a/51170789
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Since your uid1 and uid2 are CharFields you need to use Cast database function if you want to perform arithmetical operations among CharFields. This should work: from django.db.models import F, IntegerField from django.db.models.functions import Cast students = OfflineExamResult.objects.annotate(uid1_int=Cast('uid1', IntegerField()), uid2_int=Cast('uid2', IntegerField())).annotate(roll=F('uid1_int') + F('uid2_int')).filter(roll=roll_number) P.S. I used IntegerField field in my example but if you have decimal numbers in the database you should use FloatField instead.
answers question: http://stackoverflow.com/q/51166785

http://stackoverflow.com/a/53903083
downvote count: 0
has comment: http://stackoverflow.com/comment/121811748
score: 4
has body: I had the same issue. Lgb predictions are outputed in a flattened array. By inspecting it, I figured out that it goes like this : probability of sample a to class i is located at num_classes*(a-1) + i position As for your code , it should be like that: def evalerror(preds, dtrain): labels = dtrain.get_label() preds = preds.reshape(5, -1).T preds = preds.argmax(axis = 1) f_score = f1_score(labels , preds, average = 'weighted') return 'f1_score', f_score, True
type: Answer
answers question: http://stackoverflow.com/q/51139150
upvote count: 4

http://stackoverflow.com/a/51144025
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51142617
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Since you’re running this as a CGI script, you can write to standard output: #!/usr/bin/env python3 import pyromat as pm import matplotlib.pyplot as plt import numpy as np import webbrowser from io import BytesIO import base64 # Create a temperature array in steps of 10K T = np.arange(300,2000,10) # Get the Oxygen object O2 = pm.get('ig.O2') f = plt.figure(1) # Call up figure 1 f.clf() # clear it (if it already exists) ax = f.add_subplot(111) # Create an axes object on the figure ax.plot(T, O2.cp(T)) # Add a curve to that axes ax.set_xlabel('Temperature (K)') ax.set_ylabel('Specific Heat (kJ/kg/K)') image_bytes = BytesIO() f.savefig(image_bytes, format="png") # write bytes to in-memory object image_bytes.seek(0) # go to beginning of bytes # print HTTP headers print("Content-Type: text/html; charset=utf-8") print() # encode as Base64 src = base64.b64encode(image_bytes.read()) message = """ Result Graph Test """ # print HTML with embedded image print(message.format(src)) This avoids writing either the HTML or the image to disk. Instead, it writes the HTML to standard output (which should show up in the browser) and embeds the image directly in the HTML source as Base64 data.
accepted answer of: http://stackoverflow.com/q/51142617
has comment: http://stackoverflow.com/comment/89272197

http://stackoverflow.com/comment/89269173
type: AnswerComment
has text: That link is very clear that variables *are neither passed by value nor passed by reference*, and are *always passed the same way*.
comment on: http://stackoverflow.com/a/51140662
type: Comment
score: 0

http://stackoverflow.com/q/51140011
has comment: http://stackoverflow.com/comment/89264375
has comment: http://stackoverflow.com/comment/102707239
has answer: http://stackoverflow.com/a/51140076
favorite count: 0
has body: I have a dataframe with several columns: df pymnt_plan ... settlement_term days Now I know which columns I Want to delete/drop, based on the following list: mylist = ['pymnt_plan', 'recoveries', 'collection_recovery_fee', 'policy_code', 'num_tl_120dpd_2m', 'hardship_flag', 'debt_settlement_flag_date', 'settlement_status', 'settlement_date', 'settlement_amount', 'settlement_percentage', 'settlement_term'] How to drop multiple columns which their names in a list and assigned to a new dataframe? In this case: df2 days
has comment: http://stackoverflow.com/comment/89264231
type: Question
has answer: http://stackoverflow.com/a/55213632
tagged with: python
possible better answer: http://stackoverflow.com/a/55213632
upvote count: 3
score: 0
answer count: 2
downvote count: 3
accepted answer: http://stackoverflow.com/a/51140076
linked to: http://stackoverflow.com/q/13411544
has comment: http://stackoverflow.com/comment/89274130
has comment: http://stackoverflow.com/comment/102707248
has title: pandas:drop multiple columns which name in a list and assigned to a new dataframe
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/q/51096552
score: -1
type: UnansweredQuestion
has body: Consider teams = [[], []] I want to add a people to teams, but only if (1) they for the same company as the others in the team OR (b) if the team is currently empty. The straight-forward way would be: for team in teams: if len(team) &gt; 0: # could also use "if bool(team):" if team[0].company == new_person.company: team.append(new_person) break else: continue else: team.append(new_person) break else: teams.append([]) teams[-1].append(new_person) To me that seems like many lines to make a simple decision. The complicating factor is the possibility of an empty list, which will give me an error if I try to look at a property of one of its elements. How can I say if a_list is empty or a_list[0].property == something: in one line?
has answer: http://stackoverflow.com/a/51096651
downvote count: 1
has comment: http://stackoverflow.com/comment/89180863
type: Question
tagged with: list
tagged with: comparison
has answer: http://stackoverflow.com/a/51096830
answer count: 3
upvote count: 0
has title: How can I say check in one line "if a_list is empty or a_list[0].property == something" in one line?
has comment: http://stackoverflow.com/comment/89181012
linked to: http://stackoverflow.com/q/363944
favorite count: 0
has answer: http://stackoverflow.com/a/51096881
has comment: http://stackoverflow.com/comment/89180877
tagged with: python

http://stackoverflow.com/a/51121366
has comment: http://stackoverflow.com/comment/89228223
has body: So the main problem is in these three lines forwards = forwards[:len(lefts)][:len(rights)] lefts = lefts[:len(forwards)] rights = rights[:len(forwards)] you are truncating the arrays. So to confirm the final shapes of the arrays do - print(len(forwards),len(lefts),len(rights)) // those 3 lines print(len(forwards),len(lefts),len(rights)) You'll see the difference. Also, try running the code without those three lines, the arrays will be 200 MB :) P.S. I would advise you to do truncation manually - forwards = forwards[:my_number] and so on..
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89228293
has comment: http://stackoverflow.com/comment/89228255
has comment: http://stackoverflow.com/comment/89228190
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51121203
answers question: http://stackoverflow.com/q/51121203
score: 1

http://stackoverflow.com/comment/89244251
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51129601
has text: I have code to evaluate the postfix expression. Adding to original question if it is useful.
type: Comment

http://stackoverflow.com/q/51114817
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51115243
accepted answer: http://stackoverflow.com/a/51115243
tagged with: python
has title: How to replace the column values with respect to index in each iteration.So that each table will be having new set of values in each iteration
type: AnsweredQuestion
has body: Can anyone help me with this. Index word 0 0 I 1 1 am 2 2 so 3 3 good 4 4 and 5 5 smart df_series=[] for d in range(0,2): df_series.append(df) def pos(x): position=[] for u in x: position.append(np.random.choice(u[0])) return position two = [5,2] j = [1,0] df1=[] df1.append(pd.DataFrame(two)) df1.append(pd.DataFrame(j)) df1 0 0 5 1 2 0 0 1 1 0 final=[] L=['NA','****'] for eachtable in df_series: # print(eachtable) eachtable.loc[pos(df1),'word'] = random.choice(L) final.append(eachtable) final Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA As of now I am getting like this only.Position is changing only for first table and repeating the same position for all the iteration.I want to changed position for each iteration. Can anyone find the mistake in my code and help me with this. I want like something like this print(final) Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA Index word 0 I 1 am 2 **** 3 good 4 NA 5 smart
score: 1
tagged with: dataframe
type: Question
upvote count: 1

http://stackoverflow.com/comment/89152702
type: Comment
has text: Yes it does, when I use Store.objects.all() it shows me the whole list of the stores that are being created.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51081803

http://stackoverflow.com/a/51164563
downvote count: 0
answers question: http://stackoverflow.com/q/51164491
score: 2
has body: sympy.solve() returns a list, so you'll need to somehow get the expressions out of that list, and you can call &lt;expression&gt;.evalf() to get a floating point representation of the solution: So either: print(k[0].evalf()) or for sol in k: print(sol.evalf()) will display: 3.99352431498656
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51164491

http://stackoverflow.com/a/51051644
type: Answer
answers question: http://stackoverflow.com/q/51051136
has body: i = '{a:b,c:d},{e:f,g:h}' [e.strip('{}') for e in i.split('},{')] # ['a:b,c:d', 'e:f,g:h']
score: 0
has comment: http://stackoverflow.com/comment/89096473

http://stackoverflow.com/comment/89021658
score: 0
type: Comment
type: QuestionComment
has text: Yes it updates @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000
comment on: http://stackoverflow.com/q/51014427

http://stackoverflow.com/comment/89161046
score: 0
type: AnswerComment
type: Comment
has text: @user2900860 Try adding `input=PIPE` to the arguments as well. By the way you did stress that you want get the status code in your question (you said "How to get the status code returned ?"). Saying that you don't care about it now just contradicts yourself.
comment on: http://stackoverflow.com/a/51067382

http://stackoverflow.com/comment/89052004
comment on: http://stackoverflow.com/a/51028519
type: Comment
has text: Quoting and escapes are part of the csv protocol. For instance, what if a column is `"embedded comma, should not split this column"`? CSV parses deal with this, which is why we use them instead of just splitting.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89129954
score: 0
type: Comment
has text: That's a copying error on my end, the contents of s does include ' ' at the end.
comment on: http://stackoverflow.com/a/51069669
type: AnswerComment

http://stackoverflow.com/q/51151343
tagged with: python
has body: I have a python script that makes a fetchall(): connection = pymssql.connect(host='host', user='user', password='pw', database='database', as_dict=True) cursor = connection.cursor() cursor.execute("EXEC SPname") data=cursor.fetchall() My problem is that the cursor.fetchall() is returning True or Falses (and others columns with others values example above) but in the database the value is a bit 1 or 0 and when exported to CSV it puts the True or False and I want 1 or 0. Sample data returned in SQL: ID Price Price2 Price3 Active Opened Sent Enable 1 12234.09 1111.09 3444.36 1 1 1 0
type: AnsweredQuestion
has title: Python fetchall return true and false
accepted answer: http://stackoverflow.com/a/51151390
type: Question
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51151491
tagged with: fetchall
has answer: http://stackoverflow.com/a/51151491
has answer: http://stackoverflow.com/a/51151390

http://stackoverflow.com/q/51107533
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89202395
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Load entire dict into a particular dataframe cell
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89203188
score: 0
has body: df = columnA columnAB row1 xxx row2 yyy row3 zzz row4 xyx expected df = columnA columnAB columnB row1 xxx [('A1(80)', ['BB11', 'A11', 'A21']), ('B1(70)', ['CC55', 'HH21']), ('C1(60)', ['KK88'])] row2 yyy row3 zzz row4 xyx from collections import defaultdict d1, d2 = defaultdict(int), defaultdict(list) d = {'A1BB11': 10, 'B1CC55': 20, 'A1A11': 30, 'A1A21': 40, 'B1HH21': 50, 'C1KK88': 60 } for k, v in d.items(): prefix = k[:2] d1[prefix] += v d2[prefix].append(k[2:]) final = {'{}({})'.format(k, d1[k]): v for k, v in d2.items()} print(final) # {'A1(80)': ['BB11', 'A11', 'A21'], # 'B1(70)': ['CC55', 'HH21'], # 'C1(60)': ['KK88']} Now I need to load this data in a dataframe cell, I tried converting this into list and load final = sorted(final.items()) # type(final) = &lt;class 'list'&gt; df.loc[df['columnA'].str.contains('row1', na=False), 'columnB'] = final But I run into error ValueError: setting an array element with a sequence could you suggest a way to handle this
tagged with: pandas

http://stackoverflow.com/q/51056542
answer count: 2
tagged with: beautifulsoup
has title: Python multiprocessing in for loop (requests and BeautifulSoup)
tagged with: python
has answer: http://stackoverflow.com/a/51056922
has body: I have list of a lot of links and I want to use multiprocessing to speed the proccess, here is simplified version, I need it to be ordered like this: I tried a lot of things, process, pool etc. I always had errors, I need to do it with 4 or 8 threads and make it ordered like this. Thank you for all help. Here is code: from bs4 import BeautifulSoup import requests import time links = ["http://www.tennisexplorer.com/match-detail/?id=1672704", "http://www.tennisexplorer.com/match-detail/?id=1699387", "http://www.tennisexplorer.com/match-detail/?id=1698990" "http://www.tennisexplorer.com/match-detail/?id=1696623", "http://www.tennisexplorer.com/match-detail/?id=1688719", "http://www.tennisexplorer.com/match-detail/?id=1686305"] data = [] def essa(match, omega): aaa = BeautifulSoup(requests.get(match).text, "lxml") center = aaa.find("div", id="center") p1_l = center.find_all("th", class_="plName")[0].find("a").get("href") p2_l = center.find_all("th", class_="plName")[1].find("a").get("href") return p1_l + " - " + p2_l + " - " + str(omega) i = 1 start_time = time.clock() for link in links: data.append(essa(link, i)) i += 1 for d in data: print(d) print(time.clock() - start_time, "seconds")
has answer: http://stackoverflow.com/a/51056871
score: 0
tagged with: multithreading
possible better answer: http://stackoverflow.com/a/51056922
tagged with: python-requests
tagged with: multiprocessing
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51056871

http://stackoverflow.com/comment/89171195
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51091396
type: AnswerComment
has text: @BryanOakley Fair point. I agree that `product` might be a little bit advanced for a beginner. That's why I felt it was appropriate to add the links to the docs & some explanation about it to my answer. OTOH, it's never too early to learn about `enumerate`, IMHO.

http://stackoverflow.com/q/51070495
tagged with: python
has body: I want to make a for loop (or any loop) to create a bunch of buttons for a calculator. For example the button for "0" plus the grid arrangement looks like this: Button0 = Button(root, text="0", command=lambda: btnPress(0)) Button0.grid(row=4, column=1) I use tkinter and tkk if it matters What I have been trying to do is this which obviously does not work: for x in range(0, 10): Button x = Button(root, text="x", command=lambda: btnPress(x)) row = 0 col = 0 if x == 0: Button + x.grid(row=4, column=1) if x % 3 == 0: row += 1 Button + x.grid(row=row, column=col) col = + 1 I guess the real question is how to make multiple objects with different names with a for loop, and if this is even possible.
duplicate of: http://stackoverflow.com/q/1373164
has title: Multiple objects with different names Python
has comment: http://stackoverflow.com/comment/89133611
has comment: http://stackoverflow.com/comment/89130854
tagged with: loops
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89130879
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164

http://stackoverflow.com/q/51157288
has answer: http://stackoverflow.com/a/63068208
has answer: http://stackoverflow.com/a/51157298
possible better answer: http://stackoverflow.com/a/63068208
has title: pandas:add a column based on another one
answer count: 3
tagged with: pandas
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51157298
has body: I want to add a column based on column 'mths_since_recent_revol_delinq',if mths_since_recent_revol_delinq is null then get the new column equals 1,and get new dataframe like: +----+--------------------------------+------------------------------------+ | | mths_since_recent_revol_delinq | mths_since_recent_revol_delinq_add | +----+--------------------------------+------------------------------------+ | 0 | NaN | 1 | | 1 | 33 | 0 | | 2 | NaN | 1 | | 3 | NaN | 1 | | 4 | 57 | 0 | | 5 | 21 | 0 | | 6 | 60 | 0 | | 7 | NaN | 1 | | 8 | 2 | 0 | | 9 | 24 | 0 | | 10 | NaN | 1 | +----+--------------------------------+------------------------------------+ def label_race (df): if df['mths_since_recent_revol_delinq'].isnull(): return 1 else: return 0 Loan_a1['mths_since_recent_revol_delinq_add'] = Loan_a1.apply (lambda df: label_race(df),axis=1) and Traceback : --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 Loan_a1['mths_since_recent_revol_delinq_add'] = Loan_a1.apply (lambda df: label_race(df),axis=1) D:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds) 4150 if reduce is None: 4151 reduce = True -> 4152 return self._apply_standard(f, axis, reduce=reduce) 4153 else: 4154 return self._apply_broadcast(f, axis) D:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce) 4246 try: 4247 for i, v in enumerate(series_gen): -> 4248 results[i] = func(v) 4249 keys.append(v.name) 4250 except Exception as e: in (df) ----> 1 Loan_a1['mths_since_recent_revol_delinq_add'] = Loan_a1.apply (lambda df: label_race(df),axis=1) in label_race(df) 1 def label_race (df): ----> 2 if df['mths_since_recent_revol_delinq'].isnull(): 3 return 1 4 else: 5 return 0 AttributeError: ("'float' object has no attribute 'isnull'", 'occurred at index 0') any ideas on how to …
tagged with: python
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51158076
type: Question

http://stackoverflow.com/comment/89302113
type: Comment
type: QuestionComment
has text: Try `l1, l2 = zip(*(map(int, i.split(',')) for i in l))`.
comment on: http://stackoverflow.com/q/51159355
score: 1

http://stackoverflow.com/a/51052034
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51048776
answers question: http://stackoverflow.com/q/51048776
upvote count: 3
has body: There are 2 kinds of messaging models: Point to Point (one to one) - a message is sent from one application to another application via a queue. There can be more than 1 consuming (receiver) applications but only one of them will receive the message. Publish / Subscribe - is where a message is published to a topic and multiple consumers (subscribers) will each receive a copy of the message. There can be 1 or more applications publishing messages to the same topic and 1 or more applications consuming (receiving) the messages. MQTT is built on the Publish / Subscribe messaging model. Your description sounds like you want Point to Point messaging. Yes, you can bend MQTT to act like Point to Point but be aware that if you have multiple applications publishing messages to the same topic, you may get confused. MQTT_PATH = "test_channel" publish.single(MQTT_PATH, "Hello World!", hostname=MQTT_SERVER) There is no such thing as a "channel" in MQTT. Your code is publishing a message to the topic called: test_channel. It is better to use a little hierarchy in your topic names. i.e. pivk95/food/burgers pivk95/food/fries pivk95/food/pizza pivk95/food/burritos pivk95/drink/shakes pivk95/drink/soft_drink Just remember that any number of applications can publish messages to a given topic and any number of applications can subscribe to a given topic and receive copies of the messages.
type: AcceptedAnswer
type: Answer
score: 3

http://stackoverflow.com/q/51046762
has comment: http://stackoverflow.com/comment/89084810
linked to: http://stackoverflow.com/q/4406389
tagged with: python
has answer: http://stackoverflow.com/a/51046916
has title: If, else statement for large array
has body: I want to plot some data of wind speed and direction on a wind rose (polar rose plot), but it seems that the library I am using (windrose) doesn't like when you feed it a negative wind direction. Thus, I am trying to add 360 degrees to all the negative values, thinking that it should plot. I tried doing the method shown in this post, if else in a list comprehension, but I still have plenty of negative numbers in my array. wind_speed=np.sqrt(u**2+v**2) wind_dir_calc=np.arctan(v/u) wind_dir=np.degrees(wind_dir_calc) [x+360 if x&lt;0 else x+0 for x in wind_dir] np.set_printoptions(threshold=np.inf) print(wind_dir) Sample output: [-6.34019175 84.6607632 -58.73626831 55.40771131 73.87242417 66.70543675 48.0127875 50.71059314 52.27500496 38.15722659 37.50414236 48.14495746 -2.20259816 16.53483786 38.75162833 19.0466243 -58.67130713 -63.00416161 -65.41842552 -74.96956948 -74.23281746 -68.36911316 -46.46880071 -83.26398879 -80.75388725...]
has comment: http://stackoverflow.com/comment/89084745
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51046921
tagged with: list
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/51046916
downvote count: 1
type: Question
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/51046921
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/89085152
has comment: http://stackoverflow.com/comment/89085010
tagged with: arrays
favorite count: 0

http://stackoverflow.com/a/51167856
type: Answer
answers question: http://stackoverflow.com/q/51165305
upvote count: 1
has comment: http://stackoverflow.com/comment/89355032
score: 1
has comment: http://stackoverflow.com/comment/89355329
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51165305
has body: Do i need to cut my sentences into words or just use sentences for train HMM models? Theoretically you just need sentences and phonemes. But having isolated words may be useful for your model (it increases the size of your training data) Do I need phonemes dataset for train ? if yes do i need to train it use HMM too ? if not how my program recognize the phonemes for HMM predict input? You need phonemes, otherwise it will be too hard for your model to find the right phoneme segmentation if it does not have any example of isolated phonemes. You should first train your HMM states on the isolated phonemes and then add the rest of the data. If you have enough data, your model may be able to learn without the isolated phoneme examples, but I wouldn't beat on this. What steps i must do first ? Build your phoneme examples and use them to train a simple HMM model you don't model the transition between phonemes. Once your hidden states have some information about phonemes, you may continue the training on isolated words and sentences.

http://stackoverflow.com/a/51046200
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89083890
type: Answer
has body: Your example didn't work because map() behaves differently in Python 2 vs Python 3. In Python 2 it returns a list, but in Python 3 it returns a special map object. You can convert it to a list by calling list() on it: this_map = list(this_map)
accepted answer of: http://stackoverflow.com/q/51046087
answers question: http://stackoverflow.com/q/51046087

http://stackoverflow.com/q/51012614
tagged with: dataframe
has title: How to iterate through two data frames in python
upvote count: 2
tagged with: pandas
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89018028
favorite count: 0
tagged with: python-3.x
has body: I have two Data frames df1( having columns C1,C2,etc) and df2(having columns S1,S2,etc) I want to iterate through each column of both the Data Frames. Currently I am doing the following thing: df3=pd.Dataframe([]) for index1,row1 in df1.iterrows(): for index2,row2 in df2.iterrows(): if row1['C1']==row2['S1']: #perform Some Operations on each row like: df3 = df3.append(pd.DataFrame({'A': row2['S1'], 'B': row2['S2'],'C':functionCall(row1['c3'], row2['S3'])}, index=[0]), ignore_index=True) This works ok but it takes too much time. I wanted to know, Is there a more efficient way of iterating through two Data Frames?
linked to: http://stackoverflow.com/q/41463119
tagged with: python
has comment: http://stackoverflow.com/comment/89038945
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89018122
has answer: http://stackoverflow.com/a/51012679
has comment: http://stackoverflow.com/comment/89017973
type: Question
has comment: http://stackoverflow.com/comment/89038845

http://stackoverflow.com/comment/89099812
has text: Any work around without renaming the columns. Renaming the columns does not work in my application as it has lot of further processing.
comment on: http://stackoverflow.com/a/51054388
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89018095
has text: To find the max value you need to go through the whole list once - no need to sort. You can do this manually (`for el in li:` and then remember the max one manually) or simpy type `max(li)` - for tuples max checks the first element of the tuple, further tuple elements only come into play if the earlier ones are tied.
comment on: http://stackoverflow.com/q/51012646
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51030426
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51030011
has comment: http://stackoverflow.com/comment/89053577
type: Answer
has body: I am not an expert but what happens is that you are getting as results the variables that make your plot. I have run it into Spyder and on the right (variables section) I also get your results. What you need to do however, is to write explicitly "show the plot": .... plt.colorbar plt.show() This will plot automatically your plot in a new window without showing all the arrays. Here some explanation Previous post.
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51030011
has comment: http://stackoverflow.com/comment/89053410
has comment: http://stackoverflow.com/comment/89054117
has comment: http://stackoverflow.com/comment/89053918

http://stackoverflow.com/comment/89159629
score: 0
type: Comment
has text: sry i was referring to the linear case without polynomial features. For the polynomial case it should be the number of features times the degree (+1 if you're estimating with constant included)
type: QuestionComment
comment on: http://stackoverflow.com/q/51043573

http://stackoverflow.com/comment/89309715
score: 0
has text: @wizzwizz4 Well this is more of a pandas thing tbh. Normally pandas is not tagged with np.
type: QuestionComment
comment on: http://stackoverflow.com/q/51163175
type: Comment

http://stackoverflow.com/comment/89274760
has text: Does it works limit 1,1 for min and limit 5,1 for max?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51145204

http://stackoverflow.com/comment/89075096
type: Comment
comment on: http://stackoverflow.com/a/51039695
type: AnswerComment
score: 0
has text: Alright, but then I'm confused as to what you are asking

http://stackoverflow.com/comment/89183858
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51097943
type: QuestionComment
has text: Wouldn't it be just `{{ comment.whose.profile.i_need }}`? But you should show the actual models.

http://stackoverflow.com/comment/89194909
comment on: http://stackoverflow.com/q/51099630
has text: I agree, the first error is that the ``cython_wrapper.pxd`` file can't be found, even though it's in the same directory as the ``cython_wrapper.pyx`` file.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51151459
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89286364
score: 0
has title: Custom search in Dask
has comment: http://stackoverflow.com/comment/89289939
tagged with: dask-distributed
tagged with: dask
type: UnansweredQuestion
has body: I have 1000 regex patterns which I have to search in each of the 9000 strings. Normal brute force method using pandas list took 25 min for the same task. I have used delayed function of dask to parallelize the entire function. It took 9 min to accomplish the task. I need to have more speedup. How can I leverage dask arrays or dask dataframe to do the task? Or is there any faster way to do it? def match(string): for regex in regex_list: if re.search(regex, string): pass [match(x) for x in string_list]
tagged with: python
tagged with: dask-delayed

http://stackoverflow.com/comment/89310912
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51162314
type: Comment
has text: @Anthony Yes, and that analogy will even help you correctly guess what happens if you, e.g., leave a space between the backslash and the newline. Just remember that it's an analogy and don't take it too far. (When in doubt, you have to come back to how it actually works, as described in the lexer section of the reference docs, but you should rarely if ever be in doubt.)

http://stackoverflow.com/q/51112630
accepted answer: http://stackoverflow.com/a/51112848
tagged with: discord.py
has comment: http://stackoverflow.com/comment/89212352
has comment: http://stackoverflow.com/comment/89212157
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89212247
has comment: http://stackoverflow.com/comment/89212184
has title: StreamPlayer "after" function isn't being called
downvote count: 0
score: 1
favorite count: 0
has body: I am creating a discord bot that can play music but I'm a bit stuck because when the bot finishes playing music is should leave the current voice channel. However this isn't happening, instead my after function vc.disconnect isn't being called at all though I've followed the instructions on the FAQ page. vc = await bot.join_voice_channel(ctx.message.author.voice_channel) player = await vc.create_ytdl_player(arg.split(' ')[1], after=vc.disconnect) player.start()
has comment: http://stackoverflow.com/comment/89212337
type: Question
has answer: http://stackoverflow.com/a/51112848
tagged with: python
tagged with: discord
has comment: http://stackoverflow.com/comment/89212123
has comment: http://stackoverflow.com/comment/89212299
upvote count: 1
has comment: http://stackoverflow.com/comment/89212207
answer count: 1
has comment: http://stackoverflow.com/comment/89212245
has comment: http://stackoverflow.com/comment/89212008

http://stackoverflow.com/a/56991005
has comment: http://stackoverflow.com/comment/110006224
type: Answer
answers question: http://stackoverflow.com/q/51124878
has comment: http://stackoverflow.com/comment/111644768
upvote count: 4
downvote count: 0
score: 4
has body: You can't associate Jenkinsfile with Groovy in PyCharm, but you can associate them with Java. Not perfect, but the syntax is similar enough to be useful for simple files. To do that (in PyCharm 2018.3): PyCharm → Preferences → Editor → File Types → Select "Java" under "Recognized File Types" → Click the + → Type "Jenkinsfile"

http://stackoverflow.com/a/51119188
has body: To my knowledge, this is not possible with seaborn because it sadly does not provide any means of modifying the positions keyword. See also this similar question. The easiest workaround is to use a different boxplot function, for example the one that comes with pandas dataframes: bplot = tips.boxplot(by="day", column="total_bill", positions=[1,2,3,4.5]) Of course, this is nowhere near as nicely styled as the seaborn version. Fortunately, matplotlib provides infinite options to those willing to explore them, so one could create something similar to the seaborn plot by modifying the different parts of the plot accordingly. This comes close: # Prep import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") # Create boxplot bplot = tips.boxplot(by="day", column="total_bill", positions=[1,2,3,4.5], return_type='dict', figsize=(8,6), grid=False, patch_artist=True, sym='d', fontsize=16) # Style boxplot colors = ['blue', 'green', 'red', 'cyan'] for patch, color in zip(bplot['total_bill']['boxes'], colors): patch.set_facecolor(color) patch.set_edgecolor('0.2') patch.set_linewidth(1.5) for whisker in bplot['total_bill']['whiskers']: whisker.set_color('0.2') whisker.set_linewidth(1.5) for fliers in bplot['total_bill']['fliers']: fliers.set_markerfacecolor('0.2') for median in bplot['total_bill']['medians']: median.set_color('0.2') median.set_linewidth(1.5) for caps in bplot['total_bill']['caps']: caps.set_color('0.2') caps.set_linewidth(1.5) # Other adjustments plt.title("") plt.suptitle("") plt.xlabel("day", fontsize=18) plt.ylabel("total_bill", fontsize=18)
downvote count: 0
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51105226

http://stackoverflow.com/q/51106564
score: 3
answer count: 0
downvote count: 0
tagged with: selenium
type: Question
upvote count: 3
favorite count: 0
has title: Selenium IDE browser plugin 3.1.0
has body: I have installed the new (!) Selenium IDE 3.1.0 Firefox plugin, and I can't find any facilities to export the tests, to run them from Python driver. What am I missing? Search on SO only returns suggestions for the legacy IDE, but not for the new web-browser plugin
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/104478683
tagged with: python

http://stackoverflow.com/q/51115590
tagged with: python
has body: How do I remove the superscripts from all of the text? I have code below that gets all visible text, but the superscripts for footnoting are messing things up. How do I remove them? for example Active accounts (1),(2), (1),(2) are visible superscripts. from bs4 import BeautifulSoup from bs4.element import Comment import requests f_url='https://www.sec.gov/Archives/edgar/data/1633917/000163391718000094/exhibit991prq12018pypl.htm' def tag_visible(element): if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']: return False if isinstance(element, Comment): return False return True def text_from_html(body): soup = BeautifulSoup(body, 'html.parser') texts = soup.findAll(text=True) visible_texts = filter(tag_visible, texts) return u" ".join(t.strip() for t in visible_texts) html = requests.get(f_url) text= text_from_html(html.text)
favorite count: 0
upvote count: 3
accepted answer: http://stackoverflow.com/a/51116004
downvote count: 1
type: Question
type: AnsweredQuestion
has title: Beautiful soup remove superscripts
has comment: http://stackoverflow.com/comment/89218331
score: 2
answer count: 1
has comment: http://stackoverflow.com/comment/89217664
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51116004

ssh
tags question: http://stackoverflow.com/q/51044259
tags question: http://stackoverflow.com/q/51111868
tags question: http://stackoverflow.com/q/51099873
tags question: http://stackoverflow.com/q/51164489
tags question: http://stackoverflow.com/q/51057611
tags question: http://stackoverflow.com/q/51065438
tags question: http://stackoverflow.com/q/51085083
tags question: http://stackoverflow.com/q/51156884
tags question: http://stackoverflow.com/q/51148715
type: Tag
tags question: http://stackoverflow.com/q/51103887
tag name: ssh
tags question: http://stackoverflow.com/q/51027192

http://stackoverflow.com/q/51156864
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89297810
tagged with: math
has body: Here I have made a code to create random sized bubbles which can be destroyed by collision of another object: import tkinter window = tkinter.Tk() window.title("...") c = tkinter.Canvas(width=800, height=500, bg="...") ojct_id1 = c.create_polygon(...) ojct_id2 = c.create_oval(...) # A polygon in an oval should constitute the object def move ojct(event): ... from random import randint bubbles = list() bubbles_r = list() # radius bubbles_speed = list() def create_bub(): ... def move_bubbles(): ... from time import sleep while True: if randint(1, 10) == 1: create_bub() move_bubbles() window.update() sleep(0.01) The following code determines the position of any bubble:That helps to find out collision. def hole_coord(id_num): pos = c.coords(id_num) x = (pos[0] + pos[2])/2 y = (pos[1] + pos[3])/2 return x, y Now I have to make func. for deleting bubbles: def del_bubbles(): del bubbles_r[i] del bubbles_speed[i] c.delete(bubbles[i]) del bubbles[i] The following code determines, if the two objects are colliding: from math import sqrt def distance(id1, id2): x1, y1 = hole_coord(id1) x2, y2 = hole_coord(id2) return sqrt((x2 - x1)/2 + (y2 - y1)/2) def collision(): for bub in range(len(bubbles)-1, -1, -1): if distance(ojct_id2, bubbles[bub]) &lt; (15 + bubbles_r[bub]): del_bubbles(bub) Here it is sth. wrong: bubbles get deleted without a hit but if they are hit often they don't get deleted. Can anybody help me? Thanks!
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: How to determine collision in python in right way
tagged with: python
has answer: http://stackoverflow.com/a/51157230
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89329964
score: 0
accepted answer: http://stackoverflow.com/a/51157230

http://stackoverflow.com/comment/89165695
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51088481
type: Comment
has text: i dont want any association between them

http://stackoverflow.com/comment/89303511
score: 0
has text: You can get rid of the outer brackets and make it a generator expression: `l1, l2 = (list(d) for d in zip(*[[int(i) for i in c.split(',')] for c in l]))`
type: Comment
comment on: http://stackoverflow.com/a/51159387
type: AnswerComment

http://stackoverflow.com/comment/89236841
has text: In both OP code and @zindarod code, minRadius and maxRadius are set to zero, which will return LOTS of results. You may wish to set these parameters.
comment on: http://stackoverflow.com/a/51100375
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/89133191
has text: @pault While your edit is constructive, I'd prefer if you didn't edit my answer so substantially. Especially considering you have already answered the question yourself.
comment on: http://stackoverflow.com/a/51070569
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51045018
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89081272
has body: .norm() returns a unit vector so that the result is a vector not a scalar. This is the vector form of Newtonian gravity. (See Wikipedia) .mag2 does the same thing as what is expected from **2, however in general, powers of vectors are not defined, so it wouldn't make sense to define the exponentiation operator on the vector class.
upvote count: 1
answers question: http://stackoverflow.com/q/51044800

notification-area
tags question: http://stackoverflow.com/q/51104372
type: Tag
tag name: notification-area

http://stackoverflow.com/q/51128177
has title: Auto Transform into New Data - Pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/89243135
has answer: http://stackoverflow.com/a/51130253
has comment: http://stackoverflow.com/comment/89244348
tagged with: transpose
tagged with: python
has body: I am a newbie in python, I search in StackOverflow for my case but I couldn't find the technical answer. I have a big number of BS row. my problem like this, I have a dataframe: df BS N BS1 - BS5 1 BS2 - BS7 2 BS1 - BS9 2 BS9 - BS1 1 I want to make new data automatically. My expected result like this: New_BS BS1 - BS5 BS2 - BS7 BS1 - BS9 BS9 - BS1 Total BS1-2 1 2 3 BS2-3 1 2 2 5 BS3-4 1 2 2 5 BS4-5 1 2 2 5 BS5-6 2 2 4 BS6-7 2 2 4 BS7-8 2 2 BS8-9 2 2 BS9-8 1 1 BS8-7 1 1 BS7-6 1 1 BS6-5 1 1 BS5-4 1 1 BS4-3 1 1 BS3-2 1 1 BS2-1 1 1 thank you in advance for helping me
type: AnsweredQuestion
tagged with: row
has comment: http://stackoverflow.com/comment/89244592
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89241562
has comment: http://stackoverflow.com/comment/89244294
score: 0
accepted answer: http://stackoverflow.com/a/51130253
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89241754
answer count: 1

http://stackoverflow.com/a/51110816
has comment: http://stackoverflow.com/comment/89208667
has comment: http://stackoverflow.com/comment/125576352
downvote count: 1
has comment: http://stackoverflow.com/comment/89276711
type: AcceptedAnswer
upvote count: 87
has body: Use tempfile.NamedTemporaryFile to create a temporary file with a name, and then use the .name attribute of the object. Note that there are platform-specific limitations on how this name can be used. The documentation says: Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
answers question: http://stackoverflow.com/q/51110783
accepted answer of: http://stackoverflow.com/q/51110783
score: 86
has comment: http://stackoverflow.com/comment/89208676
has comment: http://stackoverflow.com/comment/89273992
type: Answer

http://stackoverflow.com/comment/89278567
type: Comment
has text: Ohh. @Damian you're working with windows right? were you able to include python in your Environment Variables?
score: 0
comment on: http://stackoverflow.com/q/51147178
type: QuestionComment

http://stackoverflow.com/comment/89126676
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51067922
has text: I've also tried filling out all the hidden variables in the values. And no dice, is I'm not sure about the seeds though, as it re-generates everytime i re-fresh
score: 0

http://stackoverflow.com/comment/89236259
type: Comment
comment on: http://stackoverflow.com/q/51125415
score: 0
has text: This autogenerated docstring doesn't show up if I already have a docstring on the class, which is fine, because a human-supplied docstring is (usually!) much better than an autogenerated one. Manually assigning the docstring is definitely clunky and something I'd like to avoid if possible, hence this question.
type: QuestionComment

http://stackoverflow.com/q/51024384
has title: more efficient way to search through geoJson in double for loop Python
type: Question
linked to: http://stackoverflow.com/q/32976373
tagged with: for-loop
downvote count: 0
tagged with: shapely
tagged with: python
favorite count: 0
has body: What is the most efficient (or Pythonic way) to search in double for loop through geoJson file? I would like to find the Linestrings that starts or ends coordinates equals point coordinates. I mean, I need first iterate over point file then for loop over linestring file and in case coordinates are equal dump it into new geojson file. You can see my code below: for j, feature2 in enumerate(nav['features']): if feature2['properties']['gp'] in ('RTE', 'RTB', 'RTA'): for i, feature in enumerate(tra['features']): segment = LineString( [Point(feature['geometry']["coordinates"][0]), Point(feature['geometry']["coordinates"][1])]) if Point(poi) != Point(segment.coords[0]) and Point(poi) != Point(segment.coords[1]): continue after that I do some calculations with these points and dump them to new file. My point file contains ~ 10k and linestring file ~ 90k objects and now processing takes more than a day. I found similar topic but it seems to have no effect in my case I will appreciate any ideas of how process this more elegant and efficient!
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: geojson
score: 2

http://stackoverflow.com/a/51026631
has body: 1) Don't use old "init.d" method. Use something modern. If you have Ubuntu 15.04 and higher, you can use Systemd to create daemon that will be started automatically at startup. If you have for example Ubuntu older than 15.04 - use Upstart. For Systemd: Create unit file in /lib/systemd/system/you_service_name.service with the following content (as far as I can see your python script doesn't spawn new process while running, so Type should be simple. More info here): [Unit] Description=&lt;your_service_name&gt; After=network.target network-online.target [Service] Type=simple User=&lt;required_user_name&gt; Group=&lt;required_group_name&gt; Restart=always ExecStartPre=/bin/mkdir -p /var/run/&lt;your_service_name&gt; PIDFile=/var/run/&lt;your_service_name&gt;/service.pid ExecStart=/path/to/python_executable /path/to/your/script.py [Install] WantedBy=multi-user.target Save this file and reload systemd: sudo systemctl daemon-reload Then add your service to autostart: sudo systemctl enable you_service_name.service you should see that Systemd created required symlinks after enable action. Reboot and see if it's up and running (ps aux | grep python or sudo systemctl status you_service_name.service). If there is something weird - check Systemd journal: sudo journalctl -xe UPD: To launch your python script in desired virtualenv, just use this expression in your service unit file: ExecStart=/venv_home/path/to/python /venv_home/path/to/your/script.py 2) You can also use crontab, but you need to specify full path for desired shell there, for example: @reboot /bin/bash /path/to/script.sh If you need additional help - just let me know here.
type: Answer
score: 11
answers question: http://stackoverflow.com/q/51025312
upvote count: 11
accepted answer of: http://stackoverflow.com/q/51025312
has comment: http://stackoverflow.com/comment/89057367
has comment: http://stackoverflow.com/comment/120393364
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89046850

http://stackoverflow.com/comment/89126798
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51068439
has text: What happens when you use `import telethon`, `telethon.sync`? What is the traceback of the attribute error that throws?
score: 0

http://stackoverflow.com/q/51100306
accepted answer: http://stackoverflow.com/a/51100358
linked to: http://stackoverflow.com/q/3394835
has title: TypeError in python which says that dict object is not callable
favorite count: 0
has answer: http://stackoverflow.com/a/51100360
answer count: 5
has answer: http://stackoverflow.com/a/51100358
upvote count: 1
tagged with: python
has body: I'm new to Python. I am getting the error TypeError:dict object is not callable. I haven't used dictionary anywhere in my code. def new_map(*arg1, **func): result = [] for x in arg1: result.append(func(x)) return result I tried calling this function as follows: new_map([-10], func=abs) But when I run it, I am getting the above error.
has answer: http://stackoverflow.com/a/51100392
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51100380
score: 1
has answer: http://stackoverflow.com/a/51100529
type: Question
possible better answer: http://stackoverflow.com/a/51100360
downvote count: 0
tagged with: keyword-argument
tagged with: typeerror
linked to: http://stackoverflow.com/q/36901

http://stackoverflow.com/q/51018963
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52673604
tagged with: pickle
tagged with: python
linked to: http://stackoverflow.com/q/52395651
has title: Serialize/Deserialize tfidf-vectorizer with custom tokenizer on AWS
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92139382
has body: Good morning! I am currently working with an TfidfVectorizer from sklearn and a customized tokenizer. The idea is to create a pickled TfidfVectorizer and to load this vectorizer into a AWS Lambda-function, which transforms text input. The problem is: On my local machine it works fine: I am able to load the vectorizer from the S3-bucket, deserialize it, create a new vectorizer-object and use it to transform text. On AWS it does not work. It seems that it cannot load my customized tokenizer, I always get an AttributeError. I already tried using a lambda function and the dill-pickler, but it does not work on AWS either. It cannot find the PorterStemmer-module I use in my customized tokenizer. The serialized TfidfVectorizer(I serialized it on my local machine): import pickle from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem.porter import PorterStemmer def tokenizer_porter(text): porter = PorterStemmer() return [porter.stem(word) for word in text.split()] tfidf = TfidfVectorizer(ngram_range=(1, 1), stop_words=None, tokenizer=tokenizer_porter) tfidf.fit(X) pickle.dump(tfidf, open(pickle_path + 'tfidf_vect.pkl', 'wb'), protocol=4) The deserialization (in the AWS Lambda-service): def tokenizer_porter(text): porter = PorterStemmer() return [porter.stem(word) for word in text.split()] def load_model_from_bucket(key, bucket_name): s3 = boto3.resource('s3') complete_key = 'serialized_models/' + key res = s3.meta.client.get_object(Bucket=bucket_name, Key=complete_key) model_str = res['Body'].read() model = pickle.loads(model_str) return model tfidf = load_model_from_bucket('tfidf_vect.pkl', bucket_name) tfidf.transform(text_data) In AWS Cloudwatch I get this Traceback: Can't get attribute 'tokenizer_porter' on &lt;module '__main__' from '/var/runtime/awslambda/bootstrap.py'&gt;: AttributeError Traceback (most recent call last): File "/var/task/handler.py", line 56, in index tfidf = load_model_from_bucket('tfidf_vect.pkl', bucket_name) File "/var/task/han…
has comment: http://stackoverflow.com/comment/92276923
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
linked to: http://stackoverflow.com/q/50465106
has comment: http://stackoverflow.com/comment/92213880

http://stackoverflow.com/comment/89127256
type: Comment
score: 1
has text: On UNIX, `shell=True` is actively harmful in this use case -- `python` alone would be parsed as a shell script, and the additional argument would be ignored because the script that's given in the first argument never looks at its subsequent arguments (doesn't refer to `$0`, `$1`, etc). Might not make a difference on Windows, though; command-line handling is... different there.
comment on: http://stackoverflow.com/a/51068693
type: AnswerComment

http://stackoverflow.com/comment/89764863
has text: The graph would show levels by hierarchy, so horizontal placement is not an issue.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51157949

http://stackoverflow.com/comment/89171353
type: QuestionComment
score: 0
has text: what I must add is this object does not have __dict__ as it is not descendent of object.
type: Comment
comment on: http://stackoverflow.com/q/51091565

http://stackoverflow.com/q/51046282
accepted answer: http://stackoverflow.com/a/51055162
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51055162
type: Question
score: 3
tagged with: plotly
has body: How to set x and y range in a bar plot. My plot currently likes the following (in python): x = [1,2,3,5,6,7] y = [3,5,76,8,96,1] data = [go.Bar( x=x, y=y )] layout = { 'xaxis': {'title': 'Query Duration'}, 'yaxis': {'title': 'Proportion (%)'}, 'barmode': 'relative' } But as I tested, I couldn't send range to the data or layout.
has title: Set x and y range in bar plot in plotly
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51046150
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
answer count: 2
tagged with: python
has title: How to ignore the dependencies of a specific package when installing it with pipenv?
score: 22
has body: Is there a possibility to install a python package with pipenv without also installing the dependencies? I'm looking for an analogue of pip install package_name --no-dependencies for the Pipfile. I already tried to specify with a marker but it raises an exception. [packages] "psycopg2-binary" = "*" "aiopg"={version = "*", markers="--no-dependencies"}
has answer: http://stackoverflow.com/a/71534365
has answer: http://stackoverflow.com/a/72334878
upvote count: 22
tagged with: pipenv

http://stackoverflow.com/a/51156863
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51154729
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51154729
has body: The error occurred because the code is compiled using python3 but the module was installed using pip. So the pytesseract module was installed to Python2 instead of Python3. Installing using pip3 would solve the problem.
upvote count: 3

http://stackoverflow.com/q/51106189
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89201589
answer count: 0
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/89213227
has body: I am encountering issue in editing the values fetched from DB. Encountering the below error: mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1") Results are displayed as below When Edit Profile is clicked for example the first one the below details are fetched correctly when editing the details and clicking on Submit encountering the above mentioned error. Using the below code to edit the results @app.route('/Update', methods=['GET', 'POST']) def Update(): CR_ID = request.args.get('CR_ID') cur = mysql.connection.cursor() result = cur.execute("""SELECT CR_ID, name, email, CRType from users where CR_ID = %s""",CR_ID) # result = cur.execute("Update table users set name=?, email=?, CRType=? where CR_ID = %s", CR_ID) RV = cur.fetchall() user = RV[0] cur.close() return render_template('Update.html',user=user) to Update the records using the below code: @app.route('/UpdateData', methods=['GET', 'POST']) def UpdateData(): name = request.args.get('name') email = request.args.get('email') CRType = request.args.get('CRType') cur = mysql.connection.cursor() result = cur.execute("""Update table users set name=?, email=?, CRType=? where CR_ID = ?""") mysql.connection.commit() cur.close() return index()
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/89199952
has title: How to Edit Data fetched from DB in Python Flask
has comment: http://stackoverflow.com/comment/89366837

http://stackoverflow.com/q/51121099
has answer: http://stackoverflow.com/a/51133312
type: Question
tagged with: c#
has body: If I have an UI written using C#, and I'd like to press a button and call a python script (which depends on a number of external python library, such as matplotlib). My final application have to be deployed in Windows platform. Which should be the approach to do? IronPython: It does not support Python3 yet, and I cannot use it. Python For .NET: I still get confused on the use of Python for .NET, can this serve my purpose? Any recommended tutorial? Calling Python script with StartProcessInfo class of C#. I can do it, but I feel that it is not the most elegant way to do so. Python rest API. However, there will be overhead on setting up server etc. Which should be the way to do that?
score: 0
answer count: 1
tagged with: .net
tagged with: python
type: UnansweredQuestion
has title: C# interface calling Python

http://stackoverflow.com/q/51148876
tagged with: python
score: 0
tagged with: tensorflow
has body: def Network(self): inputs = Input(shape=(512, 512, 1), batch_shape=None) conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs) conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool1) conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool2) conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool3) conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv4) drop4 = Dropout(0.5)(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(drop4) conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool4) conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5) drop5 = Dropout(0.5)(conv5) up6 = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')( UpSampling2D(size=(2, 2))(drop5)) merge6 = merge([drop4, up6], mode='concat', concat_axis=3) conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge6) conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6) up7 = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal')( UpSampling2D(size=(2, 2))(conv6)) merge7 = merge([conv3, up7], mode='concat', concat_axis=3) conv7 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge7) conv7 = Conv2D(256, 3, activation='relu', padding='same', k…
tagged with: image-segmentation
has title: Very poor dice coefficient in MIT road and building dataset using UNET
answer count: 0
type: UnansweredQuestion
tagged with: keras
has comment: http://stackoverflow.com/comment/89312826
type: Question
has comment: http://stackoverflow.com/comment/90352226
tagged with: machine-learning

http://stackoverflow.com/a/51050412
has comment: http://stackoverflow.com/comment/89091865
has comment: http://stackoverflow.com/comment/89092285
type: AcceptedAnswer
downvote count: 0
has body: There are a number of ways to do this. You have the right idea using a variable; you just need to figure out when to change it. An easy way is to assign "foo" to val before entering your loop, use it to assign your dictionary value, then change val to "bar" after it's been used. val = "foo" for items in soup.select("[name='JadeForm'] input"): if items.get("name").startswith('4194813'): item = items.get("name") formdata[item] = val val = "bar" Another way is to put the values into a list, make an iterator over the list, then use next() to get the next value from the iterator. This is a more general approach that can be used with any number of items, not just two. val = iter(["foo", "bar"]) for items in soup.select("[name='JadeForm'] input"): if items.get("name").startswith('4194813'): item = items.get("name") formdata[item] = next(val)
accepted answer of: http://stackoverflow.com/q/51050202
answers question: http://stackoverflow.com/q/51050202
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/89268845
type: QuestionComment
comment on: http://stackoverflow.com/q/51141674
score: 0
has text: @LaurentMazuel Thank you so much but I am exactly following the same step.
type: Comment

http://stackoverflow.com/q/51089374
has comment: http://stackoverflow.com/comment/89167886
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89167997
has body: I'm trying to build a simple app that concats 2 mp4 files. It works fine if I run it from the command line, but if I run it from py2app app it doesn't work. If I run the app from within the py2app in the console (eg 'dist/addTag.app/Contents/MacOS/addTag'), it works fine. It only doesn't work if i run the app by double clicking on it. Any ideas? code below #! /usr/bin/python import argparse import ffmpeg import os import shutil import sys from Tkinter import * import time fields = 'Input Video', 'Tag Video', 'Output Name' def fetch(entries, bu, lb, rt): bu['state'] = 'disabled' lb['text'] = 'working' rt.update() ffmpeg.concat(ffmpeg.input(entries[0][1].get()), ffmpeg.input(entries[1][1].get())).output(os.path.expanduser("~/desktop/")+entries[2][1].get()).run() bu['state'] = 'normal' lb['text'] = 'Ready' rt.update() def makeform(root, fields): entries = [] for field in fields: row = Frame(root) lab = Label(row, width=15, text=field, anchor='w') ent = Entry(row) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append((field, ent)) return entries if __name__ == '__main__': root = Tk() root.title("Video Maker") ents = makeform(root, fields) root.bind('&lt;Return&gt;', (lambda event, e=ents: fetch(e))) label = Label(root, text="Ready") label.pack(side=LEFT) b1 = Button(root, text='Make Video', command=(lambda e=ents: fetch(e, b1, label, root))) b1.pack(side=LEFT, padx=5, pady=5) b2 = Button(root, text='Quit', command=root.quit) b2.pack(side=LEFT, padx=5, pady=5) root.mainloop()
tagged with: tkinter
answer count: 0
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/89168058
has comment: http://stackoverflow.com/comment/89168171
tagged with: py2app
type: Question
has title: ffmpeg not working if run from py2app
has comment: http://stackoverflow.com/comment/89167715
score: 0

http://stackoverflow.com/comment/138729799
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51136806
type: Comment
has text: for more recent visitors to this q&a, pandas >= 2 has no attribute 'append' so won't work

http://stackoverflow.com/comment/89103393
type: Comment
has text: that's fantastic! I was toying with the idea of using dictionaries but I wasn't aware of NamedTuples which sounds like the way to go here. After looking into this datatype, it sounds like a perfect fit for what I'm trying to achieve. Thank you.
comment on: http://stackoverflow.com/a/51051536
type: AnswerComment
score: 0

http://stackoverflow.com/a/51168577
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/98203661
accepted answer of: http://stackoverflow.com/q/51163995
type: Answer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/51163995
has comment: http://stackoverflow.com/comment/98178790
has body: If you are trying to extract all of the values, then you would let BeautifulSoup return all of the items and Python can then filter the values you want. For example: from bs4 import BeautifulSoup html = """ Item1 Value1 Item2 Value2 Item3 Value3 Item4 Value4 """ soup = BeautifulSoup(html, "html.parser") div = soup.find("div", class_="box1") values = [] for tr in div.find_all('tr'): values.append(tr.find_all("td")[1].text) print(values) Giving you a list of values: ['Value1', 'Value2', 'Value3', 'Value4'] Or if you want a list of containing all of the data as columns: soup = BeautifulSoup(html, "html.parser") div = soup.find("div", class_="box1") columns = [] for tr in div.find_all('tr'): columns.append([td.text for td in tr.find_all("td")]) columns = list(zip(*columns)) print(columns) print(columns[1]) # display the 2nd column Giving you: [('Item1', 'Item2', 'Item3', 'Item4'), ('Value1', 'Value2', 'Value3', 'Value4')] ('Value1', 'Value2', 'Value3', 'Value4') list(zip(*columns)) is a way of transposing a list of rows into a list of columns.
has comment: http://stackoverflow.com/comment/98111236

http://stackoverflow.com/q/51011912
linked to: http://stackoverflow.com/q/24350509
upvote count: 3
has answer: http://stackoverflow.com/a/51012077
has body: I just started on python and since I started a new calculator project, pyCharm spits out none after everything. I'm not sure what's causing this error, I would appreciate it if I could get some help here. (This is just the main function that I'm showing) Here's the code: def main(): run = True while run == True: if run == False: break try: operation = input(print("Would you like to *, -, + or /?")) if operation != "+" and operation != "-" and operation != "/" and operation != "*": print("invalid input.") go = input(print("Would you like to continue, yes or no?")) if go == "no": run = False else: continue else: num1 = int(input(print("What's your first number?"))) num2 = int(input(print("What's your second number?"))) if operation == "*": print(multi(num1, num2)) if operation == "-": print(sub(num1, num2)) if operation == "+": print(add(num1, num2)) if operation == "/": print(div(num1, num2)) go = input(print("Would you like to make another calculation, yes or no?")) if go == "no": run = False else: continue except: print("invalid input.") go = input(print("Would you like to continue, yes or no?")) if go == "no": run = False else: continue An example of what happens: Would you like to *, -, + or /? None/ What's your first number? None3 What's your second number? None4 0.75 Would you like to make another calculation, yes or no? Noneno Process finished with exit code 0
has answer: http://stackoverflow.com/a/51011964
has comment: http://stackoverflow.com/comment/89016607
score: 2
has comment: http://stackoverflow.com/comment/89016600
has comment: http://stackoverflow.com/comment/89016574
possible better answer: http://stackoverflow.com/a/51011955
type: Question
accepted answer: http://stackoverflow.com/a/51012077
has answer: http://stackoverflow.com/a/51011955
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/114144101
favorite count: 0
has title: Beginner python "None" issue
answer count: 3
downvote count: 1

http://stackoverflow.com/a/51065511
downvote count: 0
answers question: http://stackoverflow.com/q/51064563
has body: I would just split on comma, then optionaly on hyphen, and just control that each hyphen separated range has no more than to integers. Following function returns a generator that returns a list of 1 or 2 integers per range after validating syntax: def parse(string): ranges = re.split(r'\s*,\s*', string.strip()) # split on comma ignoring spaces for i in ranges: limits = re.split(r'\s*-\s*', i) # optionaly splits on hyphen if len(limits) &gt; 2: # one max raise ValueError('More than one hyphen in a range ({})' .format(i)) if any([ re.match('[0-9]+', num) == None for num in limits ]): # only integers allowed raise ValueError('A page number is not an integer ({})' .format(num)) yield [ int(num) for num in limits ] This will happily ignore any space or tab, still ensuring correct syntax
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/51088581
answers question: http://stackoverflow.com/q/51088265
score: 1
has body: Ok, found the error. I was using httplib2 version 0.9. I upgraded via: pip3 install httplib2==0.11.3 After the upgrade, the issue was resolved.
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51088265
downvote count: 0

http://stackoverflow.com/comment/89206839
score: 4
type: Comment
type: QuestionComment
has text: Please show us some sample input and output.
comment on: http://stackoverflow.com/q/51109827

http://stackoverflow.com/q/51053088
tagged with: legend
tagged with: python
linked to: http://stackoverflow.com/q/18897261
has title: Add legend to barplot composed of numerous catogies
has body: This question is related to this one. After I plot the barplot with different colors, I would like to add a corresponding legend but I cannot figure out how. Is it even possible? df = pd.DataFrame({'index':np.arange(0,10,1),'values':np.random.randint(0,100,10), 'group':list('aaabbbcccd')}) colors = {'a':'red','b':'gold','c':'lightblue','d':'cyan'} df['values'].plot(kind='bar', color=[colors[i] for i in df['group']]) It doesn't seem possible in the present solution but I tried iterating over the groups(using groupby) and plotting them onto the same axis but the plots don't come out correctly. Any alternative suggestions?
type: Question
type: AnsweredQuestion
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/51053170
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51053170

http://stackoverflow.com/q/51146458
has title: BubbleSort with recursion in Python3 - Returning "None"
has comment: http://stackoverflow.com/comment/89276997
linked to: http://stackoverflow.com/q/19215141
has answer: http://stackoverflow.com/a/72976506
has comment: http://stackoverflow.com/comment/89277012
linked to: http://stackoverflow.com/q/17778372
downvote count: 0
has answer: http://stackoverflow.com/a/70843165
tagged with: bubble-sort
score: 1
linked to: http://stackoverflow.com/q/11205254
duplicate of: http://stackoverflow.com/q/17778372
type: Question
has answer: http://stackoverflow.com/a/51146466
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/129519514
answer count: 6
tagged with: python-3.x
has answer: http://stackoverflow.com/a/58910591
has answer: http://stackoverflow.com/a/66970947
upvote count: 1
tagged with: python
has body: I created a small function to do BubbleSort (just learning how to code) in Python 3 and I can't find the issue. Here is the code. It's returning "None" for some reason. Could someone please take a look? Thank you! arr = [1,5,2,7,3] def bubbleSort(array): count = 0 #print("array is currently",array) for idx in range(len(array)-1): if array[idx] &gt; array[idx + 1]: array[idx],array[idx + 1] = array[idx + 1],array[idx] count += 1 #print("swaped and count is currently",count) #print("array is currently",array) if count == 0: #print("Count is zero") #print("array is currently",array) return array else: #print("Count is not zero") bubbleSort(array) print(bubbleSort(arr))
has answer: http://stackoverflow.com/a/59170511
possible better answer: http://stackoverflow.com/a/66970947
accepted answer: http://stackoverflow.com/a/51146466

http://stackoverflow.com/comment/89209429
type: QuestionComment
comment on: http://stackoverflow.com/q/51091500
score: 0
has text: We keep all our largest files on a separate data drive, and I am having no trouble saving large pdfs (i.e. a scatterplot with 40000 points), so I don't think disk space is an issue
type: Comment

http://stackoverflow.com/q/51129984
answer count: 1
has answer: http://stackoverflow.com/a/51130227
has body: I have the following code to open files, where I want show the path of the file as a Label. import Tkinter, Tkconstants, tkFileDialog top = Tkinter.Tk() top.resizable(width=False, height=False) top.geometry("700x300+350+200") def OpenOldFile(): top.filename = tkFileDialog.askopenfilename(initialdir = "/",title="Select old file") lb2 = Tkinter.Label(text="Old File:").grid(row=2,column=1, sticky='w') lb3 = Tkinter.Label(text=top.filename).grid(row=2,column=2, sticky='w') def OpenNewFile(): top.filename = tkFileDialog.askopenfilename(initialdir = "/",title="Select New file") lb2 = Tkinter.Label(text="New File:").grid(row=6,column=1, sticky='w') lb3 = Tkinter.Label(text=top.filename).grid(row=6,column=2, sticky='w') lb1 = Tkinter.Label(text= "Select Old file:").grid(row=1,column=1, sticky='w') B1 = Tkinter.Button(text = "Click to open file", command = OpenOldFile).grid(row=1,column=2, sticky='w') lb4 = Tkinter.Label(text="Select New File:").grid(row=4,column=1, sticky='w') B2 = Tkinter.Button(text="Click to open file", command = OpenNewFile).grid(row=4,column=2, sticky='w') top.mainloop() Problem: When I click Button B1 multiple times to open the different files, the text of Label lb3 is overwriting on the previous text as shown below in the screenshots. When I click first time: Second click:
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/51130227
score: 0
has title: Update text of label in Tkinter
type: Question
tagged with: python-2.7

http://stackoverflow.com/a/51041233
answers question: http://stackoverflow.com/q/51041094
has body: You cannot build this kind of structure because python does not allow this. Just type this in your terminal you'll get idea about structure error { "dashboard": {"bounces": "10", "userType": "New Visitor", "users": "15"}, {"bounces": "12", "userType": "Returning Visitor", "users": "3"} }
type: Answer
has comment: http://stackoverflow.com/comment/89097702
score: 0

http://stackoverflow.com/q/51145100
downvote count: 0
answer count: 1
favorite count: 0
has body: I'm trying to scrape Momondo. I'm interested in the price that can be found here 182 USD I'm scraping with the following code from bs4 import BeautifulSoup import urllib.request url = 'https://www.momondo.com/flight-search/PAR-BER/2018-07-22?sort=price_a' response = urllib.request.urlopen(url) html = response.read() print(html) soup = BeautifulSoup(html,'html5lib') all = soup.find_all('div',class_='price-price') for item in all: print(item.text) Response and hence html do not contain a class 'price-price'. Can you point me to my error?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89826085
tagged with: python
has title: BS4 returns HTML missing elements
score: 1
tagged with: web-scraping
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51424839

http://stackoverflow.com/q/51024719
type: UnansweredQuestion
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/51025603
has answer: http://stackoverflow.com/a/51027426
has comment: http://stackoverflow.com/comment/89045815
type: Question
has body: I have a html page with text box and submit button. When somebody enters data in text box and click submit, i have to pass that value to a python script which does some operation and print output. Can someone let me now how to achieve this. I did some research on stackoverflow/google but nothing conclusive. I have python 2.7, Windows 10 and Apache tomcat. Any help would be greatly appreciated. Thanks, Jagadeesh.K
has title: Passing command line parameters to python script from html page
score: 0
answer count: 2
upvote count: 1
tagged with: apache
downvote count: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/89043436

http://stackoverflow.com/comment/89122866
score: 0
type: Comment
has text: That seemed to work! Now i'm a little confused about how to do predictions/log outcomes then, as I had to remove the "classes: and "probabilities" as you mentioned for it to run, as well as all logging. Is there a tensor to add back in for logging? I suppose previously it displayed some confidence in each classification option, this doesn't exist anymore (a confidence value) does it? Rather, I just get a scalar output?
comment on: http://stackoverflow.com/a/51066076
type: AnswerComment

http://stackoverflow.com/comment/89162010
type: AnswerComment
comment on: http://stackoverflow.com/a/51078835
type: Comment
has text: Nope. Used r to get rid of the Unicode error and still causes an issue.
score: 0

http://stackoverflow.com/comment/89227170
comment on: http://stackoverflow.com/a/51112570
score: 0
type: AnswerComment
type: Comment
has text: I really dont think I understand your comment. What changed to what..? Can you re-read your comment

http://stackoverflow.com/q/51160487
tagged with: cx-oracle
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51171287
favorite count: 0
tagged with: python
tagged with: debian
has title: reflecting a database table in cx_Oracle / sqlalchemy
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51171287
upvote count: 1
tagged with: sqlalchemy
type: Question
has body: I'm trying to connect to a database from python, running in a debian based docker container. I extracted the bit of code that's causing the failure: import sqlalchemy from db_tools import generate_sandbox_connection con = generate_sandbox_connection('churn', 'PASSWORD') metadata = sqlalchemy.MetaData() report_lookup = sqlalchemy.Table('REPORT_LOOKUP', metadata, schema = 'SCHEMA', autoload = True, autoload_with = con) This causes the following output: Traceback (most recent call last): File "sqlalchemytest.py", line 43, in &lt;module&gt; autoload_with = sandb_con) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 457, in __new__ metadata._remove_table(name, schema) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 452, in __new__ table._init(name, metadata, *args, **kw) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 534, in _init include_columns, _extend_on=_extend_on) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/schema.py", line 547, in _autoload _extend_on=_extend_on File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2056, in run_callable ... reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context context) File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 509, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (cx_Oracle.ProgrammingError) positional and named binds cannot be intermixed [SQL: u'SELECT table_name, compression, compress_for FROM ALL_TABLES WHERE table_name = :table_name AND owner = :owner '] [parameters: {'owner': u'TRIP', 'table_name': u'CHURN_REPORT_LOOKUP'}] (Background on this error at: http://sqlalche.me/e/f405) …
tagged with: docker

http://stackoverflow.com/q/51111216
type: Question
has comment: http://stackoverflow.com/comment/89213044
answer count: 2
tagged with: spyder
downvote count: 0
has answer: http://stackoverflow.com/a/56243141
has comment: http://stackoverflow.com/comment/89210177
favorite count: 0
has comment: http://stackoverflow.com/comment/89216976
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89212823
tagged with: python
has answer: http://stackoverflow.com/a/57907568
score: 3
tagged with: pycharm
upvote count: 3
has comment: http://stackoverflow.com/comment/89210170
has title: compatibility error in pycharm using plt.show()
tagged with: matplotlib
has body: I want to plot the pca components graph according to the following code in pycharm. import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, decomposition, datasets from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV logistic = linear_model.LogisticRegression() pca = decomposition.PCA() pipe = Pipeline(steps = [('pca',pca), ('logistic', logistic)]) digits = datasets.load_digits() x_digits = digits.data y_digits = digits.target # plot pca spectrum pca.fit(x_digits) plt.figure(1, figsize=(4,3)) # clear the current figure plt.clf() # add axes plt.axes([.2,.2,.7,.7]) plt.plot(pca.explained_variance_, linewidth = 2) plt.xlabel('n_components') plt.ylabel('explained_variance_') # prediction n_comp = [20, 40, 64] # logspace default is base 10, this is 10^-4 to 10^4 cs = np.logspace(-4, 4, 3) # parameters of pipelines can be set using '__' separated parameter names: estimator = GridSearchCV(pipe, dict(pca__n_components = n_comp, logistic__C = cs)) estimator.fit(x_digits, y_digits) plt.axvline(estimator.best_estimator_.named_steps['pca'].n_components, linestyle = ':',label = 'n_compoenents chosen') plt.legend(prop = dict(size = 12)) plt.axis('tight') plt.show() However I got a error message as : UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.warnings.warn("This figure includes Axes that are not " and File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 25, in __call__ manager.show(**kwargs) File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 107, in show self.canvas.show() File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 62, in show self.figure.tight_layout() File "C:\Users\User\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1752, in tight_layout rect=rect) F…

http://stackoverflow.com/comment/89216467
type: QuestionComment
has text: @0709_ I am trying with BeautifulSoup4.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51115004

http://stackoverflow.com/a/51056922
score: 0
answers question: http://stackoverflow.com/q/51056542
type: Answer
has body: As far I can understand you have the list of links and make requests concurrently to make the process faster. Here is the sample code for multithreading. I hope this will help you. Read the documentation for concurrent futures. import concurrent.futures import urllib.request URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/'] # Retrieve a single page and report the URL and contents def load_url(url, timeout): with urllib.request.urlopen(url, timeout=timeout) as conn: return conn.read() # We can use a with statement to ensure threads are cleaned up promptly with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: # Start the load operations and mark each future with its URL future_to_url = {executor.submit(load_url, url, 60): url for url in URLS} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (url, exc)) else: print('%r page is %d bytes' % (url, len(data)))

http://stackoverflow.com/comment/136026677
type: Comment
has text: Should this code be executed after using `df.to_excel()`? If yes, could you please give a complete code example with using `df.to_excel()`, changing `number_format` and then saving the workbook?
comment on: http://stackoverflow.com/a/51251105
type: AnswerComment
score: 0

http://stackoverflow.com/a/51102450
has body: The reason it throws this error is because you are binding to an unknown address hence the error. To bind the socket to your IP, do: socket.gethostbyname(socket.gethostname()) in the place of the address. socket.gethostname() gets the hostname of the computer e.g. DANS_PC socket.gethostbyname() looks up the IP of the hostname that is given in the parameters. To make the server public however, do the same but port forward your computers IP address in your router settings.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51081741
answers question: http://stackoverflow.com/q/51081741
type: AcceptedAnswer

http://stackoverflow.com/q/51024446
downvote count: 0
answer count: 1
has title: Cannot add scalar and a vector error in VPyhton (GlowScript)
favorite count: 0
tagged with: physics
has answer: http://stackoverflow.com/a/51027589
tagged with: python
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51027589
score: 1
tagged with: glowscript
has body: I'm implementing a solar system with VPython in GlowScript. Now I have received this error when running: Error cannot add scalar and a vector. I think I've done all correctly. Do I have to change something with the pos. ? Here is the code: GlowScript 2.7 VPython from visual import * scene = display(width = 800, height = 800, center = vec(0,0.5,0)) #sun sonne = sphere(pos = vec (0,0,0), radius=8, color = color.orange, shininess=1) #earth erde = sphere(pos = vec (50,0,0), radius=1.5, color = color.blue, make_trail=True) erdeV = vector(0,0,5) #masses erdeM = 5.97*10**24 sonneM = 1.989*10**30 #Grav-constant G = 6.67259*10**-11 for i in range (1000): rate(1000) erde.pos = erde.pos + erdeV #distance entfernung = sqrt(erde.pos.y**2 + erde.pos.z**2) #Gravitational law F = G * m * M / r*r --&gt; G*s*e/AE*AE ae=Astr. Einheit Fgrav = G *( erdeM * sonneM) / (entfernung*entfernung) erdeV = erdeV + Fgrav erde.pos += erdeV if entfernung &lt;= sonne.radius: break
type: Question
tagged with: vpython

http://stackoverflow.com/q/51018143
has answer: http://stackoverflow.com/a/51037513
type: Question
has answer: http://stackoverflow.com/a/57996955
has answer: http://stackoverflow.com/a/68582511
upvote count: 1
linked to: http://stackoverflow.com/q/47788247
has answer: http://stackoverflow.com/a/56252402
favorite count: 0
has body: I am trying to run the TensorFlow Object Detection API. It works when I use it on my webcam with that line : cap = cv2.VideoCapture(0) But when I try to do it on a video with that line : cap = cv2.VideoCapture('kev.mp4') I end up having that error: Traceback (most recent call last): File "C:\Users\leahj\Documents\models-master\research\object_detection\object_detection_tutorial_cam.py", line 147, in &lt;module&gt; feed_dict={image_tensor: image_np_expanded}) File "C:\Users\leahj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 900, in run run_metadata_ptr) File "C:\Users\leahj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1104, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "C:\Users\leahj\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\numeric.py", line 492, in asarray return array(a, dtype, copy=False, order=order) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Both the video and the code are in this folder: C:\Users\leahj\Documents\models-master\research\object_detection Any ideas ?
has answer: http://stackoverflow.com/a/51027349
answer count: 5
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
has title: Run TensorFlow Object Detection API on video
downvote count: 0
score: 1

http://stackoverflow.com/a/51032946
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/51032601
type: Answer
accepted answer of: http://stackoverflow.com/q/51032601
upvote count: 7
has body: I would expect that you'd want to normalize the values for a given feature, across the samples. If you normalize a given sample's data across its features, you've tossed out a lot of information. That would be for comparing features (which rarely makes sense), rather than for comparing samples for a feature. I don't know numpy or sklearn so take this with a grain of salt, but when normalizing, you want to normalize (using the same parameters) all data for a given feature, to bring all the values for that feature into the range of (-1 ... +1), with the mean as zero (or something like that). You'd do this separately for each feature, so they'll all end up in that range, with each feature's mean at zero. Consider an example, if you normalized across all the features for a given sample. height weight age person1 180 65 50 person2 140 45 50 If we normalize the values for person1 across the features, then do the same for person2, then person2 will seem to have a different age than person1! If we normalize across the samples for a given column, then the relationships will still hold. Their ages will match; person1 will be taller, and person2 will weigh less. But all values for all features will fit within the distribution rules necessary for subsequent analysis.
type: AcceptedAnswer

http://stackoverflow.com/comment/89239490
has text: i get this result with the shell AttributeError: 'NoneType' object has no attribute 'xpath' and if i see the view i can see the website withour problems
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51127160

http://stackoverflow.com/comment/89085661
score: 1
has text: @Cibic - hmm, some idea `mask = df.select_dtypes(include=[object]).applymap(lambda x: 'ball' in str(x).lower() if pd.notnull(x) else False)` or `mask = df.select_dtypes(include=[object]).apply(lambda x: x.str.contains('ball', na=False, regex=False, case=False))`
comment on: http://stackoverflow.com/a/51045259
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51068716
has comment: http://stackoverflow.com/comment/89127422
answer count: 3
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51068840
tagged with: list
has answer: http://stackoverflow.com/a/51068841
has comment: http://stackoverflow.com/comment/89127254
downvote count: 2
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51068841
type: AnsweredQuestion
has body: I have a list of dictionaries, in very documents I want to keep only words which are in group of 3( for ex 'done auto manufacturing') and after filtering I wan to keep top 2 grams which based on values and if values are same then top two keys in the dictonary. b=[{'america': 0.10640008943905088, 'delete option snapshot': 0.18889748775492732, 'done': 0.10918437741476256, 'done auto manufacturing': 0.18889748775492732, 'done auto delete': 0.18889748775492732, 'overwhelmed': 0.1714953267142263, 'overwhelmed sub': 0.18889748775492732, 'overwhelmed sub value': 0.18889748775492732}, {'delete': 0.17737631178689198, 'delete invalid': 0.2918855502796403, 'delete invalid data': 0.2918855502796403, 'invalid': 0.19409701271823834, 'invalid data': 0.2918855502796403, 'invalid data sir': 0.2918855502796403, 'nas': 0.14949544719217545, 'nas server': 0.1632884084021329, 'nas server replic': 0.2799865687396422}] output: b=[{'delete option snapshot': 0.18889748775492732, 'done auto manufacturing': 0.18889748775492732, 'done auto delete': 0.18889748775492732, 'overwhelmed sub value': 0.18889748775492732}, {'delete invalid data': 0.2918855502796403, 'invalid data sir': 0.2918855502796403}] My solution: This doesn't seem right. for i in range(1, len(b)+1): for k,v in i.items(): if len(re.findall(r'\w+',k[i])&lt;3: del b[k]
has answer: http://stackoverflow.com/a/51068843
score: -1
accepted answer: http://stackoverflow.com/a/51068840
has comment: http://stackoverflow.com/comment/89127365
has comment: http://stackoverflow.com/comment/89127393
has comment: http://stackoverflow.com/comment/89127352
has title: Delete keys from dictionary based on condition in python
favorite count: 0

http://stackoverflow.com/comment/89215622
comment on: http://stackoverflow.com/q/51114638
type: Comment
score: 3
has text: please, indent your code correctly. It is actually unreadable.
type: QuestionComment

http://stackoverflow.com/q/51111046
upvote count: 1
type: Question
has body: I'm attempting to run flask migrate db in my working directory, and it does not use the model I defined in models.py Here's the code. models.py import sys sys.path.append("../") from Talks2 import db class Talk(db.Model): presenter = db.Column(db.Text()) talkType = db.Column(db.Text()) desc = db.Column(db.Text(), primary_key=True) link = db.Column(db.Text()) time = db.Column(db.Integer()) def __repr__(self): return "Presenter: {}\nType: {}\nDescription:\n{}\nLink: {}".format(self.presenter,self.talkType,self.desc,self.link) routes.py import sys sys.path.append("../") from flask import Flask, request, render_template from Talks2 import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app,db) from Talks2 import models @app.route("/") def index(): return render_template("index.html") @app.route("/add", methods=["POST"]) def add(): person = request.form["presenter"] ttype = request.form["type"] desc = request.form["desc"] link = request.form["link"] print(person, file=sys.stderr) print(ttype, file=sys.stderr) print(desc, file=sys.stderr) print(link, file=sys.stderr) return render_template("index.html") if __name__ == "__main__": app.run() What do I need to change for it to correctly generate the script?
tagged with: flask
has title: Flask migrate doesn't detect models.py
tagged with: alembic
tagged with: sqlite
answer count: 1
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89210422
tagged with: python
has answer: http://stackoverflow.com/a/51242403
score: 1

http://stackoverflow.com/a/51109971
has comment: http://stackoverflow.com/comment/89518485
answers question: http://stackoverflow.com/q/51109735
has comment: http://stackoverflow.com/comment/90083393
type: AcceptedAnswer
has body: Update 2018-08-15 pyodbc 4.0.24, released today, now includes Python 3.7 wheels for installing on Windows and Mac via pip. (original answer) pyodbc wheel files for Python 3.7 are not yet available on PyPI. They have been requested via the GitHub issue here. You could always revert to Python 3.6 for the time being. Or, if you really need Python 3.7 right now then you'll have to install the required Visual Studio components so pip can build pyodbc from source. Details here. I then I ran command pip install pyodbc but it give an error saying, "Microsoft Visual C++ 14.0 is required". I installed "Microsoft Visual C++ 2015 Redistributable" to accommodate this That didn't work because you installed the runtime support for Visual C++. You need the build tools for Visual C++, described here.
type: Answer
score: 6
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51109735
downvote count: 1

http://stackoverflow.com/q/51014511
upvote count: 0
possible better answer: http://stackoverflow.com/a/51025011
has answer: http://stackoverflow.com/a/51025011
favorite count: 0
has body: After declaring a variable in parse function as "self.Title" and yielding the data through another function, it is returning the data of only one URL across all others.What can be going wrong. Here is the code snippet. import scrapy from scrapy.http import Request class TestSpider(scrapy.Spider): name = 'Test' allowed_domains = ['example.com'] start_urls = ['https://example.com/search?q=com.foo', 'https://example.com/search?q=bar', 'https://example.com/search?q=data'] def parse(self, response): self.Title = response.xpath('//*[@class="search-title"]/a/text()')[0].extract() Ini_Url = response.xpath('//*[@class="search-title"]/a/@href')[0].extract() Ab_url = "https://example.com" + Ini_Url + "/download?from=details" yield Request(Ab_url, callback=self.parse_download) def parse_download(self, response): Download_URL = response.xpath('//*[@class="fdownload-box"]/p[2]/a/@href')[0].extract() yield{"Download_URL": Download_URL, "Title": self.Title} And the output is coming like Download_URL are different for all 3 scraped URLs but Title although different are coming same for all 3 request.
has title: Python-Scrapy : Yielding a Variable name defined in one function through Another
tagged with: python
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51014626
tagged with: scrapy
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51014626
answer count: 2

http://stackoverflow.com/q/51111743
tagged with: python-3.6
answer count: 1
has answer: http://stackoverflow.com/a/51111913
type: UnansweredQuestion
has body: I'm trying to figure out how to change the last found target value in a linked list to the replacement value. For example if you had a linked list such as; [1,'next'],[2,'next'],[3,next'],[2,none] How would I replace only the last 2, rather than all of them, or the first one? This is the code that I currently have; walker = node_chain if node_chain is None: return None elif walker['data'] == target_val and walker['next'] is None: walker = node.set_data(walker, replacement_val) return walker else: while walker['next'] is not None: if walker['data'] == target_val: node_chain = node.set_data(walker, replacement_val) return node_chain walker = node.get_next(walker) if walker['next'] is None and walker['data'] == target_val: walker = node.set_data(walker, replacement_val) return walker So in the given code, if the target value was 2, and the replacement value was 4, it would return [1,'next'],[4,'next'],[3,next'],[2,none] rather than what I want to be returned; [1,'next'],[2,'next'],[3,next'],[4,none] Thank you in advanced.
tagged with: python
has comment: http://stackoverflow.com/comment/89210602
score: 0
type: Question
has title: Changing the last found target value in a linked list (node chain)

http://stackoverflow.com/q/51136862
has comment: http://stackoverflow.com/comment/89260691
has body: I have a dict with "metadata" for my dataset, of sort {'m1': array_1, 'm2': array_2, ...}. Each of the arrays has shape (N, ...), where N is the number of samples. The question: Is it possible to create a tf.data.Dataset that outputs a dictionary {'meta_1': sub_array_1, 'meta_2': sub_array_2, ...} for each iteration of the datasets iterator.get_next()? Here, sub_array_i should contain the ith metadata for one batch, so should have shape (batch_sz, ...). What I tried so far is using tf.data.Dataset.from_generator(), like this: N = 100 # dictionary of arrays: metadata = {'m1': np.zeros(shape=(N,2)), 'm2': np.ones(shape=(N,3,5))} num_samples = N def meta_dict_gen(): for i in range(num_samples): ls = {} for key, val in metadata.items(): ls[key] = val[i] yield ls dataset = tf.data.Dataset.from_generator(meta_dict_gen, output_types=(dict)) The problem with this seems to be in output_types=(dict). The code above throws at me a TypeError: Expected DataType for argument 'Tout' not &lt; class 'dict'>. I'm using tensorflow 1.8 and python 3.6.
has comment: http://stackoverflow.com/comment/89259331
accepted answer: http://stackoverflow.com/a/51138337
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89260286
upvote count: 9
has comment: http://stackoverflow.com/comment/89261207
score: 9
has comment: http://stackoverflow.com/comment/89260147
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51138337
tagged with: tensorflow-datasets
favorite count: 0
tagged with: python
tagged with: dictionary
has title: Creating a tensorflow dataset that outputs a dict
type: AnsweredQuestion

http://stackoverflow.com/q/51049819
answer count: 3
has answer: http://stackoverflow.com/a/51049882
has comment: http://stackoverflow.com/comment/89090803
linked to: http://stackoverflow.com/q/1016814
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
has answer: http://stackoverflow.com/a/51049853
has title: Getting Indentation error while executing try block
downvote count: 5
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/89090630
tagged with: python-2.7
type: Question
tagged with: pandas
score: -5
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89090830
has answer: http://stackoverflow.com/a/51054030
has body: I am getting an Indentation error,while executing below code. import pyodbc import shutil import pandas as pd import numpy as np def My_function(): data = pd.read_excel(r'my excel path') dataincsv = data.to_csv(r'export into my csv path',sep=r'|') cnxn = pyodbc.connect('''connection string''') stmt1 = """Select column 1 from mytable""" try: Out_service = pd.read_sql(stmt1,cnxn) except: print("File format might be wrong,check the error") else: print(Out_service) exit() Getting below error when i run the code line 14 try: ^ IndentationError: unexpected indent
has comment: http://stackoverflow.com/comment/89090984

http://stackoverflow.com/comment/89274842
type: QuestionComment
has text: ah ha. i think its likely because you created the db object in multiple places. you’ll be better off using the approach to instantiating flask extensions project/__init__.py than in the manage.py.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51145234

http://stackoverflow.com/comment/89243490
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51126907
type: AnswerComment
has text: I mean I added the same function both auto and without and changed NextButton to FinishButton and it still highlights the finish button..

http://stackoverflow.com/comment/89275360
has text: No... This could not work
comment on: http://stackoverflow.com/q/51136268
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51027198
accepted answer of: http://stackoverflow.com/q/51025073
has comment: http://stackoverflow.com/comment/89065683
has comment: http://stackoverflow.com/comment/89065466
has body: Here update_student_ids will be a set of records. so you should replace update_student_ids with rec in for loop. eg: for rec in update_student_ids: partner = rec.partner_id.id ...
answers question: http://stackoverflow.com/q/51025073
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89375561
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51164251
has text: Or, if compiling freetype and libpng becomes a bit hairy, use the [unofficial binaries from Christoph Gohlke](https://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib) to install via wheel.
type: AnswerComment

http://stackoverflow.com/comment/89089427
comment on: http://stackoverflow.com/q/51049062
type: Comment
has text: updated my question hope it help
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89437998
score: 1
comment on: http://stackoverflow.com/q/51123537
type: Comment
type: QuestionComment
has text: This issue is fixed in the next Python minor release!

http://stackoverflow.com/a/54704579
answers question: http://stackoverflow.com/q/51091543
type: Answer
has body: You might just lack a windowinto function. Apache beam's docs state that for a streaming pipeline you are required to set either a non default window or a non default trigger. As you have not defined a window, you have one global window and it might thus wait endlessly on the end of the window before going to the sink.
score: 0

http://stackoverflow.com/comment/89090967
has text: @nosklo thanks that's what I thought, and yet the problem remains... I added above the actual code snippet from my program and the output from Python...
type: Comment
comment on: http://stackoverflow.com/a/51049886
score: 0
type: AnswerComment

http://stackoverflow.com/q/51053725
type: Question
has title: How Tkinter could load png images with transparent backgrounds?
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51055002
tagged with: tkinter
type: UnansweredQuestion
score: -3
tagged with: python
has body: Some weeks ago i load a png image into my Tkinter Canvas and drawed with create_image, but now i can't do this anymore, i tried convert with ImageTk but png did not display I have the following code: load = Image.open("mouse.png") self.img = ImageTk.PhotoImage(load) self.draw.create_image(100,100,image=self.img,anchor = NW) self.draw.image = self.img I just need to present a png image
has comment: http://stackoverflow.com/comment/89098473
tagged with: python-imaging-library
downvote count: 3

http://stackoverflow.com/a/51215244
type: Answer
has body: My problem was happening because after the Zeppelin container started, it was already too late. Zeppelin service was up and running and it would have already loaded interpreter.json. So, what I did was to configure my Dockerfile ENTRYPOINT to a script of mine, overwriting the standard Zeppelin container's entry point. My script would do the injection of the additional configurations I needed on interpreter.json file and call /zeppelin/bin/zeppelin.sh to start zeppelin. This way, I could do whatever I want with the configuration files BEFORE Zeppelin was actually started inside the container. Kind regards, AS
answers question: http://stackoverflow.com/q/51055457
score: 0
has comment: http://stackoverflow.com/comment/94682623

http://stackoverflow.com/a/51097616
has comment: http://stackoverflow.com/comment/89182989
downvote count: 0
has comment: http://stackoverflow.com/comment/89183292
has body: Replace the commas with + i.e. newli = content[0] + '\t' + content[1]
type: Answer
has comment: http://stackoverflow.com/comment/89183056
score: 2
has comment: http://stackoverflow.com/comment/89182900
upvote count: 2
answers question: http://stackoverflow.com/q/51097545

http://stackoverflow.com/comment/89180006
has text: Yes Jez. It works. Thanks for the help. Now if I want to assign the match number for each match, Can i use cumcount based on Model? i will give a try
score: 0
comment on: http://stackoverflow.com/a/51096122
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51072205
tagged with: pandas
has title: Adding empty dataframe rows based on missing datetime values
tagged with: datetime
tagged with: python
has body: I am trying to add rows to my pandas dataframe as such: import pandas as pd import datetime as dt d={'datetime':[dt.datetime(2018,3,1,0,0),dt.datetime(2018,3,1,0,10),dt.datetime(2018,3,1,0,40)], 'value':[4.,5.,1.]} df=pd.DataFrame(d) Which outputs: datetime value 0 2018-03-01 00:00:00 4.0 1 2018-03-01 00:10:00 5.0 2 2018-03-01 00:40:00 1.0 What I want to do is add rows from 00:00:00 to 00:40:00, to show every 5 minutes. My desired output looks like this: datetime value 0 2018-03-01 00:00:00 4.0 1 2018-03-01 00:05:00 NaN 2 2018-03-01 00:10:00 5.0 3 2018-03-01 00:15:00 NaN 4 2018-03-01 00:20:00 NaN 5 2018-03-01 00:25:00 NaN 6 2018-03-01 00:30:00 NaN 7 2018-03-01 00:35:00 NaN 8 2018-03-01 00:40:00 1.0 How do I get there?
accepted answer: http://stackoverflow.com/a/51072417
tagged with: indexing
type: AnsweredQuestion
tagged with: dataframe
type: Question
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51072488
has answer: http://stackoverflow.com/a/51072488
has answer: http://stackoverflow.com/a/51072417

http://stackoverflow.com/q/51042752
has answer: http://stackoverflow.com/a/51042974
score: 0
accepted answer: http://stackoverflow.com/a/51042864
answer count: 3
has title: list remove() troubles
has comment: http://stackoverflow.com/comment/89077478
has answer: http://stackoverflow.com/a/51042864
has body: Remove() isn't working properly for me in this case where I am trying to remove elements from my list that do not contain a colon. Here is my list; myList = ['hosts:127.0.0.1','-nU','-nT','-cA','-nB'] Doing separated = myList.split(',') and then for i in separated: if ':' not in i: separated.remove(i) print separated leaves me with ['hosts:127.0.0.1', '-nT', '-nB'] as my output. I'm assuming this is because remove() only removes the first matching element. That still doesn't explain why -nt and -nb would be there though. What would a good alternative be to doing this? Thanks
possible better answer: http://stackoverflow.com/a/51042893
tagged with: python
type: AnsweredQuestion
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/51042893

http://stackoverflow.com/comment/89278329
comment on: http://stackoverflow.com/q/51144970
has text: See recent SO https://stackoverflow.com/q/51122046/901925
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51133566
has body: There are many ways to do this. Here is the simplest way i can think of for you. CI/CD don't use git as code delivery infrastructure. run a private pip repository and create versioned pip packages every time you want to release new code - will have you also to get controll of what features are being released.. Use Jenkins to automate the process When you what to deploy new code all you do is pip install -U my_app=1.2.3 on the server, and then just restarting the app. To not interrupt a process, also few options.. here is one: run your code as a service (systemd, systemv, upstart). after you install your code (with pip hopefully), you can use the following commandservice my_app restart in your app add some code to listen to SIGTERM eg: import signal def handler_stop_signals(*args, **kwargs): """ Handle system signals only SIGTERM expected to trigger this""" logger.info('Shutting down gracefully ') # wait for all tasks to finish before exiting signal.signal(signal.SIGTERM, handler_stop_signals) Every time you restart your app, this handler will be calledback and execute the logic you will write to gracefully shut down. tldr: Use Jenkins to release pip packages of your code. Use Jenkins to deploy your pip packages to the target server. Adjust your code to listen to system signals and act accordingly ps: more advanced solution could be (linux only solution) is to package your code into debian packages and ship them. you can use tools like debpackager to achieve that
accepted answer of: http://stackoverflow.com/q/51127635
has comment: http://stackoverflow.com/comment/89275944
answers question: http://stackoverflow.com/q/51127635
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89321788
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89282640
type: Answer

http://stackoverflow.com/comment/89216126
type: AnswerComment
has text: Did this answer your question? If so, I'd be thankful if you'd [accept](https://stackoverflow.com/help/someone-answers) the answer.
type: Comment
comment on: http://stackoverflow.com/a/51068293
score: 0

http://stackoverflow.com/comment/89104516
type: QuestionComment
comment on: http://stackoverflow.com/q/51056746
has text: please check your script work like @JorgePeris said
score: 0
type: Comment

http://stackoverflow.com/comment/92384885
score: 1
has text: @RYN Just came out from the trip and going to another one - will take a jab at it this weekend
type: Comment
comment on: http://stackoverflow.com/q/51071212
type: QuestionComment

http://stackoverflow.com/q/51101479
downvote count: 0
has body: I want to store data by an iterative way. how could I add some new keys in an pickle that contain already a dict ?? For example with open(filename_directory, 'wb') as f: pickle.dump({"a" : 1, "b":2 }, f) new_dict_ = {} for i in range(10): new_dict_ [i] = i with open(filename_directory, 'a') as f: pickle.dump( update_dict_with_my( new_dict_ ) , f)
answer count: 1
has title: Add a new key in a pickle file
favorite count: 0
has answer: http://stackoverflow.com/a/51101546
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89190079
tagged with: pickle
tagged with: python
tagged with: dictionary
score: 3
upvote count: 3
type: Question

http://stackoverflow.com/a/51070827
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89131618
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51070661
answers question: http://stackoverflow.com/q/51070661
type: Answer
has body: I don't know your purpose but can do something like below print('x', end='\t') row = 1 while (row &lt; 13): print(row, end='\t') row += 1 row = 1 while (row &lt; 13): print('') print() print() print(row, end='\t') col = 1 while( col &lt; 13): print(row*col, end='\t') col += 1 row += 1
has comment: http://stackoverflow.com/comment/89131666
has comment: http://stackoverflow.com/comment/89132293

http://stackoverflow.com/a/51150469
has body: If I am correct in assuming that this is the heart disease dataset taken from this UCI repository and the csv file is this one, then in that case these are correct values for binarizer. The original data column that you are using has a 0 in the final row, I think you missed that, try this code for idx in range(0,len(x)): print idx,x[idx],transform_binarize[idx] Output 278 [1L] [1.] 279 [0L] [0.] 280 [2L] [1.] 281 [0L] [0.] 282 [3L] [1.] 283 [0L] [0.] 284 [2L] [1.] 285 [4L] [1.] 286 [2L] [1.] 287 [0L] [0.] 288 [0L] [0.] 289 [0L] [0.] 290 [1L] [1.] 291 [0L] [0.] 292 [2L] [1.] 293 [2L] [1.] 294 [1L] [1.] 295 [0L] [0.] 296 [3L] [1.] 297 [1L] [1.] 298 [1L] [1.] 299 [2L] [1.] 300 [3L] [1.] 301 [1L] [1.] 302 [0L] [0.] #&lt;--- I think you missed this row while reading your dataset If you try this code then you will that the binarizer is working exactly as it should be.
has comment: http://stackoverflow.com/comment/89295082
downvote count: 2
type: AcceptedAnswer
score: -1
upvote count: 1
answers question: http://stackoverflow.com/q/51148326
accepted answer of: http://stackoverflow.com/q/51148326
type: Answer

http://stackoverflow.com/q/51119306
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22449524
linked to: http://stackoverflow.com/q/2263356
has answer: http://stackoverflow.com/a/51119385
type: Question
tagged with: python-venv
has title: Is it necessary to delete pyc files when upgrading Python **within** a major release?
tagged with: pyc
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51119385
has comment: http://stackoverflow.com/comment/89224473
has body: TL;DR If you switch back-and-forth between 3.6.6 and 3.7.0 before you adopt 3.7.0, there is no concern, the two sets of pyc files will cohabit and you'll be ok. What if you switch back-and-forth between 3.6.4 and 3.6.6? Do you need to delete pyc files? Long version I see that the pyc files are specific for major releases only. For example I have: __init__.cpython-36.pyc __init__.cpython-37.pyc which is presumably the result of PEP 3147. And so it's clear enough. If I move back-and-forth during development between virtual environments in, say, 3.6.6 and 3.7.0, there is no concern. The two versions will cohabit in the __pycache__ directory because they are identified by the major version number. Question: What about switching back-and-forth between, say, 3.6.4 and 3.6.6, do I indeed need to delete pyc files when switching from one version and another within the same major release? Motivation for the question The reason that I needed to switch virtual environments is that I thought that my code runs fine with some versions of Python 3, but not others. I was getting a multitude of ImportError: No module named XYZ errors. But when I wipe out all pyc files and install one version of Python or another, set up a virtual environment ~/venv-362 ~/venv-364 ~/venv-366 ~/venv-370 then all is well and the code runs fine.
linked to: http://stackoverflow.com/q/38809686

http://stackoverflow.com/comment/89301233
has text: There was a SytaxError on `df.loc[cond1 & cond2 & cond3 & cond4, 'remarks'] = 'Duplicate svc_no'~`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51158653
type: Comment

http://stackoverflow.com/a/51072087
has body: So you only want to keep one appointment per patient for the calculation? This is how to do it: noshow_df.drop_duplicates('PatientId')['Age'].mean() Keep in mind that the age of people changes over time. You need to decide how you want to handle this.
score: 0
answers question: http://stackoverflow.com/q/51071927
type: Answer

http://stackoverflow.com/a/77944118
answers question: http://stackoverflow.com/q/51044393
type: Answer
has comment: http://stackoverflow.com/comment/137411171
has body: Your code looks correct. Just make sure that if you are running it from a virtual machine (or any machine outside of localhost) that you listen to the right IP. So you can change it like this: if __name__ == '__main__': app.run_server(debug=True, host='0.0.0.0', port='8050') Setting my host=0.0.0.0 allows my server to listen to any IP, and you will use this URL: http://&lt;YourIp&gt;:8050 You can check your IP via these commands: $: ip addr / ifconfig &gt;: ipconfig
score: 0

http://stackoverflow.com/comment/89654932
type: AnswerComment
type: Comment
has text: @RickyAguilar, I'll try and have a look a little later!
score: 1
comment on: http://stackoverflow.com/a/51158653

http://stackoverflow.com/q/51166018
type: Question
answer count: 1
score: 0
tagged with: io
tagged with: python
has title: How to add binary to start of a file, and remove it, with out load it in memory?
tagged with: python-3.x
type: UnansweredQuestion
has body: I need to prepend a part of binary to start of file(Prepend a binary). I try this: s=b'/00/' open(file,'rb') as o r=o.read() o.close() h=r.hex() w=s+h b=bytearray.fromhex(w) open(file,'wb')as o o.write(b) o.close() I have memory limit and it is not possible to use that algorithm. Also I have to be able to remove this part from file, I used: open(file,"br+") as o r=o.read() o.close() h=r.hex() s=h.replace('/00/','') o=open(file,"wb") w=bytearray.fromhex(s) o.write(w) o.close() I have memory limit for this. Can Anyone help me to read and write to these files without load them completely in memory?
has answer: http://stackoverflow.com/a/51166093

http://stackoverflow.com/a/51047936
answers question: http://stackoverflow.com/q/51045402
has body: This small couple of changes should do it: def train_input_fn(features, labels, output_types, output_shapes, batch_size, feature_names): """ Provides the data pipeline for the training process. :param features: (numpy.array) A numpy array that holds the training features. :param labels: (numpy.array) A numpy array that holds the target variable. :param output_types: (tuple(tensorflow.DType)) A tuple containing the data type of each component yielded. :param output_shapes: (tuple(tensorflow.TensorShape)) A tuple containing the shape of each component yielded. :param batch_size: (int) The size of every batch. :return: (dict, int) A dictionary of key -&gt; value for every feature and the target label. """ def gen(): for f, l in zip(features, labels): yield f, l ds = tf.data.Dataset.from_generator(gen, output_types, output_shapes) # If we do repeat without any argument we actually create and infinite loop. # That is preferred, we can now control the iterations via epochs. ds = ds.repeat().batch(batch_size) feature, label = ds.make_one_shot_iterator().get_next() return {'feature_1': feature[:, 0], 'feature_2': feature[:, 1]}, label
score: 0
type: Answer

http://stackoverflow.com/comment/89234717
type: QuestionComment
type: Comment
has text: If you can extract the correct string from the log, then just parse it using json module, see https://stackoverflow.com/questions/4917006/string-to-dictionary-in-python , you will get dictionary object.
comment on: http://stackoverflow.com/q/51124383
score: 0

http://stackoverflow.com/comment/94782144
type: QuestionComment
score: 26
has text: FWIW: I got that very error because I accidentally swapped the arguments to `json.dump()`, e.g. I used `json.dump(fp, obj)` instead of the proper `json.dump(obj, fp)`.
comment on: http://stackoverflow.com/q/51146015
type: Comment

http://stackoverflow.com/comment/89249068
comment on: http://stackoverflow.com/q/51132108
score: 0
type: Comment
type: QuestionComment
has text: You can manipulate the Microsoft Excel object model from Python and win32com; the code [will end up looking very similar to what you would have written in VBA](https://stackoverflow.com/questions/13509207/ms-word-r-w-in-python-python-docx-issue-and-win32com-references/13509702#13509702).

http://stackoverflow.com/comment/89206202
has text: Isn't this what we use inheritance for. Define a separate class with your new method - which inherits from parent class, then by scope, instance will return methods from it's class definition; if not found in its definition it will go to parent class.
comment on: http://stackoverflow.com/q/51109531
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51122702
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89230585
has body: I'm new to python coding and I'm struggling to add a new column to my pandas framework. Here's what the column looks like: Time_Difference (it's in seconds) 3 2 5 6 It's a float64 type. And what I wanna create is the following new column : Duration 3 5 10 16 Actually in the format 00:00:00 (The duration adds up to about 2h since I'm tracking a run.) Now, how to create a new column, that's clear but I struggle with the itterows() or apply() function. In my naive perception, it should look something like this: df["Duration"] = df["Time_Difference"] + df["Time_Difference"].shift(1) Well, obviously it doesn't. Couldn't find anything similar on stackoverflow as I don't wanna have the sum of the whole column but on every row.
has title: Python Pandas - Adding new sum to every row
type: Question
linked to: http://stackoverflow.com/q/13878959
score: 0
has comment: http://stackoverflow.com/comment/89230613
duplicate of: http://stackoverflow.com/q/13878959

http://stackoverflow.com/comment/89092911
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51030608
has text: @Will added a couple of examples of manipulations you can do either with the binary mask from `np.in1d` or the indices from `np.where`, see my edit

http://stackoverflow.com/q/51106981
score: 4
accepted answer: http://stackoverflow.com/a/51114199
tagged with: scipy
tagged with: numpy
has comment: http://stackoverflow.com/comment/89202148
has comment: http://stackoverflow.com/comment/89202609
has title: Conjugate transpose of self using numpy syntax
has comment: http://stackoverflow.com/comment/89200995
has answer: http://stackoverflow.com/a/68724857
upvote count: 4
tagged with: matrix
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89202231
has answer: http://stackoverflow.com/a/51114199
downvote count: 0
possible better answer: http://stackoverflow.com/a/68724857
favorite count: 0
type: Question
answer count: 2
tagged with: python
has body: I am trying to translate this MATLAB code into Python. The following is the code: Y=C*Up(:,1:p-1)'*Y; And this is my translation thus far: Y = C * Up[:, 1:p-1] * Y I am having trouble with the syntax for the conjugate transpose of self that is used in the MATLAb code. I am not certain that my first idea: Y = C * Up[:, 1:p-1].getH() * Y would be correct. Does anyone have any ideas?
tagged with: matlab

qpushbutton
type: Tag
tag name: qpushbutton
tags question: http://stackoverflow.com/q/51123581

http://stackoverflow.com/q/51020928
score: 1
tagged with: dataframe
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: series
tagged with: pandas
has body: I have the following dataframe df1: A B C D 0 case 1 1950 1.1 0 1 case 1 1951 1.3 0 2 case 1 1952 1.7 0 3 case 2 1950 1.9 0 4 case 2 1951 1.2 0 5 case 2 1952 1.4 0 I want to generate a dataframe df2 like this: case 1950 1951 1952 C case 1 1.1 1.3 1.7 D case 1 0 0 0 C case 2 1.9 1.2 1.4 D case 2 0 0 0 This is my attempt: df2=pd.DataFrame() #Empty final dataframe, "transposed" cases=['case 1', 'case 2'] for i,s in enumerate(cases): #Iterate over scenario names column_c=df1['C'][0+(2*i):2+(2*i)] #Identify the column C series from df1 column_c_t=column_c.transpose() #Transpose series temp=pd.DataFrame({'Case':s}, index=['C','D']) #Empty temp dataframe for k,j in enumerate(range(1950,1953)): #Range of years as columns temp.insert(loc=k+1,column=str(j),value=0) #Add columns with years with initial value=0 for index, row in df1.iterrows(): #Iterate over the original dataframe temp.loc["C":"C",1950:1952]=column_c_t temp.loc["D":"D",1950:1952]=0 df2=df2.append(temp) This fails as Python returns ValueError Traceback (most recent call last) &lt;ipython-input-66-f175a2667647&gt; in &lt;module&gt;() 11 12 for index, row in ebsd3.iterrows(): #Iterate over the original dataframe ---&gt; 13 temp.loc["C":"C",1950:1952]=column_c_t 14 temp.loc["D":"D",1950:1952]=0 15 ~\AppData\Local\conda\conda\envs\my_root\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value) 192 key = com._apply_if_callable(key, self.obj) 193 indexer = self._get_setitem_indexer(key) --&gt; 194 self._setitem_with_indexer(indexer, value) 195 196 def _has_valid_type(self, k, axis): ~\AppData\Local\conda\conda\envs\my_root\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value) 597 598 if len(labels) != len(value): --&gt; 599 raise ValueError('Must have equal len keys and value ' 600 'when setting with an iterable') 601 ValueError: Must have equal len keys and value when setting with an iterable I believe what I am doing wrong is assigning the column_c_t series of df…
tagged with: python
has title: Pandas: how to do row in df2 = column in df1 properly?
linked to: http://stackoverflow.com/q/47152691
tagged with: transpose
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51021218
accepted answer: http://stackoverflow.com/a/51021218

http://stackoverflow.com/q/51136388
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/17266129
favorite count: 0
accepted answer: http://stackoverflow.com/a/51136480
has title: Python: group by sum with condition
tagged with: python
has body: I have a dataframe like the following: df = pd.DataFrame({'condition' : ['a','b','b','b','a','a'], 'name' : ['one', 'one', 'two', 'three', 'three', 'three'], 'data1' : [7, 3, 48, 13, 27, 12]}) df condtion data1 name 0 a 7 one 1 b 3 one 2 b 48 two 3 b 13 three 4 a 27 three 5 a 12 three For each name I want to sum on data1 and use information of condition=a if I have that information, condition=b otherwise. At the end I would like a dataframe like the following: df1 name total 0 one 7 1 two 48 2 three 39
possible better answer: http://stackoverflow.com/a/51136672
has answer: http://stackoverflow.com/a/51136480
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/89257000
tagged with: group-by
tagged with: dataframe
has answer: http://stackoverflow.com/a/51136672
has answer: http://stackoverflow.com/a/51136851
upvote count: 2

http://stackoverflow.com/comment/89129301
has text: Because you're still blocking the main Qt loop, and Qt will never update until you break out of that while loop and let it. A QTimer approach is possible, but will be quite different that what you have.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51068327

http://stackoverflow.com/a/51164609
type: Answer
has comment: http://stackoverflow.com/comment/89383117
has comment: http://stackoverflow.com/comment/89329103
has body: Code works for me if I add all import which you forgot to add. At least it display df. Finally I release that your problem is df2 inside process_table which is local variable and doesn't exist outside process_table but you want to get it outside. You have to use global df2 to assign df to external variable, not local. def process_table(fn1, fn2, fn3, fn4, fn5, fn6, fn7, fn8, fn9, fn10, fn11, fn12, fn13, fn14, fn15 ): global df2 table_list = [fn1, fn2, fn3, fn4, fn5, fn6, fn7, fn8, fn9, fn10, fn11, fn12, fn13, fn14, fn15] df = pd.DataFrame(np.reshape(table_list, (3,5))) df.index = scenarios df2 = df print(df)
score: 0
answers question: http://stackoverflow.com/q/51162394
has comment: http://stackoverflow.com/comment/89314354

http://stackoverflow.com/comment/89250744
has text: subprocess.popen is preferred over os.popen
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51133098

http://stackoverflow.com/a/65645116
has body: import numpy as np import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') df.loc[np.isnan(df['Product_Base_Margin']),['Product_Base_Margin']]=df['Product_Base_Margin'].mean() print(round(100*(df.isnull().sum()/len(df.index)), 2))
answers question: http://stackoverflow.com/q/51070985
score: 0
type: Answer

http://stackoverflow.com/comment/89212823
has text: Did you try changing the backend used in pycharm and using the same one being used in spyder.?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51111216
type: Comment

http://stackoverflow.com/q/51104120
tagged with: properties
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89195662
accepted answer: http://stackoverflow.com/a/51104302
has title: Shorter way to make properties read-only
type: Question
tagged with: readonly
tagged with: readability
has comment: http://stackoverflow.com/comment/89195898
has answer: http://stackoverflow.com/a/51104302
tagged with: class
score: 0
has body: I read on many sites that if I want to create a read-only property, I should use the property decorator. Like this: class MyClass(object): def __init__(self): self._a = None @property def a(self): return self._a I think this is a good solution if I have just 1-3 read-only properties in a class. But what if I have maybe 10 of these? This would result in 40 extra lines of code only to mark all of them as read-only. In my opinion this does not really fit to Python which is meant to be a language where you do not have to write a big bunch of code to do little things. Is there really no shorter way to make a property read-only in Python?
answer count: 1
has comment: http://stackoverflow.com/comment/89195614
tagged with: python

http://stackoverflow.com/comment/89210177
type: QuestionComment
has text: yes i did，not working though
comment on: http://stackoverflow.com/q/51111216
score: 0
type: Comment

http://stackoverflow.com/a/51179026
upvote count: 1
answers question: http://stackoverflow.com/q/51164163
has body: I figured it out. The problem was namespace. Essentially, pysqldf accepts two arguments - query and namespace which is either global or local. If the sqldf function is wrapped inside a function and needs to use a dataframe local to that function, the namespace argument should be locals. Modifying the sort data function to this below fixed the problem: def sort_chunks(data): sorted_data = pysqldf("select * from data order by b, a", locals()) return sorted_data
downvote count: 0
type: Answer
score: 1

currency
tag name: currency
type: Tag
tags question: http://stackoverflow.com/q/51111267

http://stackoverflow.com/a/51113782
has body: You are calling one function 1000 times to get 1000 values. For python-3 you can simplify your code by using random.choices(iterable, k=nubmer of elements). One call will give you a list of 1000 random items from your source-iterable: import random fruits = ['Apple','Mango','Banana','Grapes','Guava'] random.seed(500) # reduced 1000 to 10 for output-brievity random_fruits = random.choices(fruits,k=10) # no need to get 1000 times one element, get # 1000 back in one call is more efficient. print(random_fruits) Which gives an output of: ['Grapes', 'Guava', 'Banana', 'Mango', 'Grapes', 'Mango', 'Guava', 'Mango', 'Banana', 'Grapes'] You feed it an iterable and a count and get the radomn drawn results (with duplicates) back as list. Timings: import timeit s = """import random random.seed(500) fruits=['Apple','Mango','Banana','Grapes','Guava']""" timeit.timeit("k = [fruits[random.randint(0,4)] for _ in range(1000)]", setup = s , number=100) 0.11539360368355066 vs. timeit.timeit("k = random.choices(fruits, k=1000)", setup = s, number=100) 0.02338418321748037 which makes using random.choices(...) about 5 times faster.
answers question: http://stackoverflow.com/q/51112867
type: Answer
accepted answer of: http://stackoverflow.com/q/51112867
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/51133067
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89250718
has comment: http://stackoverflow.com/comment/89279582
type: UnansweredQuestion
tagged with: azure
tagged with: python
has answer: http://stackoverflow.com/a/51133143
has body: I'm not a windows user thus I'm trying to get away from using powershell. I found it really difficult to find a way to managed azure resources in different subscriptions if I have to create a service principle for each subscription. It seems that every authentication for python requires setup of service principle and yet powershell command allows my to access multiple subscriptions based on my Tenant permissions. ServicePrincipalCredentials class UserPassCredentials class Is there a python equivalent to Login-AzurermAccount -Credential $Cred -TenantID $TenantID -SubscriptionID $SubscriptionID Without creating a service principle?
type: Question
has comment: http://stackoverflow.com/comment/89250834
has title: Login-AzurermAccount in python

http://stackoverflow.com/a/53900886
has comment: http://stackoverflow.com/comment/118169295
upvote count: 2
downvote count: 1
has body: You can wrap your numpy ndarray in a dictionary and pass it to numpy_input_fn method as input x and then use the key in that dictionary to define your feature_column. Also note that because each data in your X_train has 4 dimensions, you need to specify the shape parameter when defining tf.feature_column.numeric_column. Here is the completed code: import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import tensorflow as tf iris = load_iris() X = iris['data'] y = iris['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) input_train = tf.estimator.inputs.numpy_input_fn( x = {'x': X_train}, y = y_train, num_epochs = 100, shuffle = False) feature_columns = [tf.feature_column.numeric_column(key='x', shape=(X_train.shape[1],))] classifier_model = tf.estimator.DNNClassifier( hidden_units=[10, 20, 10], n_classes=3, feature_columns=feature_columns)
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51108765
has comment: http://stackoverflow.com/comment/117495224

http://stackoverflow.com/comment/89226106
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51120179
has text: I gave up on Homebrew python, and also recommend pyenv

http://stackoverflow.com/a/51092963
score: 1
answers question: http://stackoverflow.com/q/51092372
accepted answer of: http://stackoverflow.com/q/51092372
upvote count: 1
type: AcceptedAnswer
has body: Use the PIL. There is also an example in the picam docs. import io import time import picamera from PIL import Image with picamera.PiCamera() as camera: # Set the camera's resolution to VGA @40fps and give it a couple # of seconds to measure exposure etc. camera.resolution = (1920, 1080) camera.framerate = 15 camera.rotation = 180 time.sleep(2) # Set up 40 in-memory streams outputs = [io.BytesIO() for i in range(40)] start = time.time() camera.capture_sequence(outputs, 'jpeg', use_video_port=True) finish = time.time() # How fast were we? print('Captured 40 images at %.2ffps' % (40 / (finish - start))) count = 0 for frameData in outputs: rawIO = frameData rawIO.seek(0) byteImg = Image.open(rawIO) count += 1 filename = "image" + str(count) + ".jpg" byteImg.save(filename, 'JPEG')
type: Answer
downvote count: 0

http://stackoverflow.com/q/51165668
answer count: 0
upvote count: 2
score: 1
tagged with: python-requests
downvote count: 1
type: Question
has title: request.form.getlist gives an empty list
linked to: http://stackoverflow.com/q/20001229
has comment: http://stackoverflow.com/comment/89314956
linked to: http://stackoverflow.com/q/24204118
tagged with: flask
linked to: http://stackoverflow.com/q/9733638
favorite count: 0
linked to: http://stackoverflow.com/q/10434599
has body: My question is similar with request.form.getlist won't return any entries except that I am sending requests within Python. Simplified codes are written below: app.py from flask import Flask, request, jsonify app = Flask(__name__) app.config["DEBUG"] = True @app.route("/h2ocr", methods=["POST"]) def recognize(): report_set = jsonify({"report_set": request.form.getlist("images")}) return report_set if __name__ == "__main__": app.run(host="0.0.0.0", port=7000) test_app.py import requests import json response = requests.post( url="http://localhost:7000/h2ocr", data=json.dumps({"images": ["a", "b", "c", "d", "e"]}) ) print(json.loads(response.content), response.status_code) python test_app.py gives me {"report_set": []} and status code 200. How am I supposed to get {"report_set": ["a", "b", "c", "d", "e"]} from response.content? (Strangely it worked yesterday... :/) Edits after being marked as duplicated: According to How to get POSTed json in Flask? and Post JSON using Python Requests, one can use json parameter to pass the json contents with a Python dictionary. However I've already tried that before, I just didn't write it previously: import requests import json response = requests.post( url="http://localhost:7000/h2ocr", data=json.dumps({"images": ["a", "b", "c", "d", "e"]}), json={"images": ["a", "b", "c", "d", "e"]}, headers={"Content-Type": "application/json"} ) print(json.loads(response.content), response.status_code) With any one, any two, or even all of data, json, headers parameters being given in requests.post, I am still getting {"report_set": []} from response.content. Besides, from the answer of How to get data received in Flask request, I believe that using request.form.getlist("images") is correct. What request.form is for includes "the key/value pairs in the body, from a HTML post form", and I did send a post request with a key/value pair. Excuse me but I am not getting help from those suggested duplicates.
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89315110
tagged with: python
tagged with: request

http://stackoverflow.com/a/51147868
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51089355
answers question: http://stackoverflow.com/q/51089355
score: 3
has body: You can uncheck the menu checkbox in the pages panel.
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/51159965
answer count: 1
downvote count: 1
has title: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host error with selenium on firefox
has answer: http://stackoverflow.com/a/51162664
type: UnansweredQuestion
tagged with: css-selectors
upvote count: 0
favorite count: 0
type: Question
tagged with: python
score: -1
tagged with: selenium-webdriver
tagged with: xpath
has comment: http://stackoverflow.com/comment/89303473
tagged with: selenium
has body: I am getting an error for the below code Code: import time from selenium import webdriver import urllib driver = webdriver.Firefox() driver.get('https://mycutebaby.in/contest/participant/?n=5b2b4bf83c352#_=_') voter = driver.find_element_by_id('verification_vote_btn') voter.click() Error: Traceback (most recent call last): File "C:\Users\Hello\Documents\kritin_votes.py", line 5, in &lt;module&gt; driver.get('https://mycutebaby.in/contest/participant/?n=5b2b4bf83c352#_=_') File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 332, in get self.execute(Command.GET, {'url': url}) File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 318, in execute response = self.command_executor.execute(driver_command, params) File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 472, in execute return self._request(command_info[0], url, body=data) File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 496, in _request resp = self._conn.getresponse() File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1331, in getresponse response.begin() File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 297, in begin version, status, reason = self._read_status() File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 258, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "C:\Users\Hello\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

http://stackoverflow.com/comment/89421858
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51119801
has text: I put up a question describing the problem @AlexanderReynolds

tcp
tags question: http://stackoverflow.com/q/51154906
type: Tag
tags question: http://stackoverflow.com/q/51032877
tags question: http://stackoverflow.com/q/51108994
tags question: http://stackoverflow.com/q/51029511
tag name: tcp
tags question: http://stackoverflow.com/q/51146082

http://stackoverflow.com/q/51051335
type: Question
has body: I am new to this, so be easy on me! I have some code that works fine with CSV files, but I want to convert it to read excel files so I can have multiple tabs per file. Here is the working original import numpy as np import pandas as pd import csv pd.options.mode.chained_assignment = None #the whole portfolio num_of_contracts = 1418 num_of_simul = 10000 contract_info_df = pd.read_csv('contract_info..csv', encoding='latin-1') contract_info_df = contract_info_df.set_index(['Contract Identifier']) toy_contract = contract_info_df.iloc[:num_of_contracts, :] toy_contracts_list = contract_info_df.iloc[:num_of_contracts, :].index.tolist() toy_contracts_list = (list(map(str, toy_contracts_list))) toy_contract.index = toy_contracts_list loss_df = pd.read_csv('losstable.csv') loss_table = loss_df.loc[:,toy_contracts_list][:num_of_simul] loss_table['row_sum'] = loss_table.sum(axis = 1) Here is my attempt import numpy as np import pandas as pd pd.options.mode.chained_assignment = None #the whole portfolio num_of_contracts = 162 num_of_simul = 10000 xls = pd.ExcelFile('contract_info.xlsx') df1 = pd.read_excel(xls, 'contract_info') #worksheetname contract_info_df = df1.set_index(['Contract Identifier']) toy_contract = contract_info_df.iloc[:num_of_contracts, :] toy_contracts_list = contract_info_df.iloc[:num_of_contracts, :].index.tolist() toy_contracts_list = (list(map(str, toy_contracts_list))) toy_contract.index = toy_contracts_list xls = pd.ExcelFile('losstable.xlsx') loss_df = pd.read_excel(xls, 'losstable') #woorksheet name loss_table = loss_df.loc[:,toy_contracts_list][:num_of_simul] The error comes on this last line, it can't find the 'toy_contracts_list' values in the [columns] What is my problem? Thanks
score: 1
has title: converting from reading csv to excel - pandas/python
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51052818
has comment: http://stackoverflow.com/comment/89096677
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/89094388

http://stackoverflow.com/q/51118675
has body: C is my column in pandas dataframe(df). And it consists of many lists. C [ab ab bc abb] [ll li lo ll] D is my dictionary which is as follows. D={'ab':0, 'bc':1, 'abb':2, 'll':3, 'li':4, 'lo':5} Now, I want to assign the values of my dictionary to the list and for that, I am using the below mentioned code. df.C= [D[item] for item in df.C] Here, I am getting this error: TypeError: list indices must be integers or slices, not str. Thanks for the help.
type: AnsweredQuestion
has title: Inserting dictionary values in pandas column
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51118786
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51118786
tagged with: python

http://stackoverflow.com/comment/89408333
has text: Unless anyone wants to provide evidence to the contrary.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51201035

http://stackoverflow.com/comment/89104253
type: Comment
type: QuestionComment
has text: your `button_passed` not passed by ajax?
comment on: http://stackoverflow.com/q/51056746
score: 0

http://stackoverflow.com/a/51152923
score: 2
has body: You are passing for outputs argument the layer name. You should pass the layer(in other words the argument value should be variable that has reference to output layer). model = Model(inputs=[main_input_1, main_input_2], outputs=[logistic_regression_output])
answers question: http://stackoverflow.com/q/51152579
accepted answer of: http://stackoverflow.com/q/51152579
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89089470
comment on: http://stackoverflow.com/q/51049062
score: 0
type: Comment
type: QuestionComment
has text: Hello Chaban, What happens when you try to run this code? My best guess is that it wont run as written unless `models.Model` does more then I think it does.

http://stackoverflow.com/a/51088659
accepted answer of: http://stackoverflow.com/q/51088585
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89166698
answers question: http://stackoverflow.com/q/51088585
type: Answer
has body: The following should work: latitude = latitude.values[0] .values accesses the numpy representation of a pandas.DataFrame Assuming your code latitude = df['latitude'] really results in a DataFrame of shape (1,1), then the above should work.
score: 17
has comment: http://stackoverflow.com/comment/89166124
upvote count: 17
has comment: http://stackoverflow.com/comment/89169613

http://stackoverflow.com/q/51132674
linked to: http://stackoverflow.com/q/22249579
tagged with: python
tagged with: object-detection
has body: OpenCV-Python version 3.4.1 I am trying to detect multiple objects through a camera. The objects are Face, eyes, spoon, pen. Spoon and Pen are particular i.e. it should only detect the Pen and Spoon that I have trained it with. But it detects all the kind of faces and eyes as I have used the '.xml' file for face and eye detection that comes with OpenCV-Python. My Question is about the code. There is a line in my code below which says detectMultiScale(gray, 1.3, 10). Now, I used the documentation and still couldn't clearly understand the last two parameters of the bracket. My code: # with camera feed import cv2 import numpy as np face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') spoon_cascade = cv2.CascadeClassifier('SpoonCascade.xml') pen_cascade = cv2.CascadeClassifier('PenCascade.xml') cap = cv2.VideoCapture('link') while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) spoons = spoon_cascade.detectMultiScale(gray, 1.3, 10) pens = pen_cascade.detectMultiScale(gray, 1.3, 10) for (x, y, w, h) in spoons: font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'Spoon', (x-w, y-h), font, 0.5, (0, 255, 255), 2, cv2.LINE_AA) cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) for (x, y, w, h) in pens: font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'Pen', (x-w, y-h), font, 0.5, (0, 255, 255), 2, cv2.LINE_AA) cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) for (x, y, w, h) in faces: font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'Face', (x + w, y + h), font, 0.5, (0, 255, 255), 2, cv2.LINE_AA) cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_color = img[y:y + h, x:x + w] roi_gray = gray[y:y + h, x:x + w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2) cv2.imshow('Voila', img) cv2.imwrite('…
tagged with: opencv
type: AnsweredQuestion
score: 2
tagged with: opencv3.0
has title: Meaning of Parameters of detectMultiScale(a, b, c)
upvote count: 2
has answer: http://stackoverflow.com/a/51356792
type: Question
tagged with: cascade-classifier
accepted answer: http://stackoverflow.com/a/51356792
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89241766
has text: You can probably have a sequence of parameters; maybe white-space, or comma separated? I have not tried.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51128373

http://stackoverflow.com/q/51154031
tagged with: pandas
has comment: http://stackoverflow.com/comment/89291475
duplicate of: http://stackoverflow.com/q/17071871
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/15315452
tagged with: python
linked to: http://stackoverflow.com/q/17071871
has comment: http://stackoverflow.com/comment/89291219
has body: I have following dataframe: one two a 1.0 7.0 b 2.0 2.0 c 3.0 3.0 d 6.0 4.0 What I would like to do is to check for example for index a if each of the values in the columns is greater than 4. If one of the values is indeed greater the system prints the message that in "column name" value "x" is greater than 4. How can I accomplish that ?
type: Question
has title: How to check each value in a row in a pandas dataframe for a certain condition?
tagged with: dataframe
score: 0

http://stackoverflow.com/a/51111166
upvote count: 17
has body: This is documented at the end of the introduction to the "Format String Syntax" section: A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified. Some examples of this feature can also be found at the end of the "Format examples" section, such as: &gt;&gt;&gt; for align, text in zip('&lt;^&gt;', ['left', 'center', 'right']): ... '{0:{fill}{align}16}'.format(text, fill=align, align=align) ... 'left&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' '^^^^^center^^^^^' '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;right' &gt;&gt;&gt;
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89217125
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51111136
answers question: http://stackoverflow.com/q/51111136
score: 17

http://stackoverflow.com/a/78085804
has comment: http://stackoverflow.com/comment/137661188
score: 0
answers question: http://stackoverflow.com/q/51012787
type: Answer
has body: import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor themes = ['Одежда', 'Животные', 'Политика', 'IT'] def get_links(theme): page = requests.get(f'https://habr.com/ru/search/page1/?q={theme}&target_type=posts&order=relevance').text page_soup = BeautifulSoup(page, 'html.parser') count_pages = int(page_soup.find_all('div', 'tm-pagination__page-group')[-1].text.split()[0]) hrefs = [] for i in range(1, count_pages + 1): print(i) page = requests.get(f'https://habr.com/ru/search/page{i}/?q={theme}&target_type=posts&order=relevance').text page_s = BeautifulSoup(page, 'html.parser') links = page_s.find_all('article', 'tm-articles-list__item') hrefs.extend([f'https://habr.com/ru/news/{link["id"]}/' for link in links]) return hrefs def get_text(href): print(href) try: pagex = requests.get(href).text page_su = BeautifulSoup(pagex, 'html.parser') text = page_su.find_all("div", "article-formatted-body article-formatted-body article-formatted-body_version-1")[0].text return text except: return '' all_texts = [] for theme in themes: print(f'Сбор ссылок по теме {theme} начат') hrefs = get_links(theme) print(f'Сбор ссылок по теме {theme} закончен') texts = [''] * 1000 with ThreadPoolExecutor() as executor: results = list(executor.map(get_text, hrefs)) all_texts += results print('Сбор текстов по ссылкам окончен')

http://stackoverflow.com/q/51150468
accepted answer: http://stackoverflow.com/a/51567342
upvote count: 10
tagged with: python
type: AnsweredQuestion
has title: Error "You must compile your model before using it" in case of LSTM and fit_generator in Keras
downvote count: 0
has comment: http://stackoverflow.com/comment/90080965
type: Question
has body: I create my own class which create a Keras model inside one of its methods. self.model = Sequential() self.model.add(LSTM(32)) self.model.add(Dense(2, activation='relu')) self.model.compile(optimizer='RMSprop', loss='categorical_crossentropy', metrics=['acc']) In other method i try to train this model using python generator as data provider. self.model.fit_generator(my_gen(), steps=10, epochs=1, verbose=1) This causes an error: raise RuntimeError('You must compile your model before using it.') RuntimeError: You must compile your model before using it. Error does not rises if i change LSTM layer to Dense layer. What am i doing wrong? Keras version 2.2.0 with Tensorflow 1.8.0 backend.
has comment: http://stackoverflow.com/comment/89970786
score: 10
tagged with: keras
has comment: http://stackoverflow.com/comment/90011052
has comment: http://stackoverflow.com/comment/89285896
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51567342

http://stackoverflow.com/a/51152797
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89289006
answers question: http://stackoverflow.com/q/51152680
accepted answer of: http://stackoverflow.com/q/51152680
upvote count: 1
has body: Using re.sub Demo: import re s = """INPUT [color=00ff08]100[/color](3.0/3.0)""" text = re.sub("\[color=.*?\]", "", s) text = re.sub("\[/color\]", "", text) print(text)

http://stackoverflow.com/a/51165638
type: Answer
has body: The problem was here: path(r'^i18n/', include('django.conf.urls.i18n')), I cut off r'^': path('i18n/', include('django.conf.urls.i18n')), and works!
answers question: http://stackoverflow.com/q/51165542
score: 0

http://stackoverflow.com/q/51106680
type: Question
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/51106748
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51106773
tagged with: python
has comment: http://stackoverflow.com/comment/89200426
has comment: http://stackoverflow.com/comment/89200326
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89201269
has title: How to call a function within a class with self
has comment: http://stackoverflow.com/comment/89201492
linked to: http://stackoverflow.com/q/136097
score: -1
has body: Suppose I have the following: class myClass: def foo(self): # do something How can I call myClass from inside the class without declaring an new myClass Object? i.e. I'd like something like class myClass: def foo(self): # do something if __name__ == '__main__': # call foo or without main: class myClass: def foo(self): # do something # call foo Right now I keep getting either the error that self is not defined, or the error that foo expects 1 argument but 0 was provided.

http://stackoverflow.com/comment/89087871
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51048322
score: 7
has text: Surprisingly, Pillow can [write](https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html#pdf) pdfs, it just can't read them.

http://stackoverflow.com/comment/89312826
has text: if you only have 137 images in your dataset that's too low for training a neural network. Increase the dataset and use heavy augmentation.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51148876
score: 0

http://stackoverflow.com/q/51085665
downvote count: 0
has body: My objective is to test the spider written using scrapy (Python). I tried using contracts but it is really limited in the sense that I can not test things like pagination or whether some attributes are extracted correctly or not. def parse(self, response): """ This function parses a sample response. Some contracts are mingled with this docstring. @url http://someurl.com @returns items 1 16 @returns requests 0 0 @scrapes Title Author Year Price """ So the second idea is to mock all the requests that the spider makes in one run, and use that in the testing phase to check against expected results. However, I am unsure and how can I mock every request that is made via the spider. I looked into various libraries and one of them is betamax. However, it only supports http requests made by requests client of Python. (As mentioned here). There is another library vcrpy, but it also supports limited clients only. Are you using Requests? If you’re not using Requests, Betamax is not for you. You should checkout VCRpy. Are you using Sessions or are you using the functional API (e.g., requests.get)? Last option is to manually record all the requests and somehow store them, but that's not really feasible at the scale which the spider make requests. Does scrapy.Requests use some underline python client which can be used to mock those requests? Or is there any other way I can mock all the http requests made by the spider in one run and use that for testing the spider for expected behavior?
tagged with: scrapy
type: Question
tagged with: testing
upvote count: 3
answer count: 1
favorite count: 0
tagged with: betamax
has answer: http://stackoverflow.com/a/51089090
type: UnansweredQuestion
has title: Mocking the requests for testing in Scrapy Spider
tagged with: python
tagged with: python-requests
score: 3

http://stackoverflow.com/q/51085018
has title: How to group columns by label in a histogram using a panda DataFrame?
score: 0
tagged with: pandas
answer count: 1
tagged with: histogram
has body: I have a panda dataframe called language consisting of two columns: lang level 0 english 2 1 spanish 2 2 spanish 1 3 english 1 4 english 3 5 spanish 2 6 spanish 1 7 spanish 3 I would like to represent it in a histogram group by the categorical value language in such a way that in the same plot I have 2 groups -one for each language- with as many bar as many labels I have in the level column (3 in this case). So far I have tried the following by previously categorizaing lang getting a label of 1 to english and of 2 to spanish: language.hist(by=language['lang']) With what I obtained the following graph which is not what I want. Ideally I would like a graph similar to this where the LetterGrade would be language and the legend would refer to the level variable.
has answer: http://stackoverflow.com/a/51085087
accepted answer: http://stackoverflow.com/a/51085087
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: graphics

http://stackoverflow.com/a/51046347
upvote count: 1
has body: Python is not Java. In Python you can only access names that are either builtins or defined in the current scope or it's parents scopes - the "top-level" scope being the module namespace (AKA "global" namespace). The import statement (which is an executable statement FWIW) does two things: first load the module (this actually happens only once per process, then the module is cached in sys.modules), then bind the imported name(s) in the current scope. IOW this: import foo is syntaxic sugar for foo = __import__("foo") and from foo import bar is syntaxic sugar for foo = __import__("foo") bar = getattr(foo, "bar") del foo Also you have to understand what "loading a module" really means: executing all the code at the module's top-level. As I mentionned, import is an executable statement, but so are class and def - the def statement creates a code object from the function's body and signature, then creates a function object with this code object, and finally bind this function object to the function's name in the current scope, the class statement does the same thing for a class (executing all the code at the "class" statement's top-level in a temporary namespace and using this namespace to create the "class" object, then binding the class object to it's name). IOW, all happens at runtime, everything is an object (including functions, classes and modules), and everything you do with an import, class or def statement can be done "manually" too (more or less easily though - manually creating a function is quite an involved process). So as you can see, this really has nothing to do with how either Java or C++ work.
answers question: http://stackoverflow.com/q/51045799
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51045799

http://stackoverflow.com/comment/89016694
score: 0
has text: That somehow breaks the whole code, now even INPUT isn't generated properly
type: Comment
comment on: http://stackoverflow.com/a/51011825
type: AnswerComment

http://stackoverflow.com/a/51060344
has comment: http://stackoverflow.com/comment/89115320
score: 2
has comment: http://stackoverflow.com/comment/89114410
has comment: http://stackoverflow.com/comment/89114478
upvote count: 2
has body: Using groupby + cumsum: df['NewCol'] = df.groupby('colA')['colB'].cumsum() For summing strings, you can use a list comprehension with groupby: df = df.sort_values('colA') df['C'] = [''.join(g.iloc[:i+1].values) \ for _, g in df.groupby('colA')['colB'] \ for i in range(len(g.index))] print(df) colA colB C 0 1 val1 val1 1 1 val2 val1val2 2 1 val3 val1val2val3 3 2 val4 val4 4 2 val5 val4val5 5 2 val6 val4val5val6 6 3 val7 val7 7 3 val8 val7val8 8 3 val9 val7val8val9 Explanation First iterate groupby elements via for _, g in df.groupby(...)[...]. We ignore the index _ here as we are only interested in the values. Then iterate range(len(g.index)), i.e. iterate over the number of items in the group. Apply ''.join on the first i values. We use g.iloc[:i+1] to extract the first i values in a group. Wrap all the above in a nested list comprehension.
downvote count: 0
answers question: http://stackoverflow.com/q/51060309
has comment: http://stackoverflow.com/comment/89115214
type: Answer

http://stackoverflow.com/comment/89210029
comment on: http://stackoverflow.com/q/51111163
type: Comment
type: QuestionComment
score: 1
has text: Possible duplicate of [Making a collatz program automate the boring stuff](https://stackoverflow.com/questions/33508034/making-a-collatz-program-automate-the-boring-stuff)

http://stackoverflow.com/comment/89061151
comment on: http://stackoverflow.com/q/51034490
score: 0
has text: @blhsing I'm not sending a file. I send texts.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51073265
accepted answer of: http://stackoverflow.com/q/51072974
score: 2
downvote count: 0
has body: pip.main is no longer supported, and, as of 10.0, was removed. (See this documentation on what to do instead, but that probably isn't directly relevant to you—you're just trying to use PyCharm, not write your own replacement for PyCharm…) Anyway, any graphical package manager that was built around calling pip.main, as PyCharm's used to be, breaks with 10.0. IIRC, PyCharm changed its code to handle this before 10.0 even went live. However, you're using an old version of PyCharm, which doesn't have those changes. The obvious solution is to update PyCharm. If you don't have any reason to use an old version, just get the latest version (as of today, 2018.1.4) by auto-updating, or by downloading it from the main Download page. If you need to stick with an old version for some reason, get the latest 2017.2 version (as of today, 2017.2.7) from the Previous Releases page. This should be essentially the same as the version you have, but with critical fixes backported (which hopefully includes working with pip 10, although I haven't tested that). The other option is to downgrade pip to a pre-10.0 version. You can specify a version as just &lt;10. If you want to specify one explicitly, I think 9.0.3 should be the last-ever 9.x version, but, to be safe, check the version history. I don't know if downgrading pip with pip is supposed to work, but it actually did seem to work when I tried it on a test environment: python3 -m pip install --force-reinstall 'pip&lt;10' If not, you can uninstall it and reinstall it: python -m pip uninstall pip python -m ensurepip python -m pip install -U 'pip&lt;10'
upvote count: 2
has comment: http://stackoverflow.com/comment/89157196
has comment: http://stackoverflow.com/comment/89158181
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51072974
type: Answer

http://stackoverflow.com/comment/89126469
score: 0
type: AnswerComment
type: Comment
has text: @Frynio, More performance (test it yourself), unpacking requires a little more work.
comment on: http://stackoverflow.com/a/51068136

http://stackoverflow.com/q/51040078
tagged with: python
has body: I have been trying to use tf.optimizer.AdagradDA with a Linear Classifier. Here is my code: def input_fn(): features_in = { "random_var": tf.convert_to_tensor(np.random.randn(100)) } labels_in = tf.convert_to_tensor(np.random.choice([0, 1], size=(100,), p=[1./2, 1./2])) dataset = tf.data.Dataset.from_tensors((features_in, labels_in)) dataset.repeat(2) dataset.batch(1) iterator = dataset.make_one_shot_iterator() features, labels = iterator.get_next() return features, labels def main(): global_step_tensor = tf.Variable(0, trainable=False, name='global_step') optimizer = tf.train.AdagradDAOptimizer(learning_rate=0.001, global_step=global_step_tensor) columns = [tf.feature_column.numeric_column('random_var')] model = tf.estimator.LinearClassifier(optimizer=optimizer, feature_columns=columns) model.train(input_fn=input_fn) When I'm running the code I'm getting one of the following errors: ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/linear_model/random_var/weights/part_0:0", shape=(1, 1), dtype=float32_ref). ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/head/AdagradDA/update_linear/linear_model/random_var/weights/part_0/Cast_2/x:0", shape=(), dtype=float32) ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/linear/linear_model/random_var/weights/part_0/AdagradDA_1:0", shape=(1, 1), dtype=float32_ref). When I run the same code with a FtrlOptimizer or a AdagradOptimize the code runs properly. So I'm guessing, the issue has to be related with the global_step_tensor instanciation. Here are the things that I have tried so far: Move the code snippet into a with tf.Session() as sess: Creating the optimizer into the LinearClassifier constructor
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/53125306
has title: Tensor must be from the same graph as Tensor in LinearClassifier with AdagradDA Optimizer
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89255430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51133678
score: 0
has text: Hi eyllanesc, I tried to complete a bit more of the code but putting it all would be a mess for any reader as there are too many non-relevant functions linked between each other. I think the blinking or flickering problem comes down to the _plot() method I created although I also think is a normal behavior of matplotlib but there must be a way of avoiding this. Maybe using FuncAnimation? Thanks!

http://stackoverflow.com/comment/89201598
comment on: http://stackoverflow.com/a/51072452
type: Comment
has text: For example, when i call the view that brings me all the user with es_tecnico = True, it works, because it bring me the users i created with django admin. To resume everything, i need to register (create) a new extended user with Django Rest Framework and "rest_framework.authtoken.models" without django admin framework interfering
score: 0
type: AnswerComment

http://stackoverflow.com/comment/126636169
type: AnswerComment
score: 0
has text: `resultRDD.filter(lambda x: any(y == "OK" for y in x[1]))`
type: Comment
comment on: http://stackoverflow.com/a/51040032

http://stackoverflow.com/a/58910591
score: 0
has comment: http://stackoverflow.com/comment/114378524
has body: Bubble sort using recursion without using any loop, def bubble_sort_recur(a, i, j, n): if j == n: i = i+1 j = 0 if i == n: return if a[i] &gt; a[j]: temp = a[j] a[j] = a[i] a[i] = temp bubble_sort_recur(a, i, j+1, n); else: bubble_sort_recur(a, i, j + 1, n); return a a = [1, 12, 3, 4] a = bubble_sort_recur(a, 0, 0, len(a)) print(a)
type: Answer
answers question: http://stackoverflow.com/q/51146458

http://stackoverflow.com/q/51164697
tagged with: django
tagged with: python
score: 3
tagged with: django-unittest
type: Question
has body: How do you test code that disables autocommit and uses savepoints, inside a Django unittest? The default Django unittest class wraps all tests inside an @atomic decorator, which is usually exactly what you want, to ensure the sqlite database gets reset between tests. However, any code that touches transaction.set_autocommit() from a test throws the error: TransactionManagementError: This is forbidden when an 'atomic' block is active. even if it works fine outside the unittest. How do you temporarily disable the transaction autocommit in a unittest, so you can test manual commits?
downvote count: 0
favorite count: 0
answer count: 1
has title: Testing manual transactions inside Django unittests
has answer: http://stackoverflow.com/a/51165628
has comment: http://stackoverflow.com/comment/89312790
has comment: http://stackoverflow.com/comment/89312675
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/89066549
has text: Have you considered appending to a list instead of assigning to a variable ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51037299
score: 0

http://stackoverflow.com/a/51120062
type: Answer
downvote count: 0
has body: You're nearly there. You cannot pass strings to c unless they're valid colors. You can either pass a list of valid colors, or pass numeric, integer values by factorizing your column. For example: plt.scatter(titanic['age'], titanic['fare'], alpha=0.5, c=pd.factorize(titanic['sex'])[0]) Or, titanic = titanic.dropna(subset=['sex']) mapping = {'male' : 'blue', 'female' : 'red'} plt.scatter(titanic['age'], titanic['fare'], alpha=0.5, c=titanic['sex'].map(mapping)) plt.show()
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51120020
answers question: http://stackoverflow.com/q/51120020

http://stackoverflow.com/a/51162504
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: The documentation for Kinds of filter explains all of the many options in depth. (Make sure to continue on through at least the find_all(), name, and keyword arguments sections after this one; that's where you'll find the best examples.) The one you're using does exact matches only: The simplest filter is a string. Pass a string to a search method and Beautiful Soup will perform a match against that exact string. But you can use, e.g., a regex instead: If you pass in a regular expression object, Beautiful Soup will filter against that regular expression using its search() method. soup.find("a", string=re.compile(r'(?i)(first|last)')) … or a function: If none of the other matches work for you, define a function that takes an element as its only argument. The function should return True if the argument matches, and False otherwise. def matches_firstlast(s): lower = s.casefold() return 'first' in lower or 'last' in lower soup.find("a", string=matches_firstlast) You could also write a function that takes the whole tag, instead of just its string, which could be more resilient against errors caused by unexpected tags, if that's an issue. You haven't specified very clearly what the exact rule that you want is, or given us a complete example to test against, so I can't promise that the regex or the function actually do exactly what you want. Here's an example: >>> h = 'first last first something something last larst fist First Last ' >>> soup = BeautifulSoup(h, 'lxml') >>> soup.find_all("a", string=re.compile(r'(?i)(first|last)')) [first, last first, something something last] >>> soup.find_all("a", string=matches_firstlast) [first, last first, something something last] Hopefully this—and the docs—are enough to code up whatever you need.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51162422
answers question: http://stackoverflow.com/q/51162422
score: 1

http://stackoverflow.com/a/51122195
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89229605
has comment: http://stackoverflow.com/comment/89229618
has comment: http://stackoverflow.com/comment/89229691
accepted answer of: http://stackoverflow.com/q/51121973
has comment: http://stackoverflow.com/comment/89229733
type: AcceptedAnswer
downvote count: 0
has body: Okay, so I see that you're using selenium from the snippet in the question. If that's the case, then there's no way to set request headers with the web driver. Reddit will know you are a bot. If you only need the page source, you can use requests to get the page and open it with selenium or use BeautifulSoup to parse the page from bs4 import BeautifulSoup import requests url = "https://www.reddit.com/user/loganb3171" page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(page.text, 'html.parser') print(soup.prettify())
has comment: http://stackoverflow.com/comment/89229546
type: Answer
answers question: http://stackoverflow.com/q/51121973
has comment: http://stackoverflow.com/comment/89229811

http://stackoverflow.com/q/51059843
tagged with: python
accepted answer: http://stackoverflow.com/a/51103692
linked to: http://stackoverflow.com/q/43387112
linked to: http://stackoverflow.com/q/12957492
has answer: http://stackoverflow.com/a/51060110
tagged with: c++
score: 2
has comment: http://stackoverflow.com/comment/89122530
has answer: http://stackoverflow.com/a/51103692
has comment: http://stackoverflow.com/comment/89123355
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29758662
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89186754
has comment: http://stackoverflow.com/comment/89155327
answer count: 2
has comment: http://stackoverflow.com/comment/89110461
has body: How can I pass an OpenCV 3 image from Python 3 to C++? In technical terms, how do I convert a NumPy array to a cv::Mat object and back? To make my question more specific, let's assume: I have a Python program that uses OpenCV to capture images from the webcam and display them. (In real life, I'm prototyping further functions there, such as some web server features.) cam.py: import cv2 def main(): cam = cv2.VideoCapture(0) while True: _, img = cam.read() cv2.imshow('cam', img) # TODO: Call the C++ function from the sample below # img = helloWorld(img) cv2.waitKey(16) # let imshow do its work (16 ms -&gt; 60 FPS) cv2.destroyAllWindows() if __name__ == '__main__': main() Run python3 cam.py to try it out. I would like to use an existing helloWorld function from some C++ library that processes the OpenCV images. (In real life, it does some signal processing and extracts information from the images.) For the sake of simplicity, my sample function below just mirrors the image horizontally. The main function is there to check that helloWorld works as expected. cam.cpp: #include &lt;opencv2/highgui/highgui.hpp&gt; using namespace cv; using namespace std; void helloWorld(Mat img) { flip(img, img, 1); } int main() { VideoCapture stream1(0); while (true) { Mat img; stream1.read(img); helloWorld(img); imshow("cam", img); waitKey(16); } return 0; } To compile this code, run g++ -std=c++11 -lopencv_core -lopencv_highgui -lopencv_videoio cam.cpp -o cam, then execute ./cam to try it out. Now what changes should I make to my code so that I can call the helloWorld C++ function out of my Python app? Luckily, I have access to the C++ source code, so that I can extend and recompile it if necessary.
downvote count: 0
has title: How to convert OpenCV image data from Python to C++?
favorite count: 0
possible better answer: http://stackoverflow.com/a/51060110
has comment: http://stackoverflow.com/comment/89187906

http://stackoverflow.com/comment/89296366
has text: the thing is that I have to concatenate the lists on the go in a loop since the lists are stored in different files. So I cannot really (a_list, b_list, c_list,....zzz_list) do that, I will have to append it one by one.. @sacul
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51156088

http://stackoverflow.com/comment/89237634
type: AnswerComment
comment on: http://stackoverflow.com/a/51125837
type: Comment
score: 1
has text: Thanks for response About first question: the purpose of it was to know why exactly this issue was fixed with context manager? If it doesn't run any functions related with connection or session then why it works? Maybe it somehow helps in garbage collecting in the right way?

http://stackoverflow.com/comment/89256895
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51136387
has text: As for "core functions in Python" - the problem is the documentation isn't explicit in that regard.
type: AnswerComment

http://stackoverflow.com/q/51060952
tagged with: python
has answer: http://stackoverflow.com/a/51063194
linked to: http://stackoverflow.com/q/41542769
has title: ValueError Pandas duplicate rows with time sequence using Numpy arange
type: Question
has body: I am currently working to find a more faster solution than the one in this link. The issue is, when my data reaches a relatively huge amount (e.g. 1M rows), it is considerably slow, especially when it is a second-by-second instead of the minute-by-minute in the original post. So I am trying to find a more efficient way of doing it using Numpy arange. But I am running into an error #First- with pd.to_datetime x = pd.DataFrame({ "ID": np.repeat(df.ID.values, df.time_delta.values), "time": np.arange(pd.to_datetime(df.FROM.values), pd.to_datetime(df.TO.values), np.timedelta64(1,'s'))}) #Second - without pd.to_datetime x = pd.DataFrame({ "ID": np.repeat(df.ID.values, df.time_delta.values), "time": np.arange(df.FROM.values, df.TO.values, np.timedelta64(1,'s'))}) The idea here is to repeat the ID for how many seconds from the column FROM to column TO (time_delta). But I keep getting the error ValueError: Could not convert object to NumPy timedelta. Here is the dtypes for my df, ID object FROM datetime64[ns, UTC] TO datetime64[ns, UTC] time_delta int64 dtype: object Can anyone tell me what I am doing wrong? Thank you in advance.
has comment: http://stackoverflow.com/comment/89112243
tagged with: numpy
linked to: http://stackoverflow.com/q/50520268
score: 0
tagged with: pandas
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/51071020
has comment: http://stackoverflow.com/comment/89132281
has body: Port 8888 is already bound on my (OS X 10.13.5) system, by a process running inside a docker container: $ netstat -an | grep 8888 tcp6 0 0 ::1.8888 *.* LISTEN tcp4 0 0 *.8888 *.* LISTEN A python program which tries to bind to that port (using as close to the socket options of golang as I can manage), fails in the way I expect: import socket import fcntl import os def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) flag = fcntl.fcntl(sock.fileno(), fcntl.F_GETFL) fcntl.fcntl(sock.fileno(), fcntl.F_SETFL, flag | os.O_NONBLOCK) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind(("0.0.0.0", 8888)) sock.listen(5) main() fails with: $ python test.py Traceback (most recent call last): File "test.py", line 15, in &lt;module&gt; main() File "test.py", line 11, in main sock.bind(("0.0.0.0", 8888)) OSError: [Errno 48] Address already in use But a go program creating a connection via net.Listen does not fail, as I expect it to: package main import ( "fmt" "net" ) func main() { _, err := net.Listen("tcp", "0.0.0.0:8888") if err != nil { fmt.Printf("Connection error: %s\n", err) } else { fmt.Println("Listening") } } Succeeds with: $ go run test.go Listening A coworker reports that with the same setup, his Ubuntu system correctly fails the go program. Why does this succeed on a Mac, and how can I get the net.Listen to show an error in binding to port 8888? edit: If I occupy port 8888 with a simple go program like: package main import ( "log" "net/http" ) func main() { log.Fatal(http.ListenAndServe("0.0.0.0:8888", nil)) } Then test.go correctly fails to bind to the port. However the docker process (which is running basically that ^^^) does not cause it to fail. edit 2: If I specify "tcp4", then the program does indeed fail as I expect. If I specify "tcp6", it succeeds but netstat says it binds to * instead of ::1: $ netstat -an | grep 8888 tcp6 0 0 *.8888 *.* LISTEN tcp6 0 0 ::1.8888 *.* LISTEN tcp4 0 0 *.8888 *.* LISTEN So, specifying "tcp4" will…
has comment: http://stackoverflow.com/comment/89132234
tagged with: sockets
has answer: http://stackoverflow.com/a/51073906
tagged with: python
type: AnsweredQuestion
has title: Golang net.Listen binds to port that's already in use
has comment: http://stackoverflow.com/comment/89136806
score: 7
has answer: http://stackoverflow.com/a/51074226
upvote count: 7
type: Question
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/51073906
has comment: http://stackoverflow.com/comment/89132357
has comment: http://stackoverflow.com/comment/89135417
possible better answer: http://stackoverflow.com/a/51074226
has comment: http://stackoverflow.com/comment/89132257
tagged with: go
answer count: 2
has comment: http://stackoverflow.com/comment/89136758
downvote count: 0
tagged with: macos
favorite count: 0
has comment: http://stackoverflow.com/comment/89136701

http://stackoverflow.com/comment/89250830
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51127044
type: AnswerComment
has text: Thank you for the in-depth example! That's pretty close to what I was trying the other night. This approach works pretty well. However while this works ```import scdcc; scdcc.api.core```, I will still end up with an ImportError when I try to import a submodule in the namespace of another module. ```from scdcc.api import core # ImportError: No module named api```. Any idea on how to solve this?

http://stackoverflow.com/q/51132582
has comment: http://stackoverflow.com/comment/89250045
downvote count: 0
has answer: http://stackoverflow.com/a/51132908
has comment: http://stackoverflow.com/comment/89249878
answer count: 2
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: No such File or Directory in Python Web Crawling?
has answer: http://stackoverflow.com/a/51133011
score: 1
has body: I am a newbie to python. I want to extract the name of categories and webpages of wikipedia page through the crawling procedure. During the course of this I am facing the following error. Downloading Traceback (most recent call last): File "C:\Users\SIBA\Desktop\PDF\Code\trialcode.py", line 100, in &lt;module&gt; printTree(name, 0) File "C:\Users\SIBA\Desktop\PDF\Code\trialcode.py", line 80, in printTree content = open("categories/Category:"+catName+".html").readlines() FileNotFoundError: [Errno 2] No such file or directory: 'categories/Category:Cricket.html' The code snippet of what I have tried is as follows. I am using Python 3.6 version. #Imports import httplib2 from bs4 import BeautifulSoup import subprocess import time import os,sys os.path.dirname(sys.argv[0]) #declarations catRoot = "http://en.wikipedia.org/wiki/Category:" MAX_DEPTH = 100 done = [] ignore = [] # Removes all newline characters and replaces with spaces def removeNewLines(in_text): return in_text.replace('\n', ' ') # Downloads a link into the destination def download(link, dest): # print link if not os.path.exists(dest) or os.path.getsize(dest) == 0: subprocess.getoutput('wget "' + link + '" -O "' + dest+ '"') print ("Downloading") def ensureDir(f): if not os.path.exists(f): os.makedirs(f) # Cleans a text by removing tags def clean(in_text): s_list = list(in_text) i,j = 0,0 while i &lt; len(s_list): # iterate until a left-angle bracket is found if s_list[i] == '&lt;': if s_list[i+1] == 'b' and s_list[i+2] == 'r' and s_list[i+3] == '&gt;': i=i+1 print (hello) continue while s_list[i] != '&gt;': # pop everything from the the left-angle bracket until the right-angle bracket s_list.pop(i) # pops the right-angle bracket, too s_list.pop(i) elif s_list[i] == '\n': s_list.pop(i) else: i=i+1 # convert the list back into text join_char='' return (join_char.join(s_list))#.replace("&lt;br&gt;","\n") # Gets bullets def getBullets(content): mainSoup = BeautifulSoup(contents) # Gets empty bullets def getAllBu…
upvote count: 1
tagged with: web-crawler
tagged with: httplib2
type: Question

http://stackoverflow.com/comment/89116839
type: Comment
comment on: http://stackoverflow.com/a/51062865
has text: Thanks for the quick reply!
score: 0
type: AnswerComment

http://stackoverflow.com/q/51085754
has answer: http://stackoverflow.com/a/51085915
favorite count: 0
has title: Getting all values from a list that do not have today's date in Python
tagged with: datetime
accepted answer: http://stackoverflow.com/a/51085915
tagged with: python
type: AnsweredQuestion
tagged with: list
upvote count: 1
type: Question
tagged with: database
has body: I am connecting to a database and retrieving a list of cameras and their respective id's. Then, I traverse through this list and get the current time of these images that have last been captured. I want to find all the cameras and their respective id's that have not been captured on today's date only (2018-06-28). import psycopg2 import os import datetime DATABASE_URL = os.environ['DATABASE_URL'] conn = psycopg2.connect(DATABASE_URL, sslmode='allow').cursor() all_cameras_query = "SELECT cameraid, name, url, latitude, longitude FROM cameras ORDER BY cameraid" conn.execute(all_cameras_query) all_cameras = conn.fetchall() current_date = datetime.datetime.today().strftime('%Y-%m-%d') last_updated_list = [] for camera in all_cameras: last_updated_query = "SELECT cameraid, curr_time FROM images WHERE cameraid=%d ORDER BY curr_time DESC" % ( camera[0]) conn.execute(last_updated_query) last_updated_list.append(conn.fetchall()) print(last_updated_list) last_updated_list prints out a list of every cameraid and the last captured time. Now, using python lists and searching, I would like to use the current_date to get all cameras that are not from today. [(185, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(186, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(187, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(188, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(189, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(190, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(191, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(192, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(193, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(194, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(195, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(196, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(197, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(198, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(199, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(200, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(201, d…
answer count: 1
downvote count: 0
score: 1

matplotlib-venn
tag name: matplotlib-venn
tags question: http://stackoverflow.com/q/51052573
type: Tag

http://stackoverflow.com/comment/89107064
score: 1
type: QuestionComment
has text: I want to read image in Python, and send it to C++ to perform operation on C++. So I have to find a way to do it, and I use a pointer for that. But I found the way to do it using #ralf answer.
comment on: http://stackoverflow.com/q/51036850
type: Comment

http://stackoverflow.com/q/51038842
answer count: 0
has title: How to scrape every tick data from IQO binary traderoom using python or mql5?
type: UnansweredQuestion
has body: Here have a look at the image: As you can see that in the image I have marked the TickData and the respective Time. I am willing to scrape it and use it in the MT5 software or anywhere in real time. I am trying to get the live values from the binary IQOption and use it for analysis. But I am lacking ideas how I can do it. Kindly, suggest me the way so that I can do it easily. I need guidance. Please help me.
tagged with: web-scraping
upvote count: 1
tagged with: mql5
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89100696
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: metatrader5
has comment: http://stackoverflow.com/comment/89089444

http://stackoverflow.com/comment/89132202
comment on: http://stackoverflow.com/a/51071163
score: 0
type: AnswerComment
type: Comment
has text: I don't think this works in this case- you need a `MapType()` column to use `getItem()` but it looks like it's a string here.

http://stackoverflow.com/comment/89240608
score: 1
comment on: http://stackoverflow.com/q/51127470
type: Comment
type: QuestionComment
has text: You possibly are missing system packages for libraries that scipy uses for optional components. Check what system packages are required for scipy. See https://scipy.github.io/devdocs/building/linux.html#generic-instructions

http://stackoverflow.com/comment/89224662
type: Comment
has text: This is great! I think this is what I was looking for. However, how do I reference the variables that are passed into the view (i.e. request, objecttype...) within the view_wrapper? I tried passing them via `kwargs` and `args`, but I can't reference them.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51111633

http://stackoverflow.com/q/51130173
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51130191
has title: python pandas DatetimeIndex how to get first day of month?
type: Question
has body: begin = '2016-08-01' end = '2018-07-01' time_unit = 'm' unit = 'month' time_dict = {} time_series = pd.DatetimeIndex(start=begin, end=end, freq=time_unit).tolist() all month generated DatetimeIndex start end day of month. for example 2016-08-31 00:00:00 how can I get 2016-08-01 00:00:00
score: 0

http://stackoverflow.com/a/51096957
has body: We can use lookarounds here like this: (?&lt;=PRIME MINISTER:\s)[\s\S]*?(?=NAME_OF_JOURNALIST:\s|\s*\Z) Demo Explantion (?&lt;=PRIME MINISTER:\s) a postive lookbehind to anchor the beginning [\s\S]*? a modified . matching across lines, lazy (?=NAME_OF_JOURNALIST:\s|\s*\Z) a positive lookahead that matches a subsequent journalist name or the end of the string \Z. Code Sample
answers question: http://stackoverflow.com/q/51096743
downvote count: 1
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/51074416
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89138172
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51074478
has title: Is there a simple way to explain required argument and optional argument? Python
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/51074478
tagged with: python
has body: I am currently learning Python through edX platform, I came across two terms that got me confused: required argument and optional argument. Can anyone feel so kind to explain the difference between the two? Take function round() for example, the quiz stated: "The function round has two arguments. Select the two correct statements about these arguments." here are the options: number is a required argument. number is an optional argument. ndigits is a required argument. ndigits is an optional argument. According to what I have learned, I know that you have to specify input in order to get ndigit, such as round(1.68 , 1) >>>>1.7 If I just wrote round(1.68) >>>> I will get 2 Thus, to my understanding, ndigit is an optional argument, meaning that you have to choose in order to make it work, otherwise, the function will only work what is it required, like an autopilot program Please give me some feedback if I am wrong, or share some link where I can learn more. I am not the native English speaker, so the words "required" and "optional" really seem confusing to me at one point. I hope to learn more from you all. By the way, I got the right answer, I'll keep learning Python, hope to work in this field, cheers!
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89133744
type: AnswerComment
score: 0
type: Comment
has text: Aye, that was me. You should not write a hacky `class Ip` for this stuff, when there is already a tried and tested one in the Python stdlibs: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address
comment on: http://stackoverflow.com/a/51070998

http://stackoverflow.com/comment/89167411
has text: @Felix See I've read that question and many others like it but I don't understand what it is he really did, he posted what changes he made. But not what those changes do specifically, I'd like to understand what it is id be doing, you know?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51088946
score: 0

http://stackoverflow.com/comment/89257313
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51136313
has text: But even if they have the same slope , that doesn't mean they're linear as well, because they can have different y-intercepts (parameter b in y = ax + b)
type: Comment

http://stackoverflow.com/comment/89198482
has text: Hi Mateen, i'm using a np.max command to find the highest point among the 20 points behind the current point on the wind direction, is there any problem in this method?
comment on: http://stackoverflow.com/q/51092529
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51078201
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89146800
has body: I think need add all mising hours for correct cumcount: #floor to hours df['timestamp'] = df['timestamp'].dt.floor('h') #add missing hours per group df = df.set_index('timestamp').groupby('customer_id').apply(lambda x: x.asfreq('h')) #cumulative count per group df['hour'] = df.groupby(level=0).cumcount() df= df.dropna(subset=['customer_id']).drop('customer_id', 1).reset_index() df['hour'] = ('Day' + (df['hour'] // 24).add(1).astype(str) + ' - ' + (df['hour'] % 24).astype(str)) print (df) customer_id timestamp value hour 0 1 2018-05-28 03:00:00 1000.0 Day1 - 0 1 1 2018-05-28 04:00:00 1450.0 Day1 - 1 2 1 2018-05-28 05:00:00 1040.0 Day1 - 2 3 1 2018-05-29 02:00:00 1500.0 Day1 - 23 4 1 2018-05-29 04:00:00 1090.0 Day2 - 1 5 3 2018-05-18 03:00:00 1060.0 Day1 - 0 6 3 2018-05-18 05:00:00 1040.0 Day1 - 2 7 3 2018-05-19 03:00:00 1520.0 Day2 - 0 8 3 2018-05-19 04:00:00 1490.0 Day2 - 1
has comment: http://stackoverflow.com/comment/89147032
has comment: http://stackoverflow.com/comment/89146301
type: Answer
accepted answer of: http://stackoverflow.com/q/51078117
has comment: http://stackoverflow.com/comment/89145270
answers question: http://stackoverflow.com/q/51078117
has comment: http://stackoverflow.com/comment/89147429
has comment: http://stackoverflow.com/comment/89146266
has comment: http://stackoverflow.com/comment/89146754
downvote count: 0

http://stackoverflow.com/comment/89080466
type: Comment
has text: Please look at update 1, you don't need the original answer
type: AnswerComment
comment on: http://stackoverflow.com/a/51044571
score: 0

http://stackoverflow.com/q/51054127
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89103754
tagged with: dataframe
has answer: http://stackoverflow.com/a/51056285
score: 0
tagged with: pandas
has title: pandas df.info() as dataframe to clipboard. How?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/35436331
has body: df.info() to a clipboard as a dataframe, so that it can be pasted to Excel for checking on things. df.info() is the only (easy and quick) method that shows ALL the column names of a dataframe whenever the dataframe has LOTS of columns. What is the best way to get the result into a clipboard for pasting into Excel.. and any other methods. &gt;&gt;&gt; dfcsr2.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 19903 entries, 0 to 19902 Data columns (total 88 columns): seq 19903 non-null int64 doc_dir 19903 non-null object carrier 19903 non-null object flight_number 19903 non-null object flight_date 19903 non-null datetime64[ns] sch_arr_time 19903 non-null datetime64[ns] arr_time 19903 non-null datetime64[ns] ... ... ...

http://stackoverflow.com/comment/89308486
score: 0
has text: I'm happy with an answer like `pd.Series(['A', 'A'], ['C', 'D'])` as well.
type: Comment
comment on: http://stackoverflow.com/q/51162242
type: QuestionComment

http://stackoverflow.com/comment/89198705
type: QuestionComment
comment on: http://stackoverflow.com/q/51105517
score: 0
has text: Please post enough code to reproduce the problem.
type: Comment

http://stackoverflow.com/a/51065152
upvote count: 1
has comment: http://stackoverflow.com/comment/89120267
downvote count: 0
has comment: http://stackoverflow.com/comment/89120530
has comment: http://stackoverflow.com/comment/89120272
type: Answer
answers question: http://stackoverflow.com/q/51064911
has body: Denis' answer is correct. You can conditionally use the function. This is an incredibly common pattern in Python, especially when you're concerned with cross-version compatibility. try: my_input = raw_input except NameError: my_input = input all_config_msgs = ['Okta App URL. E.g https://acme.okta.com/home/amazon_aws/b07384d113edec49eaa6/123: ','Organization username. E.g jane.doe@acme.com: '] config_details = [] for config_msg in all_config_msgs: config_details.append(my_input(config_msg)) Tested and working in Python 2.7 and 3.5, but it will work as well for your versions. Another option that is a bit contested, because some people get all weird about changing global names, is to just enforce that raw_input exists, or define it: try: _ = raw_input except NameError: raw_input = input
has comment: http://stackoverflow.com/comment/89120335
score: 1
has comment: http://stackoverflow.com/comment/89120198

http://stackoverflow.com/comment/89244255
score: 0
type: AnswerComment
type: Comment
has text: still facing the same problem
comment on: http://stackoverflow.com/a/51129577

http://stackoverflow.com/a/51029192
has body: This isn't really related to the fact that it is a classmethod. For the same reason we don't need to pass the instance when calling a "normal" instance method, the instance (and in this case, the class) is passed implicitly. class Foo: def instance_method(self): print('No need to pass {} explictly'.format(self)) @classmethod def class_method(cls): print('No need to pass {} explictly'.format(cls)) obj = Foo() obj.instance_method() # No need to pass &lt;__main__.Foo object at 0x0000000002A38DD8&gt; explictly obj.class_method() # No need to pass &lt;class '__main__.Foo'&gt; explictly
upvote count: 3
has comment: http://stackoverflow.com/comment/89051837
has comment: http://stackoverflow.com/comment/89051595
has comment: http://stackoverflow.com/comment/89051745
answers question: http://stackoverflow.com/q/51029115
score: 3
accepted answer of: http://stackoverflow.com/q/51029115
has comment: http://stackoverflow.com/comment/89051933
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89051549
has comment: http://stackoverflow.com/comment/89051625
type: Answer

http://stackoverflow.com/comment/89078313
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51043628
has text: i've got a feeling `spatial.distance.correlation(vect[i], vect[k])` is pretty slow. you could try using `pandas` with `apply`. alternatively, does the operation have to act on each entry? Some entries may be wildly dissimilar to vect[i], so maybe you can do a short operation to toss them out. Also, consider parallellizing.
type: Comment

http://stackoverflow.com/comment/89311880
comment on: http://stackoverflow.com/q/51164215
score: 0
type: Comment
type: QuestionComment
has text: @cricket_007 can't I use a tool like Jenkins to schedule my apps, the fact is that I can run my apps in the Jenkins too but not sure how they will interact then

web-services
type: Tag
tags question: http://stackoverflow.com/q/51158289
tag name: web-services

http://stackoverflow.com/a/51056222
has body: To get the Packagenames of the list, you can use the -ExpandProperty feature of Select-Object and pipe it to the install command: pip list --outdated | Select-Object -ExpandProperty Package | Where-Object { $exclude -notcontains $_ } | ForEach { pip install -U $_}
answers question: http://stackoverflow.com/q/51054657
score: 0
type: Answer

http://stackoverflow.com/a/51028598
has comment: http://stackoverflow.com/comment/89049594
type: Answer
has body: import requests, re from urllib.parse import urljoin from bs4 import BeautifulSoup import pandas as pd url = "http://www.espn.com/mma/fighters?search={}" titleList = [] countryList = [] stanceList = [] reachList = [] ageList = [] weightClassList = [] trainingCenterList = [] winsList = [] losesList =[] drawsList = [] tkosList = [] subsList = [] #i believe this is what takes us from one page to another, but not 100% sure yet for linknum in [chr(i) for i in range(ord('a'),ord('z')+1)]: r = requests.get(url.format(linknum)) soup = BeautifulSoup(r.text,'html.parser') #a[href*=] gets all anchors a that contain whatever the href*='' for links in soup.select(".tablehead a[href*='id']"): #urljoin just takes a url and another string and combines them to create a new url res = requests.get(urljoin(url,links.get("href"))) sauce = BeautifulSoup(res.text,"lxml") try: title = sauce.select_one(".player-bio h1").text except AttributeError: title = "" try: country = sauce.find('span',text='Country').next_sibling except AttributeError: country = "" try: stance = sauce.find('span',text='Stance').next_sibling except AttributeError: stance = "" try: reach = sauce.find('span',text='Reach').next_sibling except AttributeError: reach = "" try: age = sauce.find('span',text='Birth Date').next_sibling[-3:-1] except AttributeError: age = "" try: weightClass = sauce.find('li',attrs={'class':'first'}).text except AttributeError: weightClass = "" try: trainingCenter = sauce.find('li',attrs={'class':'last'}).text except AttributeError: trainingCenter = "" try: wins = sauce.find('table',attrs={'class':'header-stats'})('td')[0].text except AttributeError: wins = "" try: loses = sauce.find('table',attrs={'class':'header-stats'})('td')[1].text except AttributeError: loses = "" try: draws = sauce.find('table',attrs={'class':'header-stats'})('td')[2].text except AttributeError: draws = "" try: tkos = sauce.find_all('table',attrs={'class':'header-stats'})[1]('td')[0].text except AttributeError: tkos = "" t…
answers question: http://stackoverflow.com/q/51014545
has comment: http://stackoverflow.com/comment/89051206
score: 0

http://stackoverflow.com/comment/89275827
score: 0
comment on: http://stackoverflow.com/q/51144929
type: Comment
has text: Short answer: In the `__init__()` method, define it as `self.cards = []`, then you'll be able to reference `self.cards` in all the other methods of the class.
type: QuestionComment

http://stackoverflow.com/a/51090435
type: Answer
has body: import collections with open(arg, "r") as sheet: s = csv.reader(sheet) main_header = next(s) sub_header = next(s) result = {} for row in s: aheader = None for main, sub, value in zip(main_header, sub_header, row): if not main: main = aheader result.setdefault(main, {}).setdefault(sub, []).append(value) aheader = main print (result)
score: 0
answers question: http://stackoverflow.com/q/51090299

http://stackoverflow.com/comment/89186067
type: Comment
type: QuestionComment
has text: @jpp That will increase the running time. The function to extract different datatype takes time and I don't want to repeat it for 'Line' column since it is same for every group.
comment on: http://stackoverflow.com/q/51099197
score: 0

http://stackoverflow.com/q/51069486
linked to: http://stackoverflow.com/q/13742494
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89128850
linked to: http://stackoverflow.com/q/32550667
has comment: http://stackoverflow.com/comment/89128926
accepted answer: http://stackoverflow.com/a/51069549
linked to: http://stackoverflow.com/q/46323798
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51069549
has title: Subprocess run/call not working
has comment: http://stackoverflow.com/comment/89128997
tagged with: terminal
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I want to use the "raster2pgsql" utility in my Python code. When I use it in a Linux terminal, it works fine. This is the command: $ raster2pgsql -a "/mnt/c/Users/Jan/path/to/raster/dem.tiff" test_schema.raster2 | psql -h localhost -d pisl -U pisl Then I use subprocess.run (I have also tried subprocess.call) to use this same tool in my Python code. This is my code: from subprocess import run command = ["raster2pgsql", "-a", '"' + file_name + '"', self.schema_name + "." + identifier, "|", "psql", "-h", "localhost", "-p", "5432", "-d", self.dbname] run(command) I get this error: ERROR: Unable to read raster file: "/mnt/c/Users/Jan/path/to/raster/dem.tiff" Printing command gives this which I think is correct (equivalent to what worked in the terminal): ['raster2pgsql', '-a', '"/mnt/c/Users/Jan/path/to/raster/dem.tiff"', 'test_schema.raster2', '|', 'psql', '-h', 'localhost', '-p', '5432', '-d', 'pisl'] I have double checked that the path to the raster file is correct, tried single quotes, double quotes but nothing helps. I have looked at a number of similar question (here, here or here ) but did not find anything helpful. I use Python 3.5 and Linux Bash Shell in Windows 10. Question: What is wrong with the way I use subprocess?

http://stackoverflow.com/a/51055589
has comment: http://stackoverflow.com/comment/104067605
type: Answer
has body: Find the absolute path of the python3 interpreter with a command like this: $ which python3 /Library/Frameworks/Python.framework/Versions/3.6/bin/python Your path may be something different, of course. Copy that line to your clipboard. Edit the pip3 script, which was installed using incorrect interpreter. Something like this: vi $(which pip3) You might need to use sudo here, but try it first without. The first line will be something like: #!/Library/Frameworks/Python.framework/Versions/2.7/bin/python Change it to the path found in the previous step, e.g. #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python Save the pip3 file and exit. This should be sufficient to associate pip3 with the correct environment. Check and verify the result with pip3 --version. Now pip3 install numpy should work as expected.
score: 12
answers question: http://stackoverflow.com/q/51055429
upvote count: 12
downvote count: 0

http://stackoverflow.com/comment/89099809
score: 1
comment on: http://stackoverflow.com/q/51054490
type: Comment
type: QuestionComment
has text: Weird question. I would say `data` is both a parameter and an argument, in both #8 and #10.

http://stackoverflow.com/a/51151963
answers question: http://stackoverflow.com/q/51151889
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89288746
downvote count: 0
has body: Try with: df.iloc[row_index, col_index] = "no" or df.loc[row_index, 'Lactose intolerance] = "no"
has comment: http://stackoverflow.com/comment/89288243
type: Answer
has comment: http://stackoverflow.com/comment/89288966

http://stackoverflow.com/comment/89080672
type: Comment
has text: or instead of defining a __unicode__ method you can write this in template itself. {{ user.first_name + user.last_name }}. but writing __unicode__ is a best practice.
score: 0
comment on: http://stackoverflow.com/a/51044341
type: AnswerComment

http://stackoverflow.com/q/51052268
possible better answer: http://stackoverflow.com/a/69671122
accepted answer: http://stackoverflow.com/a/51052613
type: Question
tagged with: video-streaming
tagged with: opencv
score: 10
has title: Streaming video in memory with OpenCV VideoWriter and Python BytesIO
has answer: http://stackoverflow.com/a/51052613
answer count: 3
downvote count: 0
has body: I was wondering if it is possible to 'stream' data using the OpenCV VideoWriter class in Python? Normally for handling data in memory that would otherwise go to disk I use BytesIO (or StringIO). My attempt to use BytesIO fails though: import cv2 from io import BytesIO stream = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc('x264') data = BytesIO() # added these to try to make data appear more like a string data.name = 'stream.{}'.format('av1') data.__str__ = lambda x: x.name try: video = cv2.VideoWriter(data, fourcc=fourcc, fps=30., frameSize=(640, 480)) start = data.tell() # Check if camera opened successfully if (stream.isOpened() == False): print("Unable to read camera feed", file=sys.stderr) exit(1) # record loop while True: _, frame = stream.read() video.write(frame) data.seek(start) # do stuff with frame bytes # ... data.seek(start) finally: try: video.release() except: pass finally: stream.release() However instead of writing the BytesIO object I end up with the following message: Traceback (most recent call last): File "video_server.py", line 54, in talk_to_client video = cv2.VideoWriter(data, fourcc=fourcc, fps=fps, frameSize=(width, height)) TypeError: Required argument 'apiPreference' (pos 2) not found ... So when I modify the VideoWriter call to be cv2.VideoWriter(data, apiPreference=0, fourcc=fourcc, fps=30., frameSize=(640, 480)) (I read that 0 means auto, but I also tried cv2.CAP_FFMPEG), I instead get the following error: Traceback (most recent call last): File "video_server.py", line 54, in talk_to_client video = cv2.VideoWriter(data, apiPreference=0, fourcc=fourcc, fps=fps, frameSize=(width, height)) TypeError: bad argument type for built-in operation So my question is, is it possible to write encoded video using the cv2.VideoWriter class in memory and if so how is it done? At this point I'm fresh out of ideas, so any help would be most welcome :-)
has answer: http://stackoverflow.com/a/69671122
favorite count: 0
has answer: http://stackoverflow.com/a/69792994
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/89095832
type: AnsweredQuestion
tagged with: in-memory

http://stackoverflow.com/comment/89191765
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51102135
has text: Another thing, your script is _highly_ insecure. Anyone can post what ever commands they want (within the user that runs PHP's permissions of course). You should escape the name with [escapeshellcmd()](http://php.net/manual/en/function.escapeshellcmd.php).

http://stackoverflow.com/a/63595136
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51167099
has comment: http://stackoverflow.com/comment/112457248
has body: Thanks @Kevin C for the tip, trying out now ... As you wrote, the "pip under windows" solution is working BUT ... useless to some degree, because ansible really needs to be executed in a linux environment to fully work as designed. To try out install python 3.8 via MS Store e.g. and pip install the cloned ansible git repo from here As you suggested using the Windows Subsystem for Linux (WSL) will work. See below my Summary and Walkthrough Summary It is possible to install ansible on Win10 + Windows Subsystem for linux rather than in a docker container, you have to decide youself if it fits your purpose better or worse. The setup time is also very reasonable, and e.g. integration into Visual Studio code works in order to test ansible development locally (ansible-lint or ansible-playbook --syntax-check e.g.). Also, other commands, like ansible-galaxy and ansible-inventory commands work as expected, basic tests done... Walkthrough You might want to make sure you are running the most recent Windows 10 release; At the time of writing I am using Windows 10 pro, Version 2004. WSL2 is available for this Windows Version. WSL2 installation via Admin powershell as per MS instructions: dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart wsl --set-default-version 2 you might still have to update the wsl kernel image if the last command tells you to, so follow the wsl2kernel update guide that is shown there if you see this message: WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel ... after installing that, the above message should not be shown any more. At the time of writing installing any linux "distribution" from the Microsoft store directly via powershell is not possible . [EDIT] @2021-02: previously, https://aka.ms/wslstore worked... not any more. BUT you can now still either use the store and…
downvote count: 0

http://stackoverflow.com/q/51152792
tagged with: web-scraping
tagged with: scrapy
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51154506
downvote count: 3
has body: I would like to know what is the best/preferred PYTHON 3.x solution (fast to execute, easy to implement, option to specify user agent, send browser &amp; version etc to webserver to avoid my IP being blacklisted) which can scrape data on all of below options (mentioned based on complexity as per my understanding). Any Static webpage with data in tables / Div Dynamic webpage which completes loading in one go Dynamic webpage which requires signin using username password &amp; completes loading in one go after we login. Sample URL for username password: https://dashboard.janrain.com/signin?dest=http://janrain.com Dynamic web-page which requires sign-in using oauth from popular service like LinkedIn, google etc &amp; completes loading in one go after we login. I understand this involves some page redirects, token handling etc. Sample URL for oauth based logins: https://dashboard.janrain.com/signin?dest=http://janrain.com All of bullet point 4 above combined with option of selecting some drop-down (lets say like "sort by date") or can involve selecting some check-boxes, based on which the dynamic data displayed would change. I need to scrape the data after the action of check-boxes/drop-downs has been performed as any user would do it to change the display of the dynamic data Sample URL - https://careers.microsoft.com/us/en/search-results?rk=l-seattlearea You have option of drop-down as well as some checkbox in the page Dynamic webpage with Ajax loading in which data can keep loading as => 6.1 we keep scrolling down like facebook, twitter or linkedin main page to get data Sample URL - facebook, twitter, linked etc => 6.2 or we keep clicking some button/div at the end of the ajax container to get next set of data; Sample URL - https://www.linkedin.com/pulse/cost-climate-change-indian-railways-punctuality-more-editors-india-/ Here you have to click "Show Previous Comments" at the bottom of the page if you need to look &amp; scrape all the comments I want to learn &amp; bui…
tagged with: urllib2
answer count: 2
has comment: http://stackoverflow.com/comment/89318033
has title: Python Webscraping Solution Reccomendations required
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51154075
accepted answer: http://stackoverflow.com/a/51154075
possible better answer: http://stackoverflow.com/a/51154506
tagged with: python
upvote count: 0
score: -3

http://stackoverflow.com/q/51050277
has comment: http://stackoverflow.com/comment/89091927
has comment: http://stackoverflow.com/comment/89092228
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51051025
tagged with: django-templates
has comment: http://stackoverflow.com/comment/89092052
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89091975
has title: Django generic FormView not showing when included in other template
tagged with: django-forms
has body: First, what is currently working: I have a form defined in forms.py: class EnrollForm(forms.Form): course_id = forms.IntegerField(required=True) def enroll(self): print(self.cleaned_data) I build said form in a view in views.py: class EnrollView(FormView): template_name = 'core/enroll.html' form_class = EnrollForm success_url='' def form_valid(self, form): form.enroll() return super().form_valid(form) I display it in enroll.html: {% csrf_token %} {{ form }} So, when I visit localhost:8000/core/enroll/, I see the form in all its might: However, when I attempt to include this file in another file using {% include "core/enroll.html" %} in another html file, that only displays the button while the {{ form }} tag in enroll.htmldoesn't resolve to anything and just silently fails, showing: EDIT1: This is the file from which I am attempting to include the form: {{ course.title }} {% if error_message %} {{ error_message }} {% endif %} {# reverse lookup on codes with course foreignkey relationship #} {% for code in course.code_set.all %} {{ code.code }} {% endfor %} {% include "core/enroll.html" %}
score: 0
tagged with: django-generic-views
answer count: 1

http://stackoverflow.com/q/51106297
possible better answer: http://stackoverflow.com/a/51106865
has answer: http://stackoverflow.com/a/51106865
accepted answer: http://stackoverflow.com/a/51107005
downvote count: 0
type: Question
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51107005
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89200850
has comment: http://stackoverflow.com/comment/89200881
has body: I have a Series of Labels pd.Series(['L1', 'L2', 'L3'], ['A', 'B', 'A']) and a dataframe pd.DataFrame([[1,2], [3,4]], ['I1', 'I2'], ['A', 'B']) I'd like to have a dataframe with columns ['L1', 'L2', 'L3'] with the column data from 'A', 'B', 'A' respectively. Like so... pd.DataFrame([[1,2,1], [3,4,3]], ['I1', 'I2'], ['L1', 'L2', 'L3']) in a nice pandas way.
has comment: http://stackoverflow.com/comment/89200094
answer count: 3
has answer: http://stackoverflow.com/a/51107182
upvote count: 1
tagged with: reindex
has title: Reindex DataFrame Columns by Label Series
favorite count: 0
tagged with: pandas
tagged with: python

header
type: Tag
tags question: http://stackoverflow.com/q/51071908
tag name: header
tags question: http://stackoverflow.com/q/51140316

http://stackoverflow.com/comment/89053257
comment on: http://stackoverflow.com/q/51030131
score: 0
has text: oh ok guys, i just updated it
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89203929
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51108226
score: 1
has text: @jedwards thanks. Though the location made sense I still checked it and found out `pip.exe` was created earlier than when it's supposed to be. I uninstalled, deleted the whole directory and reinstalled python and this time it worked.

http://stackoverflow.com/q/51100508
tagged with: python
possible better answer: http://stackoverflow.com/a/51101348
type: AnsweredQuestion
downvote count: 0
tagged with: loss-function
tagged with: tensorflow
score: 9
type: Question
has answer: http://stackoverflow.com/a/51148177
accepted answer: http://stackoverflow.com/a/51148177
has title: Implementing custom loss function in keras with condition
tagged with: keras
has answer: http://stackoverflow.com/a/51101348
answer count: 2
favorite count: 0
upvote count: 9
has body: I need some help with keras loss function. I have been implementing custom loss function on keras with Tensorflow backend. I have implemented the custom loss function in numpy but it would be great if it could be translated into keras loss function. The loss function takes dataframe and series of user id. The Euclidean distance for same user_id are positive and negative if the user_id are different. The function returns summed up scalar distance of the dataframe. def custom_loss_numpy (encodings, user_id): # user_id: a pandas series of users # encodings: a pandas dataframe of encodings batch_dist = 0 for i in range(len(user_id)): first_row = encodings.iloc[i,:].values first_user = user_id[i] for j in range(i+1, len(user_id)): second_user = user_id[j] second_row = encodings.iloc[j,:].values # compute distance: if the users are same then Euclidean distance is positive otherwise negative. if first_user == second_user: tmp_dist = np.linalg.norm(first_row - second_row) else: tmp_dist = -np.linalg.norm(first_row - second_row) batch_dist += tmp_dist return batch_dist I have tried to implement into keras loss function. I extracted numpy array from y_true and y_pred tensor objects. def custom_loss_keras(y_true, y_pred): # session of my program sess = tf_session.TF_Session().get() with sess.as_default(): array_pred = y_pred.eval() print(array_pred) But I get the following error. tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'dense_1_input' with dtype float and shape [?,102] [[Node: dense_1_input = Placeholder[dtype=DT_FLOAT, shape=[?,102], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] Any kind of help would be really appreciated.

http://stackoverflow.com/comment/89162536
comment on: http://stackoverflow.com/a/51086207
type: Comment
has text: I've seen it done both ways and hotly debated. I was trained to have a test set that is never trained on either by cross validation or otherwise.
score: 1
type: AnswerComment

blueprint
tags question: http://stackoverflow.com/q/51020809
type: Tag
tag name: blueprint

http://stackoverflow.com/comment/89055234
type: Comment
type: QuestionComment
has text: Thank you, I fixed it, but the problem of my while loop not repeating still remains.
comment on: http://stackoverflow.com/q/51031379
score: 0

contour
tags question: http://stackoverflow.com/q/51034209
tag name: contour
tags question: http://stackoverflow.com/q/51025204
tags question: http://stackoverflow.com/q/51129269
tags question: http://stackoverflow.com/q/51119801
type: Tag
tags question: http://stackoverflow.com/q/51136116
tags question: http://stackoverflow.com/q/51036169

http://stackoverflow.com/comment/90471983
has text: Nice answer! It can take so much effort to write an answer like this; it's a shame when some askers don't think that's enough.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51034992

http://stackoverflow.com/comment/89068737
type: Comment
has text: yeah, but it is about avoiding using moduleA.main() and simply doing moduleA() but using some magic e.g. if __name__ == '__main__' in each module ... are there any python tricks which could help me doing so?
comment on: http://stackoverflow.com/q/51037998
score: 0
type: QuestionComment

dictionary
tags question: http://stackoverflow.com/q/51066851
tags question: http://stackoverflow.com/q/51109827
tags question: http://stackoverflow.com/q/51030391
tags question: http://stackoverflow.com/q/51017095
tags question: http://stackoverflow.com/q/51151510
tags question: http://stackoverflow.com/q/51035281
tags question: http://stackoverflow.com/q/51104645
tags question: http://stackoverflow.com/q/51157360
tags question: http://stackoverflow.com/q/51125170
tags question: http://stackoverflow.com/q/51153553
tags question: http://stackoverflow.com/q/51114987
tags question: http://stackoverflow.com/q/51144354
tags question: http://stackoverflow.com/q/51108451
tags question: http://stackoverflow.com/q/51088012
tags question: http://stackoverflow.com/q/51124119
tags question: http://stackoverflow.com/q/51125054
tags question: http://stackoverflow.com/q/51085875
tags question: http://stackoverflow.com/q/51113280
tags question: http://stackoverflow.com/q/51042399
tags question: http://stackoverflow.com/q/51027875
tags question: http://stackoverflow.com/q/51079753
tags question: http://stackoverflow.com/q/51035431
tags question: http://stackoverflow.com/q/51129996
tags question: http://stackoverflow.com/q/51145380
tags question: http://stackoverflow.com/q/51053092
tags question: http://stackoverflow.com/q/51124186
tags question: http://stackoverflow.com/q/51018409
tags question: http://stackoverflow.com/q/51111017
tags question: http://stackoverflow.com/q/51088796
tags question: http://stackoverflow.com/q/51081176
tags question: http://stackoverflow.com/q/51142313
tags question: http://stackoverflow.com/q/51062934
tags question: http://stackoverflow.com/q/51022758
tags question: http://stackoverflow.com/q/51143752
tags question: http://stackoverflow.com/q/51151015
tags question: http://stackoverflow.com/q/51149822
tags question: http://stackoverflow.com/q/51025438
tags question: http://stackoverflow.com/q/51107582
tags question: http://stackoverflow.com/q/51112646
tags question: http://stackoverflow.com/q/51109597
tags question: http://stackoverflow.com/q/51031857
tags question: http://stackoverflow.com/q/51120046
tags question: http://stackoverflow.com/q/51157042
tags question: http://stackoverflow.com/q/51047307
tags question: http://stackoverflow.com/q/51035654
tags question: http://stackoverflow.com/q/51067949
tag name: dictionary
tags question: http://stackoverflow.com/q/51084123
tags question: http://stackoverflow.com/q/51156652
tags question: http://stackoverflow.com/q/51116488
tags question: http://stackoverflow.com/q/51048170
tags question: http://stackoverflow.com/q/51080795
tags question: http://stackoverflow.com/q/51109575
tags question: http://stackoverflow.com/q/51087954
tags question: http://stackoverflow.com/q/51102752
tags question: http://stackoverflow.com/q/51079621
tags question: http://stackoverflow.com/q/51156095
tags question: http://stackoverflow.com/q/51014274
tags question: http://stackoverflow.com/q/51026089
tags question: http://stackoverflow.com/q/51059699
tags question: http://stackoverflow.com/q/51131660
tags question: http://stackoverflow.com/q/51145253
tags question: http://stackoverflow.com/q/51151226
tags question: http://stackoverflow.com/q/51079857
tags question: http://stackoverflow.com/q/51057028
tags question: http://stackoverflow.com/q/51102385
tags question: http://stackoverflow.com/q/51082236
tags question: http://stackoverflow.com/q/51068716
tags question: http://stackoverflow.com/q/51103389
tags question: http://stackoverflow.com/q/51105916
tags question: http://stackoverflow.com/q/51103867
tags question: http://stackoverflow.com/q/51166473
tags question: http://stackoverflow.com/q/51068938
tags question: http://stackoverflow.com/q/51099651
tags question: http://stackoverflow.com/q/51051894
tags question: http://stackoverflow.com/q/51166266
tags question: http://stackoverflow.com/q/51146522
tags question: http://stackoverflow.com/q/51033773
tags question: http://stackoverflow.com/q/51014310
tags question: http://stackoverflow.com/q/51115660

http://stackoverflow.com/comment/89082317
has text: You can convert your json to a string with json.dumps(your_json) but then you should use json.loads(your_field_with_json_string) each time when getting data from it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51045241
score: 0

http://stackoverflow.com/a/51157298
has comment: http://stackoverflow.com/comment/89298108
type: Answer
accepted answer of: http://stackoverflow.com/q/51157288
answers question: http://stackoverflow.com/q/51157288
downvote count: 0
score: 1
has body: Use isnull and then cast the result to int with astype: Loan_a1 = pd.DataFrame({'mths_since_recent_revol_delinq': [np.nan, 33.0, np.nan, np.nan, 57.0, 21.0, 60.0, np.nan, 2.0, 24.0, np.nan]}) results_key = "mths_since_recent_revol_delinq_add" input_key = "mths_since_recent_revol_delinq" Loan_a1[results_key] = Loan_a1[input_key].isnull().astype(int) print (Loan_a1) mths_since_recent_revol_delinq mths_since_recent_revol_delinq_add 0 NaN 1 1 33.0 0 2 NaN 1 3 NaN 1 4 57.0 0 5 21.0 0 6 60.0 0 7 NaN 1 8 2.0 0 9 24.0 0 10 NaN 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/95113265
has text: you mean if the 'A_attack' is in a variable . You can use the same only `var="A_attack"` `df[var]=a_attack.values`
comment on: http://stackoverflow.com/a/51152186
type: AnswerComment
type: Comment
score: 1

recurrence
tags question: http://stackoverflow.com/q/51105876
type: Tag
tag name: recurrence

http://stackoverflow.com/a/74832954
score: 0
type: Answer
has body: l1 = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test1'}] l2 = [{'id': 3, 'age': 10},{'id': 4, 'age': 10},{'id': 1, 'age': 10}, {'id': 2, 'age': 20}] def m1(l1,l2): d = defaultdict(dict) for l in (l1,l2): for d1 in l : d[d1['id']].update(d1) aa = sorted(d.values(),key = itemgetter('id')) aap = print(aa) return aap m1(l1,l2) &quot;&quot;&quot; output : [{'id': 1, 'name': 'test', 'age': 10}, {'id': 2, 'name': 'test1', 'age': 20}, {'id': 3, 'age': 10}, {'id': 4, 'age': 10}] &quot;&quot;&quot;
answers question: http://stackoverflow.com/q/51069263

http://stackoverflow.com/a/51042108
upvote count: 0
has comment: http://stackoverflow.com/comment/89075228
type: Answer
has body: I think you're getting error because you are using wrong parser, you should use html.parser instead of lxml soup = bs4.BeautifulSoup(res.text, "html.parser") hope this solves the problem
has comment: http://stackoverflow.com/comment/89075175
downvote count: 2
answers question: http://stackoverflow.com/q/51041245
score: -2

http://stackoverflow.com/q/51032986
has comment: http://stackoverflow.com/comment/89061811
has body: I am trying to run some simple code in Kivy. Could someone please help? Note: I have two hard drives installed on my PC, and I am not sure if this could have an effect with the paths. I am new to this. Please have mercy on me! Thank you so much in advance. This is the code that I am trying to run: import kivy from kivy.app import App from kivy.uix.label import Label class SimpleKivy(App): def build(self): return Label(text="Hello World!") if __name__ == "__main__": SimpleKivy().run() Here is the error I am receiving: [INFO ] [Logger ] Record log in C:\Users\Gamer\.kivy\logs\kivy_18-06-25_14.txt [INFO ] [Kivy ] v1.10.0 [INFO ] [Python ] v3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_pil, img_gif (img_sdl2, img_ffpyplayer ignored) [INFO ] [Text ] Provider: pil(['text_sdl2'] ignored) [CRITICAL] [Window ] Unable to find any valuable Window provider. sdl2 - ImportError: DLL load failed: The specified module could not be found. File "E:\Python36\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "E:\Python36\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in &lt;module&gt; from kivy.core.window._window_sdl2 import _WindowSDL2Storage [CRITICAL] [App ] Unable to get a Window, abort. Exception ignored in: 'kivy.properties.dpi2px' Traceback (most recent call last): File "E:\Python36\lib\site-packages\kivy\utils.py", line 496, in __get__ retval = self.func(inst) File "E:\Python36\lib\site-packages\kivy\metrics.py", line 174, in dpi EventLoop.ensure_window() File "E:\Python36\lib\site-packages\kivy\base.py", line 127, in ensure_window sys.exit(1) SystemExit: 1 [CRITICAL] [App ] Unable to get a Window, abort.
linked to: http://stackoverflow.com/q/40697876
has comment: http://stackoverflow.com/comment/89061697
has comment: http://stackoverflow.com/comment/89061577
type: Question
has comment: http://stackoverflow.com/comment/89061823
duplicate of: http://stackoverflow.com/q/40697876
tagged with: window
has title: Python Kivy Error: [CRITICAL] [App ] Unable to get a Window, abort
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89061922
tagged with: kivy
has comment: http://stackoverflow.com/comment/89061829
favorite count: 0
tagged with: python-3.x
tagged with: kivy-language
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89061944
downvote count: 1
has comment: http://stackoverflow.com/comment/89061848
has comment: http://stackoverflow.com/comment/89061930
has comment: http://stackoverflow.com/comment/89061602

azure-iot-sdk
tag name: azure-iot-sdk
type: Tag
tags question: http://stackoverflow.com/q/51068964

http://stackoverflow.com/q/51034264
linked to: http://stackoverflow.com/q/27974126
has title: pairs of elements of a list - Python
score: 0
duplicate of: http://stackoverflow.com/q/27974126
has answer: http://stackoverflow.com/a/51034398
has answer: http://stackoverflow.com/a/51034429
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
type: Question
answer count: 2
has body: Given a list to generate tuples, for example: lst = ['d', '112', 'b', 'c', 'i', 'a', 'e'] output: [('d','112'), ('d','b'), ('d','c'), ('d','i'), ..., ('a','e')] Thanks.

http://stackoverflow.com/q/51013184
has answer: http://stackoverflow.com/a/51013213
duplicate of: http://stackoverflow.com/q/5347065
score: -1
accepted answer: http://stackoverflow.com/a/51013213
tagged with: numpy
has title: Reconstruct numpy array using indexing
upvote count: 0
answer count: 1
tagged with: python
favorite count: 0
has body: I have a numpy array of 3*k elements, where k is an integer. For instance, for k=3 I have the array A. Below, x, y, and z are filled by drawing elements from A as shown in the following example: import numpy as np A = np.arange(9) &gt;&gt; array([0, 1, 2, 3, 4, 5, 6, 7, 8]) x = A[0::3] &gt;&gt; array([0, 3, 6]) y = A[1::3] array([1, 4, 7]) z = A[2::3] &gt;&gt; array([2, 5, 8]) Now, I want to use x, y, and z so as to reconstruct A. Is there any convenient way of doing this without using for loops?
linked to: http://stackoverflow.com/q/5347065
downvote count: 1
type: Question
tagged with: indexing
type: AnsweredQuestion

http://stackoverflow.com/q/51118767
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
score: 23
has answer: http://stackoverflow.com/a/68504845
downvote count: 1
upvote count: 24
has answer: http://stackoverflow.com/a/78546499
has title: What is boto3.client('S3') returning?
has body: I can see: s = boto3.client('s3') print(type(s)) prints &lt;class 'botocore.client.S3'&gt; But if I try print(botocore.client.S3) I get AttributeError: module 'botocore.client' has no attribute 'S3' How come? Side note: My end goal is to return a mock that is speced to what botocore.client.S3 has to offer, but the technical aspect of what is being returned has alluded me for some time, and from knowing that, I'll probably know how to answer my ultimate question.
type: Question
has answer: http://stackoverflow.com/a/68006865
tagged with: boto3
has answer: http://stackoverflow.com/a/61546535
has answer: http://stackoverflow.com/a/74290703
tagged with: python

kivy
tags question: http://stackoverflow.com/q/51105887
tags question: http://stackoverflow.com/q/51038839
type: Tag
tags question: http://stackoverflow.com/q/51141677
tags question: http://stackoverflow.com/q/51093710
tags question: http://stackoverflow.com/q/51032986
tags question: http://stackoverflow.com/q/51107701
tags question: http://stackoverflow.com/q/51039775
tags question: http://stackoverflow.com/q/51167248
tags question: http://stackoverflow.com/q/51136197
tags question: http://stackoverflow.com/q/51098897
tag name: kivy
tags question: http://stackoverflow.com/q/51035619
tags question: http://stackoverflow.com/q/51133631
tags question: http://stackoverflow.com/q/51150145
tags question: http://stackoverflow.com/q/51029714
tags question: http://stackoverflow.com/q/51058694
tags question: http://stackoverflow.com/q/51024190

http://stackoverflow.com/a/51159261
has body: You can use json library to write your dict object to a file. Try this: import json # divdir = conn.extend.standard.paged_search('cn = All.DL Div DSS Directors, ou = Distribution Lists, ou = Exchange, dc=google,dc=corpad,dc=net', '(objectClass=*)', attributes=['member']) divdir={'raw_dn': b'CN=All.DL Div Controllers - National Group,OU=Distribution Lists,OU=Exchange,DC=google,DC=corpad,DC=net', 'dn': 'CN=All.DL Div Controllers - National Group,OU=Distribution Lists,OU=Exchange,DC=google,DC=corpad,DC=net', 'raw_attributes': {'member': [b'CN=gji9847,OU=U02562,OU=02562,DC=google,DC=corpad,DC=net', b'CN=exx8092,OU=U06032,OU=06032,DC=google,DC=corpad,DC=net', b'CN=EWR8386,OU=U09373,OU=09373,DC=google,DC=corpad,DC=net', b'CN=HXU9279,OU=U00704,OU=00704,DC=google,DC=corpad,DC=net', b'CN=KVG6693,OU=U25692,OU=25692,DC=google,DC=corpad,DC=net', b'CN=JCL6495,OU=U01246,OU=01246,DC=google,DC=corpad,DC=net', b'CN=RNE9520,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=PCN5400,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=WPM9271,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', b'CN=JKJ2421,OU=U01692,OU=01692,DC=google,DC=corpad,DC=net']}, 'attributes': {'member': ['CN=gji9847,OU=U02562,OU=02562,DC=google,DC=corpad,DC=net', 'CN=exx8092,OU=U06032,OU=06032,DC=google,DC=corpad,DC=net', 'CN=EWR8386,OU=U09373,OU=09373,DC=google,DC=corpad,DC=net', 'CN=HXU9279,OU=U00704,OU=00704,DC=google,DC=corpad,DC=net', 'CN=KVG6693,OU=U25692,OU=25692,DC=google,DC=corpad,DC=net', 'CN=JCL6495,OU=U01246,OU=01246,DC=google,DC=corpad,DC=net', 'CN=RNE9520,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=PCN5400,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=WPM9271,OU=U01673,OU=01673,DC=google,DC=corpad,DC=net', 'CN=JKJ2421,OU=U01692,OU=01692,DC=google,DC=corpad,DC=net']}, 'type': 'searchResEntry'} with open('test2.txt', 'w') as file: file.write(json.dumps(divdir))
upvote count: 1
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89301812
answers question: http://stackoverflow.com/q/51158992

http://stackoverflow.com/q/51128406
has answer: http://stackoverflow.com/a/51128529
favorite count: 0
linked to: http://stackoverflow.com/q/42981578
tagged with: linux
tagged with: python
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/11774925
has body: I've never created, nor used a cron job before, but what I've gathered from numerous questions and answers on SO is that the process is fairly simple and involves something like the following: Create bash file with shell commands Edit crontab I've found lots of questions and answers on SO regarding cron jobs, but not a single one of them actually explains the syntax. I've tried looking online for a reliable explanation too, but to no avail. I did find this page, however, which explains the time and date portion of crontab statements very clearly. Here's my understanding so far: 1. Create bash script, which can be placed anywhere. #!/bin/bash cd /home/user/public_html/scrapy/projects/myproject/spiders scrapy crawl mycrawler What is the significance of the #!/usr/bin/bash statement? Why is it commented out? Is using a shell script as a proxy even necessary to run Python scripts? 2. Edit crontab via the crontab -e command I've seen so many different recommendations for this part, so I'm going to list a few examples from a few different answers. Example #1 PATH=/usr/bin * 5 * * * cd project_folder/project_name/ &amp;&amp; scrapy crawl spider_name Is embedding commands directly in crontab -e considered good practice? Example #2 */5 * * * * /usr/local/bin/python /home/Documents/SCRAPE_PYTHON/SCRAPE.py &amp;&gt;&gt; /home/Desktop/log.txt What is the significance of the first path, /usr/local/bin/python, in this context? He states in his answer that &amp;&gt;&gt; /home/Desktop/log.txt is the file to which errors and other output will be appended. Is that what the &amp;&gt;&gt; does? Is that universal for every single Linux environment? Example #3 */2 * * * * /home/user/shell_scripts/cj-scrapy.sh How come the above code does not include two paths? Is it a potential security vulnerability to place shell scripts in the /home/user/scripts directory? Is there a specific directory where shell scripts like this are commonly stored? Example #4 The cPanel Cron Job Wizard recommends …
has comment: http://stackoverflow.com/comment/89242060
has title: Cron Job Syntax
type: Question
has comment: http://stackoverflow.com/comment/89241949
linked to: http://stackoverflow.com/q/17235101
score: -2
possible better answer: http://stackoverflow.com/a/51128524
has answer: http://stackoverflow.com/a/51128524
accepted answer: http://stackoverflow.com/a/51128529
has answer: http://stackoverflow.com/a/51128589
downvote count: 2
tagged with: bash
answer count: 3
tagged with: cron
has comment: http://stackoverflow.com/comment/89242032
has comment: http://stackoverflow.com/comment/89241862

http://stackoverflow.com/comment/89352031
comment on: http://stackoverflow.com/a/51174488
has text: This is a great library. It needs more recognition, thanks for the help.
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89272159
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51144004
has text: love it. And StopIteration would be thrown if there are not enough samples for the batch. Thanks a bunch!
type: AnswerComment

statistics
tags question: http://stackoverflow.com/q/51106679
tags question: http://stackoverflow.com/q/51120555
tags question: http://stackoverflow.com/q/51078471
tag name: statistics
tags question: http://stackoverflow.com/q/51150699
tags question: http://stackoverflow.com/q/51072938
tags question: http://stackoverflow.com/q/51093906
tags question: http://stackoverflow.com/q/51122552
tags question: http://stackoverflow.com/q/51126928
tags question: http://stackoverflow.com/q/51156581
tags question: http://stackoverflow.com/q/51076577
type: Tag

http://stackoverflow.com/q/51141674
answer count: 3
tagged with: azure
tagged with: azure-functions
downvote count: 0
has answer: http://stackoverflow.com/a/51148801
accepted answer: http://stackoverflow.com/a/51148801
favorite count: 0
has answer: http://stackoverflow.com/a/51149207
has comment: http://stackoverflow.com/comment/89268022
tagged with: python
upvote count: 4
type: AnsweredQuestion
has title: Azure timer trigger function using Python
has body: I am writing an Azure timer trigger using Python 3.x. I've got one such function running. I think I know to do it, create one from JS and then delete the 'index.js' and create a run.py. But this time, when I run my python function, I always got an error saying "No such file: index.js". I didn't see any bonds between the function and the 'index.js' file. Any thoughts?
type: Question
possible better answer: http://stackoverflow.com/a/51149207
has answer: http://stackoverflow.com/a/66828786
score: 4
has comment: http://stackoverflow.com/comment/89268845

http://stackoverflow.com/q/51124878
type: UnansweredQuestion
type: Question
has body: I've been looking an so far have been unable to find any way of enabling syntax highlighting for jenkinsfile in PyCharm. Does anyone know of a method to do this? I am specifically using scripted pipeline.
upvote count: 38
has answer: http://stackoverflow.com/a/56305378
has answer: http://stackoverflow.com/a/56991005
score: 37
has comment: http://stackoverflow.com/comment/89234821
has answer: http://stackoverflow.com/a/53898818
tagged with: jenkins-pipeline
tagged with: jetbrains-ide
favorite count: 0
linked to: http://stackoverflow.com/q/46727957
answer count: 5
has title: Jenkinsfile syntax highlighting in PyCharm Idea
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89235071
has answer: http://stackoverflow.com/a/56749404
tagged with: pycharm
tagged with: jenkins
has answer: http://stackoverflow.com/a/60671348

http://stackoverflow.com/comment/89025923
score: 0
comment on: http://stackoverflow.com/q/51016696
type: QuestionComment
type: Comment
has text: Why not create `summary` before the `with`, then only use the `with` block to do the actual writing?

http://stackoverflow.com/q/51097981
tagged with: pandas
upvote count: 7
has body: I'm trying to fill a column of a dataframe from another dataframe based on conditions. Let's say my first dataframe is df1 and the second is named df2. # df1 is described as bellow : +------+------+ | Col1 | Col2 | +------+------+ | A | 1 | | B | 2 | | C | 3 | | A | 1 | +------+------+ And # df2 is described as bellow : +------+------+ | Col1 | Col2 | +------+------+ | A | NaN | | B | NaN | | D | NaN | +------+------+ Each distinct value of Col1 has her an id number (In Col2), so what I want is to fill the NaN values in df2.Col2 where df2.Col1==df1.Col1 . So that my second dataframe will look like : # df2 : +------+------+ | Col1 | Col2 | +------+------+ | A | 1 | | B | 2 | | D | NaN | +------+------+ I'm using Python 2.7
tagged with: python
has title: Fill column of a dataframe from another dataframe
has answer: http://stackoverflow.com/a/51098048
downvote count: 0
possible better answer: http://stackoverflow.com/a/51101150
has comment: http://stackoverflow.com/comment/89183571
type: AnsweredQuestion
score: 7
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51101150
favorite count: 0
accepted answer: http://stackoverflow.com/a/51098048

http://stackoverflow.com/comment/89124053
type: QuestionComment
has text: Can you post what problem are you facing after you tried your solution? It is always good to do so.
score: 1
comment on: http://stackoverflow.com/q/51067061
type: Comment

snappy
type: Tag
tag name: snappy
tags question: http://stackoverflow.com/q/51139748

http://stackoverflow.com/comment/119673116
score: 0
comment on: http://stackoverflow.com/a/60189988
type: AnswerComment
has text: I guess this is the nicest solution in most circumstances
type: Comment

pose-estimation
tag name: pose-estimation
tags question: http://stackoverflow.com/q/51089781
type: Tag

http://stackoverflow.com/comment/89316008
comment on: http://stackoverflow.com/q/51147228
score: 0
has text: I think you misread my post bro. I haven't said anything about "inline-comment recommendation" and I understand fully what "inline-comment" is. But I have asked about what do to with that when I don't wanna use block comment.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51100054
favorite count: 0
has comment: http://stackoverflow.com/comment/89188817
tagged with: python
has comment: http://stackoverflow.com/comment/89189111
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
has title: Plateauing loss in neural style transfer
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89190281
has body: I am writing an implementation of style transfer by loading a vgg model from keras and supplying it to a tensorflow model. I am using an adam optimizer. The loss function is reducing but it is very slow and plateaus off at about 108. Also the style loss is huge (order of 108) whereas content loss is much smaller(order of 105). This is weird as the paper for style transfer says to scale content loss down by a factor of 100 or 1000 when calculating total loss. I tried increasing the learning rate but that only makes the gradient overshoot. I suspect there must be a bug in my implementation but despite searching endlessly I have been unable to find what's wrong. Here's the code: # coding: utf-8 # In[1]: from keras.applications.vgg16 import VGG16 from keras.models import Model import tensorflow as tf import tensorflow.contrib.eager as tfe import numpy as np import matplotlib.pyplot as plt # In[2]: content_image_path = './skyline.jpg' style_image_path = './starry_night.jpg' output_image_path = './output.jpg' # In[4]: from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input # In[5]: content_image = image.load_img(content_image_path, target_size=(224, 224)) #plt.imshow(content_image) content_arr = image.img_to_array(content_image) content_arr = tf.convert_to_tensor(preprocess_input(np.expand_dims(content_arr, axis=0)), tf.float64) sess.run(tf.shape(content_arr)) # In[6]: style_image = image.load_img(style_image_path, target_size=(224, 224)) #plt.imshow(style_image) style_arr = image.img_to_array(style_image) style_arr = tf.convert_to_tensor(preprocess_input(np.expand_dims(style_arr, axis=0)), tf.float64) sess.run(tf.shape(style_arr)) # In[7]: #generate random image with pixel values b/w 0 -&gt; 255 o_input = np.random.randint(low=0, high=256, size=(224, 224, 3)).astype('float64') plt.imshow(o_input) o_input_old = np.copy(o_input) o_input = preprocess_input(np.expand_dims(o_input, axis=0)) print(o_input_old) o_input_var = tf.Variable(o_inp…
tagged with: deep-learning
downvote count: 0
tagged with: keras

http://stackoverflow.com/comment/89273462
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51142427
has text: Thank you for the detailed explanation. Even my initial question didn’t provide detail of how I am using this code, but I think it’s still worth it. I am learning much more than counting \n. I understand I can count \n in binary mode, and I am reading “whole line” today. Understand how to deal with utf8 will also help me in the future if I do not have option to looking for line break char.

http://stackoverflow.com/comment/89085353
has text: There have been SO questions about handling general `key=value` strings. While answers vary in details, the basic idea is that you have to parse such strings yourself - split on '=', etc. If that's all you want to parse, skip `argparse` and work with `sys.argv` directly.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51031169

http://stackoverflow.com/q/51111500
answer count: 2
has answer: http://stackoverflow.com/a/51111588
score: 0
tagged with: python
has title: How to skip one or more cells when pasting content into an Excel by using Openpyxl?
tagged with: highlight
has body: I'm trying paste texts into a column of an existing excel. However, I need to skip all the highlighted cells. For example: content.txt 1 2 3 4 5 workbook.xlsx should look like Below are the codes I have so far: import os, openpyxl f = open("content.txt", mode="r+") wb = openpyxl.load_workbook(filename = 'workbook.xlsx') worksheet = wb.active r = 1 for line in f.readlines(): if worksheet.cell(row=r, column=9).fill.bgColor.value != '00000000': r+=1 worksheet.cell(row=r, column=1).value = line r+=1 continue else: worksheet.cell(row=r, column=1).value = line r += 1 f.close() But it only skips one highlighted row..I'm still trying to figure it out though. Or if I write the code like this: import os, openpyxl f = open("content.txt", mode="r+") wb = openpyxl.load_workbook(filename = 'workbook.xlsx') worksheet = wb.active r = 1 for line in f.readlines(): if worksheet.cell(row=r, column=9).fill.bgColor.value != '00000000': r+=1 continue else: worksheet.cell(row=r, column=1).value = line r += 1 f.close() The result would be: (The txt line are also skipped...) Let me know if you have any ideas. Should i use a while loop...? Thank you!!
type: UnansweredQuestion
tagged with: excel
type: Question
tagged with: text
tagged with: row
has answer: http://stackoverflow.com/a/51127566

http://stackoverflow.com/comment/89094392
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51051619
score: 0
has text: Sounds strange. Where are you reading the data from?

http://stackoverflow.com/a/51170007
answers question: http://stackoverflow.com/q/51164281
score: 1
upvote count: 1
has body: To get scikit-learn/sklearn or any other packages to work in the pycharm, your python interpreter configured for pycharm must find those installed packges and other dependencies. The specific error in given example might be due to absence of development tools such as gcc and make. Before installing the packages try to run following command (assuming it's ubuntu linux) - sudo apt-get install build-essential For other distros see here Also, you can also install packages that pycharm python interpreter can find from settings.
downvote count: 0
type: Answer

http://stackoverflow.com/a/51110592
answers question: http://stackoverflow.com/q/51110497
has body: Something is off - you should be getting some kind of error when trying to send some integer in the socket: &gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) &gt;&gt;&gt; s.connect(('localhost', 7777)) &gt;&gt;&gt; s.sendall(len(b'some bytes')) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: a bytes-like object is required, not 'int' Sockets can only send bytes, you have to convert the int object containing the size to bytes somehow, python won't do it automatically for you. Your code should fail with the error above. In the java code you are using asIntBuffer() and Integer.toBinaryString to convert your values, in the python code you just try to send the data without converting, you should get error. Now, to convert the int to bytes, you can use the struct module; It will convert to a binary representation used by the C language - I think that's what your java code expect size_in_bytes = struct.pack('I', len(data_to_send)) In the same way, you should use struct.unpack to convert the bytes back to a integer object. See the documentation for more details and a table of possible conversions.
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/89116467
type: QuestionComment
has text: Can you share the sample xml to work on?
score: 0
comment on: http://stackoverflow.com/q/51059958
type: Comment

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/51052785

http://stackoverflow.com/comment/91245529
has text: Did you ever figure this out?
type: QuestionComment
comment on: http://stackoverflow.com/q/51064261
score: 0
type: Comment

http://stackoverflow.com/q/51095634
tagged with: python
downvote count: 6
has comment: http://stackoverflow.com/comment/89179019
tagged with: list
has body: def print_list(x): for a in x: print(x) c = [1, 2, 4, 5, 6] print(print_list(c)) Output: [1, 2, 4, 5, 6] [1, 2, 4, 5, 6] [1, 2, 4, 5, 6] [1, 2, 4, 5, 6] [1, 2, 4, 5, 6] In my textbook, it says that the code should simply generate the list however, in my console the list repeats 5 times and I used my debugger to see why it does that but it still does not illustrate how the output is 5 lines of the list. Help?
type: Question
has answer: http://stackoverflow.com/a/51096215
has answer: http://stackoverflow.com/a/51095666
has title: Python lists and for in Statements
has answer: http://stackoverflow.com/a/51095660
upvote count: 0
has answer: http://stackoverflow.com/a/51095744
score: -6
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51095661

http://stackoverflow.com/a/51095319
downvote count: 0
has body: Why not just this: df['MonthYear'] = pd.to_datetime(df'Year', 'Month'.assign(Day=1)).dt.strftime('%m-%Y') print(df) Output: Sr. Month Year MonthYear 0 1.0 3.0 2015.0 03-2015 1 2.0 6.0 2018.0 06-2018 2 3.0 9.0 2017.0 09-2017 3 4.0 NaN NaN NaT 4 5.0 5.0 2015.0 05-2015
type: Answer
answers question: http://stackoverflow.com/q/51095085
upvote count: 2
score: 2

http://stackoverflow.com/comment/113016493
score: 0
comment on: http://stackoverflow.com/q/51014376
type: QuestionComment
has text: Yup, len and count are indeed different. However, either way, it was still much faster to summarize data than groupby().describe()
type: Comment

http://stackoverflow.com/comment/89090265
score: 1
comment on: http://stackoverflow.com/q/51047568
type: Comment
type: QuestionComment
has text: As said, add `else: print "unknown type" + str(body_type)`, then raise an error message yourself.

http://stackoverflow.com/q/51021768
has body: I am trying to perform Fourier transform using numpy's fft as follows: import numpy as np import matplotlib.pyplot as plt t = np.linspace(0,1, 128) x = np.cos(2*np.pi*t) s_fft = np.fft.fft(x) s_fft_freq = np.fft.fftshift(np.fft.fftfreq(t.shape[-1], t[1]-t[0])) plt.plot(s_fft_freq, np.abs(s_fft)) The result I get is which is wrong, as I know the FT should peak at f = 1, as the frequency of the cos is 1. What am I doing wrong?
answer count: 2
has answer: http://stackoverflow.com/a/51022678
possible better answer: http://stackoverflow.com/a/51022569
has comment: http://stackoverflow.com/comment/89036525
favorite count: 0
tagged with: fft
has title: `fft` not returning what it should
has comment: http://stackoverflow.com/comment/89036718
tagged with: python
accepted answer: http://stackoverflow.com/a/51022678
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/89036845
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51022569

http://stackoverflow.com/q/51163175
favorite count: 0
has comment: http://stackoverflow.com/comment/89309744
tagged with: python-3.x
has title: How to take mean of one column while filtering by another column's criteria in python
has comment: http://stackoverflow.com/comment/89309706
linked to: http://stackoverflow.com/q/30482071
has comment: http://stackoverflow.com/comment/89309738
tagged with: python
accepted answer: http://stackoverflow.com/a/51163276
has comment: http://stackoverflow.com/comment/89309829
duplicate of: http://stackoverflow.com/q/30482071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89309719
upvote count: 1
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/51163276
tagged with: numpy
tagged with: pandas
has comment: http://stackoverflow.com/comment/89309817
has comment: http://stackoverflow.com/comment/89309715
answer count: 1
downvote count: 0
score: 1
has body: I am working in Python (normally an R guy) and I am trying to create this function for a specific application. Basically, I am trying to take the mean of the column "CallsPresented" for each month in the "Month_of_Year" column. I know I am making this more complex than I need to. How should I accomplish this? def get_monthly_mean(df): avg_by_month = [] months = ['Jan', 'Feb', 'Mar', 'Apr', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] for i in range(11): x = np.mean(df['CallsPresented'][df.loc[df['Month_of_Year'] == months[i]]]) avg_by_month.append(x) return months

http://stackoverflow.com/a/51116107
answers question: http://stackoverflow.com/q/51115171
has body: You can use flask_weasyprint: from flask_weasyprint import HTML, render_pdf import flask app = flask.Flask(__name__) @app.route('/users') def users(): cur = mysql.connection.cursor() resultValue = cur.execute("SELECT * from users") if resultValue &gt; 0: userDetails = cur.fetchall() html = render_template('users.html', userDetails=userDetails) return render_pdf(HTML(string=html)) Now, once the user navigates to /users, the download will start.
has comment: http://stackoverflow.com/comment/97823095
has comment: http://stackoverflow.com/comment/89226758
score: 3
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/comment/89120913
type: Comment
type: QuestionComment
has text: Can you show us what you have so far!
comment on: http://stackoverflow.com/q/51065473
score: 0

http://stackoverflow.com/comment/89070765
has text: Yes, but when i am running this it shows pymaps has no attribute maps.
type: Comment
comment on: http://stackoverflow.com/a/51035938
score: 0
type: AnswerComment

http://stackoverflow.com/q/51039749
tagged with: machine-learning
tagged with: python
score: 2
answer count: 0
tagged with: text-classification
tagged with: tensorflow
type: Question
has body: I'm trying to do almost the same thing as Tensorflow DNN with tf-idf sparse matrix However, I'm trying to make a custom estimator. I've followed most of what he has done, input: (&lt;tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x125fd6b70&gt;, &lt;tf.Tensor 'IteratorGetNext:1' shape=(?, 34549) dtype=int64&gt;) feature columns: [_NumericColumn(key='\x03', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None), _NumericColumn(key='\x08', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None), _NumericColumn(key='\t', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None), _NumericColumn(key='\x0b', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None) getting sparse tensor: def convert_sparse_matrix_to_sparse_tensor(X): coo = X.tocoo() indices = np.mat([coo.row, coo.col]).transpose() return tf.SparseTensorValue(indices, coo.data, coo.shape) input function: def inputs_fn(X,y): dataset = tf.data.Dataset.from_tensors((X,y)) dataset = dataset.shuffle(1000).repeat().batch(500) return dataset.make_one_shot_iterator().get_next() getting feature column keys: feature_cols = [] for key in feature_names: feature_cols.append(tf.feature_column.numeric_column(key=key)) input layer (effectively lifted off the tensorflow site): def my_model_fn( features, # This is batch_features from input_fn labels, # This is batch_labels from input_fn mode, params ): # Instance of tf.estimator.ModeKeys, see below #feature_cols = [tf.feature_column.embedding_column(categorical_column=key, dimension=1) for key in feature_names] input_layer = tf.feature_column.input_layer(features, params['feature_columns']) Lambda the input function and initialise: X = convert_sparse_matrix_to_sparse_tensor(X) print(inputs_fn(X,y) , 'INPUTS ARE CORRECTLY IN TUPLE FORM') input = lambda : inputs_fn(X,y) classifier = tf.estimator.Estimator(model_fn=my_model_fn,params={'feature_columns':feature_cols},model_dir='/checkpoints') classifier.tra…
downvote count: 0
linked to: http://stackoverflow.com/q/48530028
has title: Custom estimator using sparse matrix
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/130291644
score: 1
has text: This behavior of 0-d arrays numpy is extremely unintuitive (and hard to discover). This could be fixed by changing the `IndexError` message for 0-D arrays to `IndexError: …; Use x[()] or x.item() to extract the value from a 0-D array.`
comment on: http://stackoverflow.com/a/51158317
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51029478
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/51029414
upvote count: 6
answers question: http://stackoverflow.com/q/51029414
has body: The interactive shell is an example of a more general concept called a REPL, which stands for: Read Evaluate Print Loop The P above is the difference between the interactive shell and a regular script. The shell is calling print for you.
has comment: http://stackoverflow.com/comment/89051308
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89088987
comment on: http://stackoverflow.com/a/51021711
score: 0
type: Comment
has text: it is not showing scrapy in pip list. buti hv installed it. now what should i do to place it on that list Now i tried to install scrapy in my Python/Scripts folder by setting path in cmd and i am getting error "error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools" - @Meghana Goud
type: AnswerComment

http://stackoverflow.com/comment/89131570
comment on: http://stackoverflow.com/q/51070743
score: 0
type: Comment
type: QuestionComment
has text: Please edit that link, and an explanation, into your question instead of just leaving it as a comment. Also, fix the formatting—to post code in a question, you should select the code and hit the `{}` icon or Ctrl-K.

http://stackoverflow.com/comment/89165336
score: 0
type: Comment
has text: @Spinor8, OK, this should work now, we can just use `zip` with `df[col]` and `df[col].cat.codes`, a bit messy but the docs are also messy.
comment on: http://stackoverflow.com/a/51087590
type: AnswerComment

http://stackoverflow.com/comment/89218331
has text: Glad I could help – and good thing the most basic solution worked! (Per the possible reasons it could *not* have worked.) If you run into one of those reasons need help with fine-tuning the `tag_visible` function, just say so. It would probably need an example of your HTML.
type: QuestionComment
comment on: http://stackoverflow.com/q/51115590
score: 0
type: Comment

http://stackoverflow.com/comment/89183056
comment on: http://stackoverflow.com/a/51097616
has text: Its strange when i check on repl.it space it coming but not in my pycharm
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/56870739
upvote count: 3
has body: The solution you're looking for is : round(df.isnull().mean()*100,2) This will round up the percentage upto 2 decimal places Another way to do this is round((df.isnull().sum()*100)/len(df),2) but this is not efficient as using mean() is.
type: Answer
answers question: http://stackoverflow.com/q/51070985
score: 3
downvote count: 0

http://stackoverflow.com/comment/89189099
type: Comment
has text: I just want that the should get accessible through the custom symbol in MT5. If this gets possible then backtest and rest things are already done as far as I know.
score: 0
comment on: http://stackoverflow.com/q/51061059
type: QuestionComment

http://stackoverflow.com/comment/89168700
has text: Does anyone know if it's allowed to post automatic content for the page owner (of course this is his choice to do so or to disable it and it only promotes his own business, so it is definitely content for the facebook page owner)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51022550
score: 0

http://stackoverflow.com/q/51076652
favorite count: 0
tagged with: precision
has comment: http://stackoverflow.com/comment/89143741
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/89181157
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89142649
has comment: http://stackoverflow.com/comment/89144477
has answer: http://stackoverflow.com/a/51076847
tagged with: equality
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/89142729
has body: Why do the elements in the numpy arrays not equal each other? This is my env: jupyter QtConsole 4.3.1 Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08) Type "copyright", "credits" or "license" for more information. IPython 5.3.0 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details. import sys print(sys.version) print np.__version__ 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] 1.12.1 This is how I get both arrays: A = np.array([[2., 3.], [10., 1.]]) rprime = np.array([[8.], [13.]]) A_inv = np.linalg.inv(A) r = np.dot(A_inv, rprime) As you can see they look the same: np.dot(A, r) Out[72]: array([[ 8.], [ 13.]]) rprime Out[73]: array([[ 8.], [ 13.]]) But when I compare them, they are not: np.dot(A, r) == rprime Out[74]: array([[False], [False]], dtype=bool) The shapes and types are all the same: print type(np.dot(A, r)) print type(rprime) print type(np.dot(A, r)[0, 0]) print type(rprime[0, 0]) print type(np.dot(A, r)[1, 0]) print type(rprime[1, 0]) print np.dot(A, r).shape print rprime.shape &lt;type 'numpy.ndarray'&gt; &lt;type 'numpy.ndarray'&gt; &lt;type 'numpy.float64'&gt; &lt;type 'numpy.float64'&gt; &lt;type 'numpy.float64'&gt; &lt;type 'numpy.float64'&gt; (2, 1) (2, 1) When I use allclose I get true: np.allclose(np.dot(A, r), rprime) Out[76]: True What I am trying to understand is why they are not considered identical? Addition: It must have to do with the exact floats stored in the matrices: np.round(np.dot(A, r),0) == np.round(rprime,0) Out[81]: array([[ True], [ True]], dtype=bool) Still, trying to understand what exactly is going on.
linked to: http://stackoverflow.com/q/21895756
tagged with: python
duplicate of: http://stackoverflow.com/q/21895756
has title: numpy matrices do not equal even though they look the same
has answer: http://stackoverflow.com/a/51076841

http://stackoverflow.com/a/51058864
answers question: http://stackoverflow.com/q/51057351
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89136167
has body: I think need add DataFrame contructor to function and then add another column name to groupby like ["Model", "Mode(denote as 0 or 2)"] or ["Model", "Mode"] by columns names: def haversine(lat1,lon1,lat2,lon2, to_radians = True, earth_radius =6371): if to_radians: lat1,lon1,lat2,lon2 = np.radians([lat1,lon1,lat2,lon2]) a = np.sin((lat2-lat1)/2.0)**2+ np.cos(lat1) * np.cos(lat2) * np.sin((lon2- lon1)/2.0)**2 return pd.DataFrame(earth_radius *2 * np.arcsin(np.sqrt(a))) mydataset['dist'] = (mydataset.groupby(["Model", "Mode(denote as 0 or 2)"]) .apply(lambda x: haversine(x['Lat'], x['Long'], x['Lat'].shift(), x['Long'].shift())).values) #if need replace NaNs to 0 mydataset['dist'] = mydataset['dist'].fillna(0) print (mydataset) Index Model Timestamp Long Lat \ 0 1 X 2018-01-18 09:16:37.070 103.877728 1.356535 1 2 X 2018-01-18 09:16:39.071 103.877728 1.356535 2 3 X 2018-01-18 09:16:41.071 103.877728 1.356535 3 4 X 2018-01-18 09:16:43.071 103.877721 1.356535 4 5 X 2018-01-18 09:16:45.071 103.877705 1.356533 5 6 X 2018-01-18 09:16:51.070 103.877705 1.356533 6 7 X 2018-01-18 09:16:53.071 103.877705 1.356533 7 8 X 2018-01-18 09:59:55.072 103.877705 1.356528 Mode(denote as 0 or 2) Distance Calculated dist 0 0 0.000000 0.000000 1 0 0.000000 0.000000 2 0 0.000000 0.000000 3 0 0.000848 0.000848 4 0 0.001706 0.001706 5 2 0.000000 0.000557 6 2 0.000000 0.000000 7 0 0.000557 0.000000
has comment: http://stackoverflow.com/comment/89195393
score: 0
type: Answer

http://stackoverflow.com/comment/89038633
comment on: http://stackoverflow.com/q/51023113
has text: Try `np.concatenate((data, other_data))`. `concatenate` takes a tuple input.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/51134179
type: Question
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51134468
downvote count: 0
accepted answer: http://stackoverflow.com/a/51134220
has answer: http://stackoverflow.com/a/51134468
score: 1
favorite count: 0
has body: i want to pivot a table based on one column and with index as two columns, Dataset: uid interaction date 1 like 2016-12-04 1 like 2016-12-05 1 comment 2016-12-05 1 like 2016-12-05 2 like 2016-12-04 2 like 2016-12-05 2 comment 2016-12-05 2 like 2016-12-05 using uid and date i want to the number of interaction happened for the particular uid on the particular date. final result: uid like comment date 1 1 0 2016-12-04 1 2 1 2016-12-05 2 1 0 2016-12-04 2 2 1 2016-12-05 Approach which i tried: doc_social_interaction.pivot_table(index = ['uid','date'],columns = 'interaction', aggfunc=sum)
has title: Pandas Pivot on one column with multindex
tagged with: python
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51134220

http://stackoverflow.com/a/51152452
type: Answer
has comment: http://stackoverflow.com/comment/89288765
has comment: http://stackoverflow.com/comment/89289483
has comment: http://stackoverflow.com/comment/89293337
accepted answer of: http://stackoverflow.com/q/51151941
downvote count: 0
answers question: http://stackoverflow.com/q/51151941
score: 1
has body: From the documentation of Conv2DTranspose you can see that filters is a positional argument and is supposed to be an integer. This integer specifies the number of filters you want in your layer. The next parameter is kernel_size (also positional) which specifies the shape of your filter. I think what you were looking for is : model.add(Conv2DTranspose(n_filt, (2700, 1), activation='relu' input_shape = (1, 1, 1,))) where n_filt is the number of transposed convolution filters in your layer. Notes : Don't provide the batch dimension in the input_shape argument, or use batch_input_shape instead. Edit to clarify : If your data batch has dimensions (batch_size, dim1, dim2, dim3), you should pass either input_shape = (dim1, dim2, dim3, ) (Notice the comma before the last whitespace) or batch_input_shape = (batch_size, dim1, dim2, dim3). I recommend using input_shape as you won't have any constraints on the batchsize you want to use. Positional arguments cannot be specified with keywords i.e don't use filters = ... in the function call if filters is a positional argument.
has comment: http://stackoverflow.com/comment/89288932
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51092362
has answer: http://stackoverflow.com/a/51092503
has body: I am trying to keep clicking to next page on this website, each time appending the table data to a csv file and then when I reach the last page, append the table data and break the while loop Unfortunately, for some reason it keeps staying on the last page, and I have tried several different methods to catch the error while True: try : WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Next'))).click() except : print("No more pages left") break driver.quit() I also tried this one: try: link = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,'.pagination-next a'))) driver.execute_script('arguments[0].scrollIntoView();', link) link.click() except: keep_going = False I've tried putting print statements in and it just keeps staying on the last page. Here is the HTML for the first page/last page for the next button, I'm not sure if I could do something utilizing this: HTML for first page: Next Next HTML for last page: Next Next
has answer: http://stackoverflow.com/a/51106963
has answer: http://stackoverflow.com/a/51093789
answer count: 4
type: AnsweredQuestion
score: 3
has title: Selenium clicking to next page until on last page
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51106963
tagged with: python
possible better answer: http://stackoverflow.com/a/51094539
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/51094539
tagged with: selenium-chromedriver
upvote count: 3
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/comment/89083744
comment on: http://stackoverflow.com/a/51046130
score: 0
has text: @user2357112 It's a long time since I actively wrote Java, but back then, everything had to be wrapped in a class, and I'm not aware that you can trigger Code execution simply by loading a class without either instantiating it or calling one of its static methods.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51123449
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51123415
type: Answer
answers question: http://stackoverflow.com/q/51123415
has comment: http://stackoverflow.com/comment/89233170
has body: You can use the redirect helper. Pay particular attention to the second example: from django.shortcuts import redirect def my_view(request): try: ... except: return redirect('url-name-from-urls', foo='bar') The url name 'url-name-from-urls' should match the name= keyword argument that you've given to a url in urls.py. For example: from django.shortcuts import redirect def my_view(request): try: ... except: return redirect('detail') Would redirect to your FnDetails view, because it matches the name='detail' url.
upvote count: 1
score: 1
type: AcceptedAnswer

continuous-integration
tags question: http://stackoverflow.com/q/51033827
tag name: continuous-integration
tags question: http://stackoverflow.com/q/51127635
type: Tag
tags question: http://stackoverflow.com/q/51145554

http://stackoverflow.com/a/51097276
score: 2
has comment: http://stackoverflow.com/comment/89183033
has comment: http://stackoverflow.com/comment/89183105
has comment: http://stackoverflow.com/comment/89182867
has comment: http://stackoverflow.com/comment/89182779
has comment: http://stackoverflow.com/comment/89183079
downvote count: 0
has comment: http://stackoverflow.com/comment/89183042
has comment: http://stackoverflow.com/comment/89182324
has comment: http://stackoverflow.com/comment/89182338
has body: I think need: df1 = (df.drop_duplicates(['Contract_type', 'ID']) .set_index('Contract_type')['Unit_Weight'] .sum(level=0) .reset_index()) print (df1) Contract_type Unit_Weight 0 Other 335 1 Type-I 119 2 Type-II 642 3 Type-III 165 4 Part-time 330 5 Full-time 740
answers question: http://stackoverflow.com/q/51097173
upvote count: 2
has comment: http://stackoverflow.com/comment/89182642
type: Answer

http://stackoverflow.com/comment/89077178
type: Comment
type: QuestionComment
has text: Just a question: why did you one-hot encode the hour of the day and the month of the year? These are numeric variables so it would seem to make more sense to leave them as numbers. This would also cut down on the number of features you have!
score: 0
comment on: http://stackoverflow.com/q/51042474

http://stackoverflow.com/q/51048821
answer count: 1
has title: changing x label in python
tagged with: python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51049033
type: Question
tagged with: matplotlib
has body: I am new to python so I apologize if this if this will sound like a silly question. I am trying to change a the title of the x axis in a plot ,from what I read if you use subplots the you need to use set_xlabel('X Axis') command but for some reason this is not working for me. plot=plt.subplots(); dftemp=dftemp.set_index('Date2'); plot=dftemp['yield_bruto_percent'].plot(kind='bar',color="lightgray",title=dftemp['paper_name'][1][::-1]+' ינוציח-ימינפ גוריד ',figsize=(8,4),legend=True) plot=dftemp['dirug_mnpik_psagot'].plot(secondary_y=True,legend=True); plot=dftemp['final_score'].plot(secondary_y=True,legend=True); plot=dftemp['dirug_manpik_hitzoni'].plot(secondary_y=True,legend=True,rot=45); plot.set_xlabel('X Axis') when I run this code the label does not change and the label appears as the name of variable which is the index in my data set. This is the message i get &lt;matplotlib.text.Text at 0x23735e70390&gt; any suggestions would be highly appreciated.

http://stackoverflow.com/comment/89121032
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51065181
has text: are all your columns named with 'Result' and 'Attribute' with a number after or it's just in your example?

http://stackoverflow.com/q/51086375
has title: Python Input validation - positive float or int accepted
has answer: http://stackoverflow.com/a/51087196
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
has body: seems we are asking a lot, but we are seeking a short validation for positive int or float being entered as input. The code below rejects negative, text and null entries - yay! It accepts int as valid, but why doesn't entry like 1.1 pass? (seemingly a positive numeric entry) We want entry of positive 1 and 1.1 to pass. is there an easy way without two separate blocks, including try/catch? bookPrice = input("What is the cost of your book? &gt;&gt; ") while bookPrice.isnumeric() is False or float(bookPrice) &lt; 0: bookPrice = input("Use whole # or decimal, no spaces: &gt;&gt; ") bookPrice = float(bookPrice) print("Your book price is ${0:&lt;.2f}.".format(bookPrice))
has comment: http://stackoverflow.com/comment/94461120
tagged with: validation
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
tagged with: input
tagged with: python

http://stackoverflow.com/comment/89150088
comment on: http://stackoverflow.com/a/51080564
score: 0
type: AnswerComment
type: Comment
has text: @M.irfan this is for one _input_ file, which splits the contents of `'part_candidates'` down into individual files. There's no reason you can't extend this to multiple input files but the code won't blow up your computer if you make some attempts on your end to solve this problem yourself. Just try things out - you'll get a better understanding that way :)

http://stackoverflow.com/comment/89076124
comment on: http://stackoverflow.com/a/51042286
has text: Yep positive! I tried re-pasting the code I initially posted also. I'll update my post to include your modification. I'll also provide a screen shot of the db/table in case I am missing something there.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89058742
type: Comment
comment on: http://stackoverflow.com/a/51031236
has text: Appreciated! Thanks.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51120850
tagged with: mask
has comment: http://stackoverflow.com/comment/89227155
type: Question
tagged with: homography
has comment: http://stackoverflow.com/comment/89227168
has title: How to add something like a virtual billboard in a video with python
score: 0
has body: Virtual billboard is commonly used in sports broadcasting. These billboards is not real and will covered by the moving objects in front of them just like it's right there. I'm wondering is it possible to do this via python? Take this video as an example. (you can download it through this.) Can we add something above the lane but below the vehicles? Let's say this simple yellow rectangle: Add it to a lane will be something like this: And when the vehicles passed this yellow area, the area should be covered by the vehicles rather than cover the vehicle. Before dealing with video, what I'm trying is first using homography and some wrapping to add the rectangle onto and fit the lane area in a picture with the following code: import cv2 import numpy as np # source image source_img = cv2.imread('yellow_rec.jpg') size = source_img.shape # get four corners of the source (clock wise) pts_source = np.array( [ [0,0], [size[1] - 1, 0], [size[1] - 1, size[0] -1], [0, size[0] - 1 ] ],dtype=float ) #pts_source = np.array([[310,0], [440,0], [589,151],[383,151]]) # destination image dst_img = cv2.imread('video_screen_shot.png') # four corners in destination image (also clock wise): pts_dst = np.array([[400,115], [531,108], [647,186],[533,244]]) # calculate homography h, status = cv2.findHomography(pts_source, pts_dst) # warp source image to destination based on homography temp = cv2.warpPerspective(source_img, h, (dst_img.shape[1], dst_img.shape[0])) # Black out polygonal area in destination image. cv2.fillConvexPoly(dst_img, pts_dst.astype(int), 0, 16) # Add warped source image to destination image. dst_img = dst_img + temp cv2.imshow('warpped', dst_img) cv2.waitKey(0) Which gives me: However, if I do this on every video frame, the yellow area will just cover the vehicles passing it rather than being coverred by the vehicles. How could I make it like a virtual billboard, which will be covered by the moving objects in the video?
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: opencv

http://stackoverflow.com/a/51133794
type: Answer
has body: Please download and install Oracle Client. (There are several editions of Oracle Client, but the instant one will do): http://download.oracle.com/otn/nt/instantclient/122010/instantclient-basic-nt-12.2.0.1.0.zip Once it is installed, the cx_Oracle python module will look for the Oracle libs (OCI) and load them.
has comment: http://stackoverflow.com/comment/89321344
score: 1
has comment: http://stackoverflow.com/comment/89335215
answers question: http://stackoverflow.com/q/51126056
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/51105532
has body: Everybody is missing the point. While there are some better ways to do it, nobody is pointing the real error on your code: Since you want the variable to be ascii letters, it can't be any of those conditions, so you want to use the and boolean operator, not or: if var not in r_lower and var not in r_upper and var != 32: That will work fine.... If you want to use or then the conditions change: if not(var in r_lower or var in r_upper or var == 32):
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51104530
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51104530
upvote count: 3
type: Answer

http://stackoverflow.com/comment/89068448
type: Comment
comment on: http://stackoverflow.com/q/51038364
score: 0
type: QuestionComment
has text: Which zip-file did you download? Did you tried to unpack it? Is there a README.txt file or similar? Did you read it?

http://stackoverflow.com/comment/89151045
comment on: http://stackoverflow.com/q/51080191
score: 0
type: Comment
type: QuestionComment
has text: List size < 5000, n and all the other integers -10^9 up to 10^9

http://stackoverflow.com/comment/89146666
type: QuestionComment
has text: @Priyal Gosar: Can you use the Python module outside of the ROS package? E.g. can you import it in an interactive Python terminal?. As I wrote above, there should be no need for doing anything special in the ROS package.
comment on: http://stackoverflow.com/q/51031359
score: 0
type: Comment

http://stackoverflow.com/a/51125608
answers question: http://stackoverflow.com/q/51125568
accepted answer of: http://stackoverflow.com/q/51125568
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89236076
type: Answer
has body: There are two mathematical operators used here: // represents floor division, i.e. extract the integer portion of the result after division. % represents modulus, i.e. the remainder after division. Therefore, for n = 808, the algorithm returns: str(808 // 60 * 100 + 808 % 60) = str(13 * 100 + 28) = '1328' map(int, '1328') then takes each character in the string '1328' and converts it into an integer, itself returning an iterable. map requires an iterable as its second (and subsequent) arguments. Strings can be iterated to extract each character one at a time. Finally, sum takes each of the integers returned from map and adds them together. An equivalent formulation of the logic is possible via sum with a generator expression: sum(int(i) for i in str(n // 60 * 100 + n % 60))
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/51130199
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89247719
tagged with: amazon-redshift
tagged with: python
has comment: http://stackoverflow.com/comment/89246408
has body: HI I have the following function to save a csv file: mysql_cur = mysql_conn.cursor() mysql_cur.execute('select * from %s where Date &gt; "2018-01-01";' % mysql_table_name ) description = mysql_cur.description rows = mysql_cur.fetchall() for row in rows: c.writerow(row) Then I manually upload the file to an S3 bucket. Last I run the COPY query: redshift_cur = redshift_conn.cursor() sql = """copy kpi_kpireport from 's3://clab-migration/kpi.csv' credentials 'aws_access_key_id=ID;aws_secret_access_key=KEY/KEY/pL/KEY' csv;""" print(redshift_cur.execute(sql)) The COPY command works when I use it in SQL Workbench/J, I am just not sure what I am doing wrong here with the syntax in the execute statement that does not copy any rows.
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51133147
type: Question
tagged with: copy
has title: Redshift COPY csv in S3 using python
accepted answer: http://stackoverflow.com/a/51133147

http://stackoverflow.com/q/51017725
tagged with: python
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/51017861
type: Question
score: 1
has title: Which web frame of python has clicking button to pop a sub page's function?
downvote count: 0
answer count: 1
has body: Now I use python to design a page,I have not written python web code. I want to know which python web frame encapsulates the functions I want. For example,I have a button "dept" on my home page likes this: I want to click this button "dept" to pop a sub page, and the sub page can choose the department likes this. After selection, the home page can get the values of the selected departments in the sub page. I know many HTML frame for example bootstrap's modal provides such a function. So does python have such a function? The button "run" on my home page needs to use departments values as parameters to run python programs. So I should choose Django or Flask or Bottle?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51017861

http://stackoverflow.com/a/51832984
answers question: http://stackoverflow.com/q/51069236
has body: I am developing a simple library called disk.frame that has the potential to take on dask one day. It uses the fst file format and data.table to manipulate large amounts of data on disk. As of now, it doesn't have a cluster module but given that it uses future in the background and future can have cluster back-ends, it is a possibility in the future. There is also multidplyr in the works by Hadley and co. Currently, I have used disk.frame successful to manipulate datasets with hundreds of million rows of data and hundreds of columns. If you willing to look beyond R then JuliaDB.jl in the Julia ecosystem is something to look out for.
downvote count: 0
upvote count: 8
type: Answer
score: 8

http://stackoverflow.com/q/51141889
upvote count: 1
has comment: http://stackoverflow.com/comment/89272391
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51164251
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89267912
type: Question
has comment: http://stackoverflow.com/comment/89309539
answer count: 1
has title: How to download matplotlib for python 3.7 in windows 8?
downvote count: 0
has answer: http://stackoverflow.com/a/51164251
tagged with: python
has body: How do you download matplotlib to windows so I can use it with python? Every other question related to this that I've found on StackOverflow has led to the same problem which is that it keeps giving me the error: python setup.py egg_info failed with error code 1 in C:\Users\Myname\AppData\Local\Temp\pip-install-9gc765gs\matplotlib\ Things I have tried (from the command prompt): pip install matplotlib pip install matplotlib-1.5.0-cp35-none-win_amd64.whl (which is the file I downloaded from SourceForge and is now stored in my computer) pip install "matplotlib-1.5.0-cp35-none-win_amd64.whl" python -mpip install -U matplotlib I even tried tried: pip install --upgrade setuptools python -mpip install -U pip prior to using the other commands to make sure everything was up to date. Any help would be very appreciated.
favorite count: 0

http://stackoverflow.com/q/51084199
type: UnansweredQuestion
has title: Cannot access the file location where json data is saved in python
tagged with: python
score: -1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89157148
has comment: http://stackoverflow.com/comment/89157024
tagged with: http://stackoverflow.com/tag/json
has body: with open("/home/akash/akashenv/PyCharm/PycharmProjects/chatbot_tensorflow{}/RC_{}".format(timeframe.split('-')[0], timeframe)., buffering = 1000) as f: for row in f: print(row) row_counter += 1 row = json.loads(row) parent_id = row['parent_id'] body = format_data(row['body']) created_utc = row['created_utc'] sub = row['sub'] the error showing is: Traceback (most recent call last): File "/home/akash/akashenv/PyCharm/PycharmProjects/chatbot_tensorflow/database.py", line 37, in with open("/home/akash/akashenv/PyCharm/PycharmProjects/chatbot_tensorflow{}/RC_{}".format(timeframe.split('-')[0], timeframe), buffering = 1000) as f: FileNotFoundError: [Errno 2] No such file or directory: '/home/akash/akashenv/PyCharm/PycharmProjects/chatbot_tensorflow0/RC_0-01' Process finished with exit code 1 I have set all the names in RC_0-01, RC_0-02 and so on, and i am trying to rain a chatbot using these data set. Can anyone help me out here?
has comment: http://stackoverflow.com/comment/89158548
has comment: http://stackoverflow.com/comment/89157613
has comment: http://stackoverflow.com/comment/89156813
tagged with: chatbot
has answer: http://stackoverflow.com/a/51084670
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89157540
favorite count: 0

http://stackoverflow.com/comment/89255965
type: AnswerComment
type: Comment
has text: Sorry, but your answer does not answer the question at all, or am I wrong?
comment on: http://stackoverflow.com/a/51135848
score: 0

http://stackoverflow.com/comment/89281377
score: 0
type: Comment
type: QuestionComment
has text: In your case `(df1+df2).fillna(df1)`
comment on: http://stackoverflow.com/q/51148526

http://stackoverflow.com/comment/89276355
type: QuestionComment
has text: Every time you create an object in Python (i.e. `a = ...`) it will potentially (and usually) have a different address in memory. You probably just want to create `a` once and then do the rest of your calculations based on `a`'s unchanging memory address.
comment on: http://stackoverflow.com/q/51146054
score: 0
type: Comment

http://stackoverflow.com/q/51095139
type: UnansweredQuestion
tagged with: multithreading
has body: My python script calls another python scripts method (which runs an infinite loop and performs some activity) and runs it as thread. I want to kill my calling python script as soon as the thread dies
tagged with: python
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/12435211
type: Question
has title: How to kill the calling process when it spawned thread dies in python?
has comment: http://stackoverflow.com/comment/89178409
has comment: http://stackoverflow.com/comment/89179689
upvote count: 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51096738

http://stackoverflow.com/q/51129847
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51131358
has body: Why can we not use Popen to run a batch file? &gt;&gt;&gt; p = Popen(["filename"], shell=True, stdout = PIPE) This is working well, but according to the documentation we should not use shell = True for "running a batch file or console-based executable". Why can't we use shell = True when it runs a batch file? Why should it only be used for building in cmd?
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89269549
has comment: http://stackoverflow.com/comment/89269999
has comment: http://stackoverflow.com/comment/89269987
has title: Using subprocess.Popen to run a batch file in Windows
type: Question
has comment: http://stackoverflow.com/comment/89269884
has comment: http://stackoverflow.com/comment/89269693
score: 0
accepted answer: http://stackoverflow.com/a/51131358
tagged with: windows
has comment: http://stackoverflow.com/comment/89245024

http://stackoverflow.com/q/51062603
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51064459
has comment: http://stackoverflow.com/comment/89115250
tagged with: topic-modeling
has body: I am looking for ways to extract specific paragraphs out of strings. I have a lot of documents which I want to use for topic modeling, but these contain tables, figures, headers, etc. I only want to use the summary which usually is in a document. But the summaries aren't clearly declared. I converted the PDFs to text and tried something like this but it did not work out well, because the summaries are always declared in a different way: def get_summary(text): subject = "" copy = False textlines = text.splitlines() for line in textlines: #print line if line.strip() == 'SUMMARY_BEGIN': copy = True elif line.strip() == 'SUMMARY_END': copy = False elif copy: #print(line) subject += line return subject I dont want search for a summary between 100 different possible substrings. Edit: look alike example: Date 21 Jun 2017 name name [abc] name name [abc] name name [cbd] name name name name name name name name name name nonsense-word1 nonsense-word1 nonsense-word1 12354 37264324 Summary: Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of my document. Here is the only part I want to extract out of …
answer count: 3
upvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89116028
has answer: http://stackoverflow.com/a/51063664
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89115698
has comment: http://stackoverflow.com/comment/89116716
tagged with: nlp
score: -1
has comment: http://stackoverflow.com/comment/89116210
has title: How to search for a specific paragraph in a text?
has comment: http://stackoverflow.com/comment/89115430
downvote count: 1
has answer: http://stackoverflow.com/a/51064574

http://stackoverflow.com/a/51076383
score: 0
type: Answer
has body: You will have to change your code as follows to obtain a bar chart fig, ax = plt.subplots() ax.set_xlabel('Country') ax.set_ylabel('Total Impressions') ax.bar(x,y) plt.show() For additional options within the bar plotting tool, you may refer the documentation : https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html
answers question: http://stackoverflow.com/q/51068397
has comment: http://stackoverflow.com/comment/89159105
has comment: http://stackoverflow.com/comment/89176227

http://stackoverflow.com/q/51109792
answer count: 1
has body: I have to search for a pattern either inside the content of a variable or inside a data file. Below is the code I have so far: import re UserSpecifiedPattern = "segfault" # find every instance of a user specified pattern pattern = re.compile( rb'(\.\W+)?([^.]?segfault[^.]*?\.)', re.DOTALL | re.IGNORECASE | re.MULTILINE ) My problem is, how does one specify a variable to "re.compile". Meaning, I'm storing the actual pattern to be searched into a variable. And I'm then giving that variable to re.compile. The below is what I presume should work, but it isn't: import re UserSpecifiedPattern = "segfault" # find every instance of a user specified pattern pattern = re.compile( rb'(\.\W+)?([^.]?UserSpecifiedPattern[^.]*?\.)', re.DOTALL | re.IGNORECASE | re.MULTILINE ) I'm guessing this should be it? import re UserSpecifiedPattern = "segfault" # find every instance of a user specified pattern pattern = re.compile( rb'(\.\W+)?([^.]?{UserSpecifiedPattern}[^.]*?\.)', re.DOTALL | re.IGNORECASE | re.MULTILINE )
tagged with: regex
score: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51109868
type: AnsweredQuestion
has title: Compiling search patterns in Python
upvote count: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51109868

http://stackoverflow.com/comment/89301126
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51158770
score: 0
has text: `fruit in favorite_fruits is "apple"` is not going to do anything meaningful, but I can't even guess what you thought it would mean, especially considering apple isn't in that list.

http://stackoverflow.com/comment/89148406
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51079771
has text: I love how detailed this is, is there any way I can run this using pandas? Because I have to run it again using a csv file with a 1500+ rows of the same formated data as the screenshot.

http://stackoverflow.com/comment/89295152
comment on: http://stackoverflow.com/q/51102741
score: 0
has text: I tried. It worked. Thanks
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51053678
accepted answer: http://stackoverflow.com/a/51053751
has body: I am trying to create a new Column that displays a cumulative count based off values in separate columns. So for the code below, I'm trying to create two new columns based off Cause and Answer Columns. So for the values in Column Answer, if In is situated in Column Cause I want to provide a cumulative count in a new column. import pandas as pd d = ({ 'Cause' : ['In','','','In','','In','In'], 'Answer' : ['Yes','No','Maybe','No','Yes','No','Yes'], }) df = pd.DataFrame(d) Output: Answer Cause 0 Yes In 1 No 2 Maybe 3 No In 4 Yes 5 No In 6 Yes In Intended Output: Answer Cause Count_No Count_Yes 0 Yes In 1 1 No 2 Maybe 3 No In 1 4 Yes 5 No In 2 6 Yes In 2 I have tried the following but get an error. df['cumsum'] = df.groupby(['Answer'])['Cause'].cumsum()
type: Question
has answer: http://stackoverflow.com/a/51053751
has title: Cumulative count when two values match pandas
answer count: 2
has answer: http://stackoverflow.com/a/51053739
tagged with: pandas
upvote count: 1
favorite count: 0
tagged with: cumsum
tagged with: count
tagged with: python
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51053739
score: 1
tagged with: group-by

http://stackoverflow.com/q/51039275
has body: I have an image consisting of 5 checkboxes arranged in a parallel manner. I need to separate checkbox button and checkbox text and save them separately. There can be any number of checkboxes in an image arranged in a parallel manner how can I split the checkbox button and checkbox text and save them separately. I am new to computer vision. Please guide me how to achieve it.
has answer: http://stackoverflow.com/a/51067127
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51055043
upvote count: 3
tagged with: image-processing
has title: How to separate checkbox button and checkbox text from an image using Python?
type: Question
tagged with: opencv
possible better answer: http://stackoverflow.com/a/51067127
has answer: http://stackoverflow.com/a/51059247
accepted answer: http://stackoverflow.com/a/51059247
has comment: http://stackoverflow.com/comment/89093079
answer count: 3
has comment: http://stackoverflow.com/comment/89117393
downvote count: 0
has comment: http://stackoverflow.com/comment/89080553
favorite count: 0

http://stackoverflow.com/comment/138473955
comment on: http://stackoverflow.com/a/68006865
has text: This confirms `S3` class derives from the `BaseClient`, but doesn't tell what's actually the type.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/89058949
comment on: http://stackoverflow.com/q/51032917
type: Comment
type: QuestionComment
has text: Unless you mean that you just want the status to show as online, in which case you *still* need to run the code full time as Discord sets an account to offline when it can't find a connection to a client with that username.
score: 1

http://stackoverflow.com/q/51047179
accepted answer: http://stackoverflow.com/a/51047597
tagged with: python
has comment: http://stackoverflow.com/comment/89085537
type: AnsweredQuestion
has title: IndexError: tuple index out of range. Accessing column in specific row
possible better answer: http://stackoverflow.com/a/51047499
has comment: http://stackoverflow.com/comment/89085739
has body: I'm getting a IndexError issue that I cannot fix. What I am trying to do is iterate through rows of data and compare a specific column in one row to the same column in a different row. If they are the same it should put them in the badBucket otherwise it goes in to a goodBucket. Here is my code: XDFDF =pd.DataFrame(XDF) ct1 = 0 ct2 = 0 goodBucket = [] badBucket = [] duplicate = False for row in XDFDF.iterrows(): for row2 in XDFDF.iterrows(): if ct1 != ct2: if row[6] == row2[6]: badBucket.append(row2) duplicate = True else: goodBucket.append(row2) ct2 += 1 if duplicate: badBucket.append(row) duplicate = False ct1 += 1 Note: XDFDF is a relatively big pandas DataFrame with 6 columns (0,1,2,3,4,5,6). My Error is: Traceback (most recent call last): File "/Users/john_crowley/PycharmProjects/Greatness/venv/Recipes.py", line 118, in &lt;module&gt; if row[6] == row2[6]: IndexError: tuple index out of range Process finished with exit code 1 Note: line 118 is the line where 'if row[5] == row[5]' is typed. If anyone has a resolution to the specific issue at hand to resolve the IndexError your help would be greatly appreciated, or any comments on improving code would be appreciated as well. If you have any questions please let me know and I will get back to you as soon as I can.
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/89085769
has comment: http://stackoverflow.com/comment/89085750
tagged with: int
score: 0
tagged with: typeerror
answer count: 2
has answer: http://stackoverflow.com/a/51047499
tagged with: pandas
has comment: http://stackoverflow.com/comment/89086450
has answer: http://stackoverflow.com/a/51047597

http://stackoverflow.com/q/51091217
has answer: http://stackoverflow.com/a/51091878
tagged with: xml.etree
answer count: 3
has answer: http://stackoverflow.com/a/51091994
has comment: http://stackoverflow.com/comment/89171126
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to overwrite an XML attribute value without reading the whole file in python
has body: How do you overwrite a single attribute value when you are only reading one element at a time? Specifically I am using xml.etree.cElementTree.iterparse() to read each individual element. Then I am changing an attribute value. What I need to do then is to overwrite the original element with the changed element. Here is the example code so far: osm_file = open(sample.osm, 'r+') for event, elem in ET.iterparse(osm_file events=("start",)): # Making some changes elem.attrib['v'] = 'new_value' # Some how write the elem back to the XML file The one thing that I can not do is to read the whole XML file into python because the file is too big.
tagged with: http://stackoverflow.com/tag/xml
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/89171382
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51091632

http://stackoverflow.com/q/51127382
has answer: http://stackoverflow.com/a/62667801
has answer: http://stackoverflow.com/a/61407268
score: 7
answer count: 4
favorite count: 0
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
upvote count: 7
has title: empty row when exporting dataframe with openpyxl
type: Question
has body: I try to export an existing DataFrame to an Excel file using openpyxl. import pandas as pd from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl import Workbook d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) wb = Workbook() ws = wb.active for rows in dataframe_to_rows(df, index=True, header=True): ws.append(rows) wb.save(filename = 'test.xlsx') When doing so, I always get an empty row in the output file after the header row. I know I can delete the 2nd row manually, but is there no other way? I have already tried this here - with the same result: import pandas as pd from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl import Workbook d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) wb = Workbook() ws = wb.active rows = dataframe_to_rows(df) for r_idx, row in enumerate(rows, 1): for c_idx, value in enumerate(row, 1): ws.cell(row=r_idx, column=c_idx, value=value) wb.save(filename = 'test.xlsx')
downvote count: 0
has answer: http://stackoverflow.com/a/54772081
has answer: http://stackoverflow.com/a/68622769
tagged with: pandas

http://stackoverflow.com/comment/89297632
type: AnswerComment
type: Comment
has text: Strange, I get another value error: `ValueError: Input contains NaN, infinity or a value too large for dtype('float64').` I also removed the TRUE/FALSE tables as well: `df = df.drop(['Name', 'Type_1','Type_2','isLegendary','Color','hasGender','Egg_Group_1','Egg_Group_2','hasMegaEvolution','Body_Style'], axis=1)`.
comment on: http://stackoverflow.com/a/51147917
score: 0

http://stackoverflow.com/comment/89044649
type: QuestionComment
type: Comment
has text: @RieljunLiguid yes.
comment on: http://stackoverflow.com/q/51025577
score: 0

http://stackoverflow.com/comment/89146994
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51078671
type: QuestionComment
has text: Because the graph you provided to the algo is not what do you think it is, there is nothing wrong with your BFS, the error may be in other parts.

http://stackoverflow.com/a/51099850
type: Answer
has comment: http://stackoverflow.com/comment/89188977
score: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/89188924
has body: Using a list comprehension and dictionary input d: var = 'rohithmn3@gmail.com' res = [subd['role'] for subd in d['bindings'] if 'user:'+var in subd['members']] print(res) ['roles/browser', 'roles/viewer'] Setup d = { "bindings": [ { "members": [ "user:rohithmn3@gmail.com" ], "role": "roles/browser" }, { "members": [ "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com", "user:rohithmn03@gmail.com" ], "role": "roles/owner" }, { "members": [ "user:rohithmn3@gmail.com" ], "role": "roles/viewer" } ], "etag": "BwrRsH-UhJ0=", "version": 1 }
accepted answer of: http://stackoverflow.com/q/51099651
has comment: http://stackoverflow.com/comment/89190246
has comment: http://stackoverflow.com/comment/89187682
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51099651
upvote count: 3
has comment: http://stackoverflow.com/comment/89187590

http://stackoverflow.com/q/51077894
has body: I need to open a log file, and print out specific lines that are in between two different patterns. Beginning = pattern1 Ending = pattern2 This is what I have so far: def SeeIfDateTimeIsFound(): mylist = [] for line in input_data: if CTFBeginA in line: # Or whatever test is needed if re.search(stringA, line) and re.search(stringB, line): mylist.append((line.strip())) break for line in input_data: # This keeps reading the file if CTFEndinA in line.strip(): nextline = (next(input_data, '').strip()) if CTFEndin not in nextline: break else: if re.search(stringA, line) and re.search(stringB, line): mylist.append((line.strip())) if re.search(stringA, line) and re.search(stringB, line): mylist.append((line.strip())) return mylist What I'm trying to do is basically the equivalent of this awk code: awk '/Beginning/,/Ending/' logfile One of the problems i have with the python code above is, it only grabs the first line it finds that contains Ending pattern. If there are multiple lines containing Ending, i want the python code to grab every one of them and only stop grabbing them when it has grabbed the last one.
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89156319
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51078014
type: Question
has title: python print between two patterns, including lines containing patterns

http://stackoverflow.com/comment/89074504
score: 1
has text: In the example in the post you linked, the pages have no reference to each other. There should be no problem putting them in separate files and importing all of them in the file with the controller (SampleApp).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51041225

http://stackoverflow.com/comment/89318279
type: QuestionComment
comment on: http://stackoverflow.com/q/51167397
has text: Have you balanced all triple quotes correctly ?
score: 0
type: Comment

http://stackoverflow.com/comment/89259175
type: Comment
type: QuestionComment
score: 0
has text: Is there always a blank line before "find me", and is a blank line always followed by "find me"? Do you want to get rid of all empty lines, or just those before "find me" (and replace those with different text)?
comment on: http://stackoverflow.com/q/51137309

http://stackoverflow.com/comment/89061043
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51034509
has text: This uses a loop... :-(

http://stackoverflow.com/a/51020914
has comment: http://stackoverflow.com/comment/89035913
upvote count: 1
answers question: http://stackoverflow.com/q/51020231
type: Answer
has body: Using bins will solve the problems. The bins are the values to which you assign the values for example 0.28 will be assigned to bin 0.3. The code below provides you an example of using bins: import matplotlib.pyplot as plt values = [0.68, 0.28, 0.31, 0.5, 0.25, 0.5, 0.002, 0.13, 0.002, 0.2, 0.3, 0.45, 0.56, 0.53, 0.001, 0.44, 0.008, 0.26, 0., 0.37, 0.03, 0.002, 0.19, 0.18, 0.04, 0.31, 0.006, 0.6, 0.19, 0.3, 0., 0.46, 0.2, 0.004, 0.06, 0.] plt.hist(values, bins=[0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1]) plt.show() To plot it in a more suitable way, it can be handy to convert the x axis into a logaritmic scale: plt.hist(values, bins=[0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1], log=True) changes the log scale on the y axis. Adding the following line to your code will make a logaritmic x axis for your histogram: plt.xscale('log')
downvote count: 0
score: 1

http://stackoverflow.com/q/51100994
tagged with: installation
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/89190142
type: Question
has body: I want to install the pandas package on my Python. I am using pip to do it so I executed python -m pip install --upgrade pandas I get an error: Could not find a version that satisfies the requirement numpy==1.9.3 (from versions: 1.10.4, 1.11.0, 1.11.1rc1, 1.11.1, 1.11.2rc1, 1.11.2, 1.11.3, 1.12.0b1, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.12.1rc1, 1.12.1, 1.13.0rc1, 1.13.0rc2, 1.13.0, 1.13.1, 1.13.3, 1.14.0rc1, 1.14.0, 1.14.1, 1.14.2, 1.14.3, 1.14.4, 1.14.5, 1.15.0rc1)No matching distribution found for numpy==1.9.3 I suspect it has something to do with my numpy version not being up to date, but I already attempted to be upgrade it and it was apparentlly up to date. I am using Windows 7 and Python 3.4.3.
answer count: 1
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89189292
tagged with: python
has answer: http://stackoverflow.com/a/51101465
has title: Trouble installing pandas package on Python via PiP

http://stackoverflow.com/q/51063696
accepted answer: http://stackoverflow.com/a/51063952
answer count: 3
has answer: http://stackoverflow.com/a/72706826
possible better answer: http://stackoverflow.com/a/60194679
has answer: http://stackoverflow.com/a/60194679
tagged with: python
favorite count: 0
tagged with: hex
tagged with: checksum
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I want to determine the 8 bit modulo 256 checksum of an ASCII string. I know the formula is: checksum = (sum of bytes)%256 How can I do this in python (manipulate bytes)? If I start with a string: '1c03e8', I should output 0x94. The main problem is I'm not sure as to how to find the sum of the bytes of an ASCII string. Here is the main idea of what I'm looking for : https://www.scadacore.com/tools/programming-calculators/online-checksum-calculator/ It has CheckSum8 Modulo 256 I have tried: component = ('1c03e8') for i in range(len(component)): checksum.append(int(float(component[i].encode("hex")))) print checksum print hex(int(sum(checksum)%256)) this although gives me 0x52
has title: Determine 8 bit modulo 256 Checksum form ascii string [-Python]
type: Question
tagged with: ascii
has answer: http://stackoverflow.com/a/51063952
tagged with: modulo
downvote count: 0

http://stackoverflow.com/comment/89305365
comment on: http://stackoverflow.com/a/51160557
type: AnswerComment
score: 0
type: Comment
has text: Good point! I just did. The training predictions are all the same as well. I'm screwing up somewhere in training, but I can't seem to figure out!

http://stackoverflow.com/q/51160692
tagged with: ssl
upvote count: 2
tagged with: micropython
has answer: http://stackoverflow.com/a/52051638
tagged with: websocket
favorite count: 0
type: UnansweredQuestion
has body: I successfully managed to connect my ESP32 to a WebSocket server. Now I am trying to make it work with SSL. I tried this simple code to connect to www.google.com. I used this to generate the cert and key. openssl req -newkey rsa:2048 -nodes -keyout client.key -x509 -days 365 -out client.crt . Then copy over the key and cert files with adafruit-ampy. Don't forget to change your serial port. ampy -p /dev/tty.SLAB_USBtoUART put client.crt ampy -p /dev/tty.SLAB_USBtoUART put client.key This is the code on the ESP32 import ussl import usocket import networking KEY_PATH = "client.key" CERT_PATH = "client.crt" HOST, PATH, PORT = "www.google.com", "/" 443 with open(KEY_PATH, 'rb') as f: key1 = f.read() with open(CERT_PATH, 'rb') as f: cert1 = f.read() s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) addr = usocket.getaddrinfo(HOST, PORT)[0][-1] s.connect(addr) sock = ussl.wrap_socket(s, key = key1, cert = cert1) sock.write(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (PATH, HOST), 'utf8')) print(sock.read(100)) I get this error: mbedtls_ssl_handshake error: -7280 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 5] EIO Has anyone successfully used ssl socket_wrap on ESP32? EDIT (23.12.2018): I managed to finally get something working, fetching HTML from google over HTTPS, yee. Check code above. Hope this helps. I assume the MicropPython port for ESP32 has been getting better and this is the reason this works now. Next step is to get the SSL WebSocket working ... EDIT (09.06.2019): It's working now. This library works great for what I intended to do https://github.com/danni/uwebsockets
tagged with: python
score: 2
has title: ESP32 MicroPython SSL WebSocket
downvote count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/65980860
tagged with: esp32

http://stackoverflow.com/a/51093205
score: 0
answers question: http://stackoverflow.com/q/51092406
type: AcceptedAnswer
type: Answer
has body: You can using pivot_table df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar')
accepted answer of: http://stackoverflow.com/q/51092406

http://stackoverflow.com/comment/89244916
score: 0
type: Comment
type: QuestionComment
has text: as I understand it, your fourth Array is c+b - what would you expect?
comment on: http://stackoverflow.com/q/51129938

http://stackoverflow.com/q/51102703
has title: Is the while loop not compatible with tkinter?
has comment: http://stackoverflow.com/comment/89192775
has answer: http://stackoverflow.com/a/51103483
type: AnsweredQuestion
has body: For some reason, whenever I try incorporating the while loop into my tkinter program, the window I created freezes and says "not responding". Is this because while is not compatible with tkinter? If so, please let me know a way around this.
has comment: http://stackoverflow.com/comment/89192694
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/51103483
answer count: 1
has comment: http://stackoverflow.com/comment/89192651
tagged with: python
has comment: http://stackoverflow.com/comment/89192669
tagged with: tkinter

http://stackoverflow.com/a/51077859
type: Answer
has comment: http://stackoverflow.com/comment/89146023
upvote count: 3
has body: 1: __del__() might not be getting called for a number of reasons to do with garbage collection. From the documentation: Note del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_info()[2] keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the second can be resolved by freeing the reference to the traceback object when it is no longer useful, and the third can be resolved by storing None in sys.last_traceback. Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc module for more information about this topic. Rather than relying on the built-in memory management functionality, perhaps you could implement a bespoke function for freeing up resources once an object is no longer needed? 2: To avoid having two instances with the same name, use the factory pattern.
score: 3
accepted answer of: http://stackoverflow.com/q/51077772
answers question: http://stackoverflow.com/q/51077772
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51132371
has body: You need to authenticate using OAuth2 to be able to use the service. The 403 error you're receiving is expected because your not authenticating before trying to use the service. See the following links for some information on authenticating via these methods: https://developers.google.com/identity/protocols/OAuth2 Authenticating to the service may look like the following: from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] SERVICE_ACCOUNT_FILE = '/path/to/service.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES)
has comment: http://stackoverflow.com/comment/89249944
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89250758
has comment: http://stackoverflow.com/comment/89251162
has comment: http://stackoverflow.com/comment/89254633
has comment: http://stackoverflow.com/comment/89249961
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89250411
has comment: http://stackoverflow.com/comment/89249912
has comment: http://stackoverflow.com/comment/89254085
accepted answer of: http://stackoverflow.com/q/51131849
has comment: http://stackoverflow.com/comment/89250005
score: 1
has comment: http://stackoverflow.com/comment/89249372
answers question: http://stackoverflow.com/q/51131849

scilab
tags question: http://stackoverflow.com/q/51065173
tags question: http://stackoverflow.com/q/51021223
tag name: scilab
type: Tag

http://stackoverflow.com/q/51037132
has comment: http://stackoverflow.com/comment/89069681
has answer: http://stackoverflow.com/a/51039436
has comment: http://stackoverflow.com/comment/89068255
has body: I have an date 2/1/2018 ,which I am fetching from excel sheet column. I want to check what is the actual date format of this string. I am doing as follows: try: datetime.datetime.strptime(v, '%d/%m/%Y') print ('date format is correct') except : print ("Incorrect data format, should be mm/dd/yyyy") It's printing date format is correct. For %m/%d/%Y this also it's saying date format is correct. Actually I have two dates in excel column 2/1/2018 and 2/13/2018 and trying to convert in %Y-%m-%d using pandas.to_datetime(value,dayfirst=True,errors='coerce').dt.strftime("%Y-%m-%d").replace('NaT', '') If I remove dayfirst=True then it is working fine only for this excel, for other it is wrong. as one is getting converted in 2018-01-02 and another 2018-02-13. How do i identify what is the actual date format ?
score: 0
has comment: http://stackoverflow.com/comment/89066336
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89066200
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89066160
tagged with: python
has comment: http://stackoverflow.com/comment/89068239
has comment: http://stackoverflow.com/comment/89068286
has comment: http://stackoverflow.com/comment/89069789
downvote count: 1
has comment: http://stackoverflow.com/comment/89069968
has comment: http://stackoverflow.com/comment/89066270
type: Question
has title: Check input string date format

http://stackoverflow.com/a/51192756
type: Answer
upvote count: 54
has comment: http://stackoverflow.com/comment/124149022
accepted answer of: http://stackoverflow.com/q/51111323
has body: CatBoost has several parameters to control verbosity. Those are verbose, silent and logging_level. By default logging is verbose, so you see loss value on every iteration. If you want to see less logging, you need to use one of these parameters. It's not allowed to set two of them simultaneously. silent has two possible values - True and False. verbose can also be True and False, but it also can be an integer. If it is an integer N, then logging will be printed out each N-th iteration. logging_level can be 'Silent', 'Verbose', 'Info' and 'Debug': 'Silent' means no output to stdout (except for important warnings) and is same as silent=True or verbose=False. 'Verbose' is the default logging mode. It's the same as verbose=True or silent=False. 'Info' prints out the trees that are selected on every iteration. 'Debug' prints a lot of debug info. There are two places where you can use these parameters. The first one is model creation. The second one is fitting of the created model. If you have used a parameter when creating the model then it will be used during fitting if no parameter in fit function is specified. If you use parameter in fit function then the mode selected by this parameter will be used. In your case it looks like you have encountered a bug. The next time you see some bug, the best thing is to report to CatBoost team using issues on the GitHub page. This bug should have already been fixed, so try upgrading to the latest version or build code from source.
has comment: http://stackoverflow.com/comment/125579685
has comment: http://stackoverflow.com/comment/125578524
answers question: http://stackoverflow.com/q/51111323
type: AcceptedAnswer
downvote count: 0
score: 54

http://stackoverflow.com/q/51149638
has answer: http://stackoverflow.com/a/51150753
possible better answer: http://stackoverflow.com/a/51150038
tagged with: pip
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51149916
has title: Difference in PIP format
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51149916
has body: What is the difference between: python -m pip install forecasting and pip install forecasting In my environment, the first is working when the second format raise the following error: ModuleNotFoundError: No module named 'pip._internal'
has comment: http://stackoverflow.com/comment/89283580
answer count: 3
has comment: http://stackoverflow.com/comment/89283123
has answer: http://stackoverflow.com/a/51150038

http://stackoverflow.com/comment/89095436
type: QuestionComment
has text: Because those are strings, not integers.
score: 4
comment on: http://stackoverflow.com/q/51052142
type: Comment

http://stackoverflow.com/a/51115124
score: 1
has comment: http://stackoverflow.com/comment/89216516
has comment: http://stackoverflow.com/comment/89216533
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51114987
answers question: http://stackoverflow.com/q/51114987
type: Answer
has body: Iterate over your items in MyList and check for every item (lowercase) if any of the dict's (lowercase) keys is in it. Then replace. This assumes that you don't have different values for identical words as keys (except for lower- / uppercase difference) my_list = ["123steel", "MylistConcrete", "Nothinginhere", "45", "56", "steel", "CONCRETE"] search_strings = {'concrete': 'C', 'CONCRETE': 'C', 'Steel': 'S', 'STEEL': 'S'} for i in range(len(my_list)): for k, v in search_strings.items(): if k.lower() in my_list[i].lower(): my_list[i] = v break # avoids completing the loop if first item is found print(my_list) The result is ['S', 'C', 'Nothinginhere', '45', '56', 'S', 'C']
downvote count: 0

http://stackoverflow.com/comment/89048376
type: QuestionComment
comment on: http://stackoverflow.com/q/51026191
has text: Bram: In that case it doesn't sound to me like you would have any worries about about using too much memory by having/leaving them all open simultaneously.
score: 1
type: Comment

http://stackoverflow.com/a/51100050
downvote count: 0
answers question: http://stackoverflow.com/q/51099772
has body: If I understood this correctly, then you want to cycle between the repeated 1s every time they are returned as part of subset. One way to do this is to create a dictionary with the item as key and its indices stored in a list. Once we have this dict we can apply itertools.cycle to the list and then use next() to cycle between an items's indices: import itertools def compute(x, y): return (x + y, x - y) inputs_to_compute = [1, 1, 3] indices = {} for ind, item in enumerate(inputs_to_compute): indices.setdefault(item, []).append(ind) for k, v in indices.items(): indices[k] = itertools.cycle(v) results = [[] for i in range(len(inputs_to_compute))] for subset in itertools.combinations(inputs_to_compute, 2): r1, r2 = compute(subset[0], subset[1]) results[next(indices[subset[0]])].append(r1) results[next(indices[subset[1]])].append(r2) Output: &gt;&gt;&gt; %run so.py &gt;&gt;&gt; results [[2, 4], [0, 4], [-2, -2]]
type: Answer
has comment: http://stackoverflow.com/comment/89187618
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89187857
has comment: http://stackoverflow.com/comment/89187830
has comment: http://stackoverflow.com/comment/89187560

http://stackoverflow.com/a/63552759
score: 0
has body: There is an easy fix for this : bot = discord.Client()#Creates Client bot = commands.Bot(command_prefix='!')#Sets prefix for commands(!Command) Just change client to bot that'll do.
answers question: http://stackoverflow.com/q/51166800
type: Answer

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/51068761
type: Tag
tags question: http://stackoverflow.com/q/51090695
tags question: http://stackoverflow.com/q/51045716

http://stackoverflow.com/q/51113129
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51113731
has title: Perspective projection with homography not working
has body: I'm trying to replace the right side road of the following picture with light yellow polygon: origin: desired(created manually): So I'm thinking using Homography to make it happen (I know just adding a filled polygon will work too, but I may want to use some other source images other than a simple yellow polygon such as advertisement pics in the future). This is a tutorial about it and I just copy the code in it and made some change on pixles. The source image I'm using is like this: And the first image in this post is my destination image. Here is my code for doing the job: import cv2 import numpy as np # source image source_img = cv2.imread('lightyellow.jpg') # get four corners of the source (clock wise) pts_source = np.array([[0,0], [20,0], [20,30],[0,30]]) # destination image dst_img = cv2.imread('0.png') # four corners in destination image (also clock wise): pts_dst = np.array([[292,0], [415,0], [578,120],[415,189]]) # calculate homography h, status = cv2.findHomography(pts_source, pts_dst) # warp source image to destination based on homography img_out = cv2.warpPerspective(source_img, h, (dst_img.shape[1], dst_img.shape[0])) cv2.imshow('warped', img_out) cv2.waitKey(0) However, what I got is something like this: It's totoally wrong but I don't know why. Could somebody give me some instruction?
tagged with: python
tagged with: opencv
type: AnsweredQuestion
type: Question
tagged with: projection
tagged with: homography
tagged with: perspective
accepted answer: http://stackoverflow.com/a/51113731

http://stackoverflow.com/q/51104040
has body: I am currently trying to replace the occurrence of a number x with the xth argument in a string. Here is my code: def simple_format(format, *args): res = format.replace("%", "") for x in res: if (isinstance(x, int)): res = res.replace(x, args(x)) return res The first replace is used to remove the occurrence of % in the string and the next is to check if the variable encountered is a number and if it is, replacing it with the argument. For example, simple_format("hello %0", "world", "Ben") should return "hello world".The desired output is not achieved. What is the mistake? Is there any way to do it using replace method? Thanks in advance.
has comment: http://stackoverflow.com/comment/89195518
has comment: http://stackoverflow.com/comment/89195727
tagged with: python
tagged with: isinstance
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51104349
has title: replacing all instances of %X with Xth argument in args in python
type: Question
tagged with: replace
answer count: 2
possible better answer: http://stackoverflow.com/a/51104220
has answer: http://stackoverflow.com/a/51104220
accepted answer: http://stackoverflow.com/a/51104349
score: 0

http://stackoverflow.com/q/51026581
accepted answer: http://stackoverflow.com/a/51026642
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51026683
tagged with: python
has answer: http://stackoverflow.com/a/51026642
has answer: http://stackoverflow.com/a/51026683
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
has title: pandas finds indices of rows in each group which meets certain condition and assign values to these rows
tagged with: dataframe
upvote count: 3
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/51026765
has body: I have a df, name_id name 1 a 2 b 2 b 3 c 3 c 3 c now I want to groupby name_id and assign -1 to rows in the group(s), whose length is 1 or &lt; 2; one_occurrence_indices = df.groupby('name_id').filter(lambda x: len(x) == 1).index.tolist() for index in one_occurrence_indices: df.loc[index, 'name_id'] = -1 I am wondering what is the best way to do it. so the result df, name_id name -1 a 2 b 2 b 3 c 3 c 3 c

http://stackoverflow.com/q/51095970
has answer: http://stackoverflow.com/a/54701323
has comment: http://stackoverflow.com/comment/89179844
has comment: http://stackoverflow.com/comment/89475101
linked to: http://stackoverflow.com/q/1940578
has comment: http://stackoverflow.com/comment/89194934
has comment: http://stackoverflow.com/comment/89190364
has title: Install Python geopandas failed
upvote count: 3
has comment: http://stackoverflow.com/comment/89391773
answer count: 3
has comment: http://stackoverflow.com/comment/89420305
tagged with: geopandas
has comment: http://stackoverflow.com/comment/89194585
has body: I'm trying to install geopandas. Have the following setup: Windows-64 Anaconda2 (64-bit) Python 2.7 Have tried two things: 1) pip install geopandas This gives me the following error: WindowsError: [Error 126] The specified module could not be found and Command "python setup.py egg_info" failed with error code 1 in c:\users\username\appdata\local\temp\pip-install-_kgeyw\shapely\ The solutions to the similar problem here suggest that it's because of the slashes in the path being converted. Not sure how to test this. 2) anaconda search -t conda geopandas I then search for the version of geopandas suitable for my setup (Windows-64): conda install -c maxalbert geopandas which produces the following error: UnsatisfiableError: The following specifications were found to be in conflict: - geopandas Use "conda info &lt;package&gt; to see the dependencies for each package When I run the command conda info geopandas I get a list of geopandas version. Not sure how to proceed from here.
favorite count: 0
has comment: http://stackoverflow.com/comment/89194779
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/89474243
has comment: http://stackoverflow.com/comment/89474732
tagged with: pip
has answer: http://stackoverflow.com/a/51560940
type: Question
has answer: http://stackoverflow.com/a/61002941
score: 3
tagged with: anaconda

http://stackoverflow.com/a/51959349
downvote count: 0
upvote count: 64
score: 64
type: Answer
answers question: http://stackoverflow.com/q/51019622
has body: It seems like it's pycurl install error. When installing on centos try this: export PYCURL_SSL_LIBRARY=openssl If you install on macos try this one: export PYCURL_SSL_LIBRARY=openssl export LDFLAGS=-L/usr/local/opt/openssl/lib export CPPFLAGS=-I/usr/local/opt/openssl/include then run pip install pycurl

http://stackoverflow.com/comment/89297953
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51157107
has text: what is the name of your `image`?
type: Comment

http://stackoverflow.com/q/51160546
favorite count: 0
has title: Python - Using 'With Module as x' and Threading.Timer
tagged with: python
tagged with: ocr
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: multithreading
upvote count: 1
type: Question
has body: I'm trying to use Tesserocr to continuously read a changing line of text, as frequently as possible (right now that is every 3 seconds, but I want it to be much more frequently). Right now, I have the following code: from tesserocr import PyTessBaseAPI def readingFunction(): threading.Timer(1.0, readingFunction).start() with PyTessBaseAPI() as api: # Get image img = getImageForOCR() # Get OCR Text api.SetImage(img) return api.GetUTF8Text() readingFunction() This works well, but every time the function runs, PyTessBaseAPI() loads and that slows down my code. If I get the 'with PyTesBaseAPI()..' statement outside the function like this: from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: def readingFunction(): threading.Timer(3.0, readingFunction).start() # Get image img = getImageForOCR() # Get OCR Text api.SetImage(img) return api.GetUTF8Text() readingFunction() .. then it works well only the first time, but then the second time (and the next runs fired by the Timer), I get the following error: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1182, in run self.function(*self.args, **self.kwargs) File "TestFile.py", line 111, in &lt;module&gt; def readingFunction(): File "TestFile.py", line 118, in returnOCRTextFrom return api.GetUTF8Text() File "tesserocr.pyx", line 2111, in tesserocr.PyTessBaseAPI.GetUTF8Text RuntimeError: Failed to recognize. No image set? I have tested, and img does have a valid image, and I believe api.SetImage(img) is run. Can someone tell me what I'm doing wrong?
downvote count: 0

http://stackoverflow.com/comment/89317809
type: QuestionComment
has text: The imports are not superfluous and when you think about it there's nothing strange. You have to import all model classes before using your models, because without importing, the class definitions are never evaluated, or in other words the code is not executed, and so the models and their tables are not created and stored in the registries.
comment on: http://stackoverflow.com/q/51155963
score: 0
type: Comment

http://stackoverflow.com/q/51081572
has comment: http://stackoverflow.com/comment/89152069
has comment: http://stackoverflow.com/comment/89160956
favorite count: 0
has body: Lets say I want to make a page in my website where I want to be able to enter in the DB if workers are present or not. Every worker has separate profile page. My models.py: class profile(models.Model): ...#other fields username = model.Charfield(max_length=26, blank=false) class attendence(models.Model): user = models.ForeignKey(profile, related_name='attendence') 28January2018 = models.BooleanField(default=1) Prototype Picture: In the prototype picture, if it is green it should be True in the boolean field, means present (this is the defualt), and when I click their name, the booleanfield will be false means absent and it will be red. How can achieve this? I need the template and the view code.
has comment: http://stackoverflow.com/comment/89152998
has answer: http://stackoverflow.com/a/51081784
has comment: http://stackoverflow.com/comment/89152314
has comment: http://stackoverflow.com/comment/89205340
has comment: http://stackoverflow.com/comment/89193069
tagged with: python
tagged with: templates
has comment: http://stackoverflow.com/comment/89159685
type: AnsweredQuestion
upvote count: 0
tagged with: view
has comment: http://stackoverflow.com/comment/89160119
tagged with: django
has comment: http://stackoverflow.com/comment/89152139
has comment: http://stackoverflow.com/comment/89193214
type: Question
has comment: http://stackoverflow.com/comment/89151926
has title: How can I edit multiple users info in one page?
has comment: http://stackoverflow.com/comment/89205995
score: -1
accepted answer: http://stackoverflow.com/a/51081784
has comment: http://stackoverflow.com/comment/89204814
has comment: http://stackoverflow.com/comment/89153654
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/89150062
has text: If you can't find the flags being set in one of the env vars (for reference, [here's the spot in `distutils` source where the flags are read from env](https://github.com/python/cpython/blob/master/Lib/distutils/sysconfig.py#L173)), then they're probably baked into `gcc` by the vendor or distro maintainer (you can check `gcc -dumpspecs` for that). If you need a vanilla `gcc`, build one from source and pass the custom executable via `CC` var.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51028942
type: AnswerComment

http://stackoverflow.com/q/51134375
downvote count: 3
score: -3
has title: Print 5 letter or numbers to fit in cells
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/89253281
has comment: http://stackoverflow.com/comment/89253815
answer count: 1
has comment: http://stackoverflow.com/comment/89253402
favorite count: 0
has answer: http://stackoverflow.com/a/51654813
tagged with: pandas
has comment: http://stackoverflow.com/comment/89253117
tagged with: python
has comment: http://stackoverflow.com/comment/89253345
has body: I would to make a table. The cells have a fixed size. How can I cut the letters or numbers so that they fit in the cells? Is there a possibility (e.g. limit string or int)? It should run automatically automated and work for all sorts of scenarios. This is my Code. import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import pandas as pd from pandas.plotting import table def main(): data_frame = pd.read_excel('C:/test/TestArrays.xlsx') with PdfPages('multipage.pdf') as pdf: columns_per_page = 10 for page_no, start_column in enumerate( range(0, data_frame.shape[1], columns_per_page), 1 ): sub_frame = data_frame.iloc[ 0:15, start_column:start_column + columns_per_page ] fig, ax = plt.subplots(figsize=(5, 1)) fig.suptitle('1.Excel-Daten-Seite-{}'.format(page_no), fontsize=15) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_frame_on(False) a_table = table(ax, sub_frame, colWidths=[0.2] * sub_frame.shape[1]) a_table.auto_set_font_size(False) a_table.set_fontsize(15) a_table.scale(1.5, 1.5) cells = a_table.get_celld() for cell in (cells[0, i] for i in range(sub_frame.shape[1])): cell.set_fontsize(13) cell.set_color('grey') pdf.savefig(fig, bbox_inches='tight', dpi=300) if __name__ == '__main__': main()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89253469
tagged with: matplotlib

http://stackoverflow.com/a/51081845
type: Answer
has body: Instantiate self.sockerIOReqAccept within the init method: from socketIO_client_nexus import SocketIO, LoggingNamespace import threading class OpenInvitation(): def __init__(self): self.socketIOReqAccept = SocketIO('http://192.168.219.1', 5200, LoggingNamespace) thread = threading.Thread(target=self.socket) thread.start() def socket(self):. def getSID(args): NOWsocketID = args self.socketIDfromOpenforPlay = NOWsocketID print(NOWsocketID) self.socketIOReqAccept.on('s_id', getSID) self.socketIOReqAccept.wait() oi = OpenInvitation() socker = oi.socketIOReqAccept
answers question: http://stackoverflow.com/q/51080326
score: 0

http://stackoverflow.com/q/51092406
has answer: http://stackoverflow.com/a/51093205
accepted answer: http://stackoverflow.com/a/51093205
tagged with: python
type: AnsweredQuestion
has title: Efficiently assign bar chart from a pandas df
has body: I'm currently manually creating a bar chart from a pandas df. Is there a more efficient way to read it straight from the df? import pandas as pd import matplotlib.pyplot as plt d = ({ 'A' : ['1','1','1','2','2','2','3','3','3','3'], 'B' : ['A','B','C','A','B','C','D','A','B','C'], 'C' : ['John','Carl','Carl','John','Lily','John','Lily','John','Carl','Carl'], }) df = pd.DataFrame(data=d) fig,ax = plt.subplots(figsize = (3,3)) Ay = [3] Ax = [1] By = [2,1] Bx = [7,12] Cy = [1,2] Cx = [3,8] Dy = [1] Dx = [14] plt.bar(Ax,Ay, label = 'A') plt.bar(Bx,By, label = 'B') plt.bar(Cx,Cy, label = 'C') plt.bar(Dx,Dy, label = 'D') plt.legend(loc = 'upper right') plt.show() If I manually add in xticks to display the person the intended output is:
has answer: http://stackoverflow.com/a/51092734
type: Question
possible better answer: http://stackoverflow.com/a/51092734
tagged with: matplotlib
score: 0
answer count: 2
tagged with: pandas
tagged with: bar-chart

http://stackoverflow.com/comment/89183550
has text: what was the error you were getting.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51093366

http://stackoverflow.com/a/51112855
score: 1
has comment: http://stackoverflow.com/comment/89213674
upvote count: 1
has comment: http://stackoverflow.com/comment/89213174
answers question: http://stackoverflow.com/q/51112711
type: Answer
has comment: http://stackoverflow.com/comment/89213580
downvote count: 0
has comment: http://stackoverflow.com/comment/89213065
has comment: http://stackoverflow.com/comment/89213039
has body: Set an owner_ID to each link entry in DB. Than you can selecet the link by link_id and owner_ID. If the curr user not the user of the directory you can return a permission_denied(403)

http://stackoverflow.com/comment/89207204
has text: @G.Hyseni: Do you need help, to convert days into weeks? OK, here is a result of 20 years of experience with Python: divide by 7 :) What is your problem, really?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51109881
score: 0

http://stackoverflow.com/a/51031429
has body: The main difficult point is to get ('ABCD, Jun/14/1999'), content. It can not be a single-element tuple, as it would have been printed as ('ABCD, Jun/14/1999',), (note extra , before the )). So to get exactly the result you wanted, I did it using a series of print statements. The whole script (in Python 3) can be as follows: import re input = [ 'ABCD , D.O.B: - Jun/14/1999.', 'EFGH , DOB; - Jan/10/1998,', 'IJKL , D-O-B - Jul/15/1985..', 'MNOP , (DOB)* - Dec/21/1999,', 'QRST , *DOB* - Apr/01/2000.', 'UVWX , D O B, - Feb/11/2001 ' ] result = [ re.sub(r'^([a-z]+).*? - ([a-z]{3}/\d{2}/\d{4}).*', r'\1, \2', txt, flags = re.IGNORECASE) for txt in input ] print('OUTPUT = [') for txt in result: print(" ('{}')".format(txt)) print(']')
type: Answer
answers question: http://stackoverflow.com/q/51030488
score: 0

http://stackoverflow.com/a/74421937
downvote count: 0
type: Answer
has body: You could use the solve_qp function from qpsolvers. It can be installed, along with a starter kit of open source solvers, by pip install qpsolvers[open_source_solvers]. Then you can replace your line with: from qpsolvers import solve_qp solver = "proxqp" # or "osqp", "quadprog", "cvxopt", ... x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) There are many solvers available in Python, each coming with their pros and cons. Make sure you try different values for the solver keyword argument to find the one that fits your problem best. Here is a standalone example based on your question and the other comments: import numpy as np from qpsolvers import solve_qp H = np.array([[4.0, 1.0], [1.0, 2.0]]) f = np.array([1.0, 1]) G = np.array([[1.0, 0.0], [0.0, 1.0]]) h = np.array([0.7, 0.7]) A = np.array([[1.0, 1.0]]) b = np.array([1.0]) q_0 = np.array([1.0, 1.0]) solver = "cvxopt" # or "osqp", "proxqp", "quadprog", ... options = {"verbose": True} x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options)
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51161348

http://stackoverflow.com/a/51013957
has body: To add environment variables to your gitlab-ci.yml file: https://docs.gitlab.com/ce/ci/variables/#gitlab-ci-yml-defined-variables Also use a python docker image instead of installing python: https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#define-image-and-services-from-gitlab-ci-yml image: python:3.6 test: stage: test variables: LC_ALL=C.UTF-8 LANG=C.UTF-8
has comment: http://stackoverflow.com/comment/89024338
has comment: http://stackoverflow.com/comment/89024124
has comment: http://stackoverflow.com/comment/89024454
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89025425
has comment: http://stackoverflow.com/comment/89024030
has comment: http://stackoverflow.com/comment/89024170
has comment: http://stackoverflow.com/comment/89024180
has comment: http://stackoverflow.com/comment/89042140
accepted answer of: http://stackoverflow.com/q/51012960
type: Answer
has comment: http://stackoverflow.com/comment/89024420
has comment: http://stackoverflow.com/comment/89023688
answers question: http://stackoverflow.com/q/51012960
has comment: http://stackoverflow.com/comment/89024191
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89024478

http://stackoverflow.com/comment/89027143
has text: not sure if it was not resolved by now...but it seems that cuda-9 wasn't supported in tensorflow few months ago.. you may consider to downgrade to 1.4 tensorflow and see how it goes ...here is a useful link about same problem...good luck https://github.com/tensorflow/tensorflow/issues/14622\
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51016504

http://stackoverflow.com/comment/89159190
comment on: http://stackoverflow.com/q/51068397
has text: Got it, sorry about that just copied and pasted it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89036845
comment on: http://stackoverflow.com/q/51021768
score: 0
type: Comment
has text: Fft is accurate if frequency*total_time is large. In your case this number is approximately one.
type: QuestionComment

http://stackoverflow.com/a/62667801
downvote count: 0
type: Answer
upvote count: 2
has body: You can set the index as a column and then use index=False import pandas as pd from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl import Workbook d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) wb = Workbook() ws = wb.active df.reset_index(level=0, inplace=True) rows = dataframe_to_rows(df, index=False) for r_idx, row in enumerate(rows, 1): for c_idx, value in enumerate(row, 1): ws.cell(row=r_idx, column=c_idx, value=value) wb.save(filename = 'test.xlsx') The Output of the excel file will be
answers question: http://stackoverflow.com/q/51127382
score: 2

http://stackoverflow.com/comment/89086712
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51047542
has text: @piRSquared, Thank you, I had a feeling it had to do with using Python built-ins on NumPy arrays instead of NumPy vectorised functions.
score: 0

http://stackoverflow.com/a/51077992
has comment: http://stackoverflow.com/comment/89144896
answers question: http://stackoverflow.com/q/51077070
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89144785
type: Answer
accepted answer of: http://stackoverflow.com/q/51077070
downvote count: 0
has body: There is problem in test index values, not columns values. #sorting for better seen groups df1 = df1.sort_values(['a','b']) df2 = df1.groupby(['a','b'],as_index = False).apply(add_buy_label) print (df2) a b type buy_label 0 1 1 1 0 3 1 1 0 0 1 2 2 0 1 &lt;- return 1 only because index == 1 per group (2,2) 4 2 2 1 1 2 3 3 1 0 5 3 3 0 0 6 3 3 1 0 So need comapre by 1 with any for check at least one True: if group['type'].eq(1).any(): #what is same as if (group['type'] == 1).any():
score: 1

http://stackoverflow.com/comment/89085845
comment on: http://stackoverflow.com/a/51045750
has text: Notice you don't need an instance of "lorentz" before the line in my code (if it was made of zeros)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/68813136
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51038609
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/121612834
has body: If you have a file named random.py that you made, you may want to open it and look for the randint and choice functions in it, or the python is not installed correctly.

http://stackoverflow.com/q/51012658
tagged with: scikit-learn
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/51017425
type: Question
upvote count: 2
tagged with: python
has title: keras: returning model.summary() vs scikit learn wrapper
has answer: http://stackoverflow.com/a/76846233
answer count: 3
has answer: http://stackoverflow.com/a/51017425
downvote count: 0
possible better answer: http://stackoverflow.com/a/51015696
has answer: http://stackoverflow.com/a/51015696
tagged with: wrapper
tagged with: summary
score: 2
type: AnsweredQuestion
has body: While working with keras, I learned that using a wrapper comes with adverse effects for keras and scikit learn api requests. I am interested in a solution to have both. Variant 1: scikit Wrapper from keras.wrappers.scikit_learn import KerasClassifier def model(): model = Sequential() model.add(Dense(10, input_dim=4, activation='relu')) model.add(Dense(3, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model estimator = KerasClassifier(build_fn=model, epochs=100, batch_size=5) model.fit(X, y) -> This lets me print scikit commands such as accuracy_score() or classification_report(). However, model.summary() does not work: AttributeError: 'KerasClassifier' object has no attribute 'summary' Variant 2: No Wrapper model = Sequential() model.add(Dense(10, input_dim=4, activation='relu')) model.add(Dense(3, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X, y, epochs=100, batch_size=5) -> This lets me print model.summary() but not the scikit commands. ValueError: Mix type of y not allowed, got types {'multiclass', 'multilabel-indicator'} Is there a way that enables to use both?

http://stackoverflow.com/q/51014205
has title: Automating Opening Transcript for Youtube Automatic Generated Captions
score: 4
answer count: 1
tagged with: python
upvote count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51017831
accepted answer: http://stackoverflow.com/a/51017831
tagged with: selenium
tagged with: youtube
type: AnsweredQuestion
downvote count: 0
type: Question
has body: I am trying to write a python script that will automate the clicking of opening the transcript for a youtube video. For example, if you go to a youtube video, two to the right of the share button(represented by the 3 dots), you can open up the transcript of the youtube video. The code I have so far opens the URL, and turns on the closed caption(which works). from selenium import webdriver import requests driver = webdriver.Chrome() driver.get("https://www.youtube.com/watch?v=q1RYI034sH0") element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "ytp-subtitles-button"))) element.click() However, I know want to open the transcript by adding the following-code, which produces an error because it cannot locate the button. element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "yt-icon-button)"))) I am not really sure what to do from here, and any help to automate opening youtube's transcript is much appreciated.
tagged with: automation

http://stackoverflow.com/comment/89126445
comment on: http://stackoverflow.com/a/51068136
score: 0
has text: Is there actually a performance or a security difference there? Just asking, cuz I didn't find anything in the docs
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89096748
score: 0
comment on: http://stackoverflow.com/q/51052604
type: Comment
type: QuestionComment
has text: Seems that this is an Anaconda-specific issue. Try re-installing it a few times and it may fix itself. https://github.com/ContinuumIO/anaconda-issues/issues/172

http://stackoverflow.com/comment/89285281
comment on: http://stackoverflow.com/q/51150819
type: Comment
score: 1
type: QuestionComment
has text: The submit `button` is part of your web browser. Do you want to automate the browser? You could use [`selenium`](https://selenium-python.readthedocs.io/). Or do you just want to post data to a url? You can just use [**`requests.post`**](http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests) for that.

http://stackoverflow.com/q/51037957
answer count: 1
has comment: http://stackoverflow.com/comment/89067491
favorite count: 0
tagged with: python-3.x
has body: I've referenced this question How to generate all permutations of a list in Python, where I faced a similar scenario that expressed in this question. This time, I wanna generate all possible permutations(without an empty list [])of a list , and store it in another single list. E.g. the target list is a_list=[1, 2, 3], and I want something like: [ [1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] ] I've tried this code, which worked successfully (using built-in itertools module): import itertools perm = list() for i in range(1, len(a_list) + 1): perm.extend([list(x) for x in itertools.permutations(a_list, i)]) I wanna to try it in a list comprehension way, but I failed with this attempt: perm = [list(x) for x in permutations(a_list, i) for i in range(1, len(a_list)+1)] So is there any feasible list comprehension method to do this stuff?
linked to: http://stackoverflow.com/q/35479600
has answer: http://stackoverflow.com/a/51038481
tagged with: python
duplicate of: http://stackoverflow.com/q/35479600
type: AnsweredQuestion
upvote count: 2
score: 0
downvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/51038481
has title: Get all possible permutation of a list with list comprehension in python?
linked to: http://stackoverflow.com/q/104420

http://stackoverflow.com/comment/89303151
comment on: http://stackoverflow.com/q/51159898
type: QuestionComment
type: Comment
has text: So, if there can be no "Quote" at all, what is the pattern? Just digits? `df['your_cal'].str.extractall(r"(\d+)")`? Or, `df['your_col'].str.findall(r'\d+').apply(','.join)`?
score: 2

http://stackoverflow.com/q/51080795
has answer: http://stackoverflow.com/a/51080907
tagged with: nested
has body: I have a loop function that returns a complicated nested dictionary each time, which can be simplified like this: d= { "key1":"A", "key2":"B", "cumulative score":0.1, "direct score":0.4, "depth":0, "chain":[ {"key1":"A1", "key2":"B1", "cumulative score":0.2, "direct score":0.5, "depth":1, "chain":[{"key1":"A11", "key2":"B11","cumulative score":0.3, "direct score":0.6, "depth":2, "chain":[]}, {"key1":"A12", "key2":"B12","cumulative score":0.5, "direct score":0.7, "depth":2, "chain":[]}] }, {"key1":"A2", "key2":"B2","cumulative score":0.1, "direct score":0.2,"depth":1, "chain":[None, {"key1":"A22", "key2":"B22","cumulative score":0.1, "direct score":0.5, "depth":2, "chain":[]}] } ] } My real dictionary can go up to "depth"=10+, and can have a lot more data. Since I need to manually check the returned value in excel, I find copying the output window to clipboard and then to excel can create a clear way of showing the data like this: So I want to add such a function to do this at the end of my loop function. I have tried this def add_to_clipboard(text): import tempfile with tempfile.NamedTemporaryFile("w") as fp: fp.write(text) fp.flush() command = "pbcopy &lt; {}".format(fp.name) os.system(command) My question is: I got the following error, and I don't know to save the data on clipboard to excel. Can anyone help? Thanks. TypeError Traceback (most recent call last) &lt;ipython-input-102-8afb2d14c221&gt; in &lt;module&gt;() ----&gt; 1 add_to_clipboard(result_test) &lt;ipython-input-101-89cb10853a94&gt; in add_to_clipboard(text) 2 import tempfile 3 with tempfile.NamedTemporaryFile("w") as fp: ----&gt; 4 fp.write(text) 5 fp.flush() 6 command = "pbcopy &lt; {}".format(fp.name) ~\AppData\Local\Continuum\Miniconda3\envs\Battery\lib\tempfile.py in func_wrapper(*args, **kwargs) 481 @_functools.wraps(func) 482 def func_wrapper(*args, **kwargs): --&gt; 483 return func(*args, **kwargs) 484 # Avoid closing the file as long as the wrapper is alive, 485 # see issue #18879. TypeError:…
tagged with: clipboard
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51081164
tagged with: dictionary
has title: How to save complicated nested dictionary to clipboard and then to excel
tagged with: excel
score: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/89176798
type: Comment
type: QuestionComment
score: 0
has text: Why mark as negative without comment?
comment on: http://stackoverflow.com/q/51094378

http://stackoverflow.com/a/51146037
answers question: http://stackoverflow.com/q/51145596
score: 0
has body: //*[starts-with(@id, "bpr-guid")]
type: Answer

http://stackoverflow.com/comment/89055609
has text: SQLAlchemy automatically uses MySQLdb. But anyways, it turns out the documentation for MySQL's connect params is slightly misleading--MySQLdb's connect function actually requires the SSL params to be formatted like: `{'ssl':{'ca':'value'}}` instead of `{'sslca':'value'}`
type: AnswerComment
comment on: http://stackoverflow.com/a/51031187
type: Comment
score: 1

http://stackoverflow.com/comment/89328733
type: Comment
type: QuestionComment
has text: The units seem confusing. You say the distances are in meters but your code seems to treat them as kilometers. If the distances are in meters then such small amounts are swamped by glib estimates like `R = 6371` and `1.57` for `math.pi/2`. If they are in kilometers, then ignoring the curvature of the earth in computing distances isn't justified and in any event saying that a forklift is 33.86 kilometers away from a known location doesn't seem like a very sensible way to locate a machine within a factory. It would help if you made your question a [mcve] and say what the expected output is.
comment on: http://stackoverflow.com/q/51155780
score: 0

http://stackoverflow.com/q/51088946
has comment: http://stackoverflow.com/comment/89167015
has comment: http://stackoverflow.com/comment/89166903
type: Question
has comment: http://stackoverflow.com/comment/89166727
tagged with: base64
tagged with: image
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51089402
has comment: http://stackoverflow.com/comment/89167067
answer count: 1
has body: So I have this basic code at the moment. import base64 with open("test.png", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) And it converts the image into a crazy long string, I'm doing this of hopes of copying that string and making it a variable in another script I'm making. I don't want to save it to the computer or anything, I just want it to be decoded and opened for the GUI background. I'm trying to make it so just the exe is needed and nothing else. I've found other questions going over this, but sadly I can't quite understand the answers very well. So if possible the simplest way would be much preferred, thank you! Edit: The possible duplicate that was linked is fair, but it doesn't answer my question because as I said I don't understand what they did, why it works that way. And if i understand it at all I think it stores the image path but not the actual image in the exe. I want to be able to take the exe file and only that on a flash drive and it works.
downvote count: 0
has title: How to decode base64 string to its original image and open it without saving it
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51089402
tagged with: exe
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89167411
score: 1
has comment: http://stackoverflow.com/comment/89166672
linked to: http://stackoverflow.com/q/31836104
upvote count: 1

http://stackoverflow.com/comment/89130307
type: Comment
type: QuestionComment
has text: what output are you trying to achieve?
comment on: http://stackoverflow.com/q/51070127
score: 0

http://stackoverflow.com/a/51152869
has body: import pandas as pd # read a CSV with pandas src = "your/path" old_df = pd.read_csv(src, sep=",") # the columns that you want desired_cols = ['c1','c2'] # pandas will return a new df only with the columns that you want new_df = old_df[desired_cols]
type: Answer
answers question: http://stackoverflow.com/q/51152657
score: 0

http://stackoverflow.com/a/51164941
score: 0
answers question: http://stackoverflow.com/q/51164723
type: Answer
has body: You can tell the signature of a user defined function using function annotations. But actually it's just a meta information. It does not enforce any type checking rules. You can use a separate line type checker in modern editors like pycharm etc. These type checker acts as powerfull linter. Typically, Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. Refer- type hints

http://stackoverflow.com/comment/89234185
has text: I am still having a large sequence of spaces, any idea of how to delete them into a single space?
comment on: http://stackoverflow.com/a/51124428
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/55664742
answers question: http://stackoverflow.com/q/51072140
score: -1
upvote count: 1
downvote count: 2
type: Answer
has body: Python gets confused when you search for text that includes parenthesis. I can't just run your code since you are importing your dataframe, but I think if you just did: iFlow = Sales.loc[Sales['Product'].str.contains('\Vector HF/LF (Opt 2', na=False), "18-Jun"] it will work
has comment: http://stackoverflow.com/comment/134202857

http://stackoverflow.com/q/51128057
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51128144
has answer: http://stackoverflow.com/a/51128144
tagged with: pandas
upvote count: 1
answer count: 1
has body: Starting with Python, I ran into a problem that must be common but couldn't find a straightforward solution for. I have some fictional questionnaire data I would like to get meaningful descriptives on. Specifically, for each question I want to know how many times a particular response ("Yes"/"Maybe"/"No") was given. Input: Question1 Question2 Question3 Answer1 Maybe Yes Yes Answer2 No Maybe Yes Answer3 Maybe Maybe No Answer4 No Yes Maybe Now, I'd like to get a nice overview of the number of times a particular answer was given to a question. A preferred output would be something like this: (Preferred) Output: Yes Maybe No Question1 0 2 2 Question2 2 2 0 Question3 2 1 1 My own idea was that the solution must be in the 'groupby' command. So far I have not succeeded to get any meaningful output though: df.groupby(['Question1']).sum() Question2 Question3 Question1 Maybe YesMaybe YesNo No MaybeYes YesMaybe I have generated the dummy-data with: # Generate data data = np.array([['','Question1','Question2','Question3'],['Answer1',"Maybe","Yes","Yes"],['Answer2',"No","Maybe","Yes"],['Answer3',"Maybe","Maybe","No"],['Answer4',"No","Yes","Maybe"]]) # convert to pandas dataframe df = pd.DataFrame(data=data[1:,1:],index=data[1:,0],columns=data[0,1:]) I know this must be an easy challenge, but any help would be greatly appreciated.
favorite count: 0
has title: Summarizing categorical questionnaire data using pandas
tagged with: python

http://stackoverflow.com/comment/89324773
type: Comment
comment on: http://stackoverflow.com/a/51167266
has text: I think the interface is in these files: https://github.com/python/cpython/blob/12a08c47601cadea8e7d3808502cdbcca87b2ce2/Modules/posixmodule.c and https://github.com/python/cpython/blob/c7f02a965936f197354d7f4e6360f4cfc86817ed/Modules/clinic/posixmodule.c.h
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89092545
score: 0
has text: If you open the file in `wb` rather than `w` mode, you can write to the file as a bytes string. `f.write(bytes('[ {} ] {}\n'.format(t, discoverable_cards[cnt])))`. That way, your encoding won't get angry
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51050644

http://stackoverflow.com/comment/89019440
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51013259
score: 1
has text: Are you sure that the two files not yielding a result contain the required lines? I suggest that you reset audit_name and verified_hits at the start of the loop.

http://stackoverflow.com/a/51154800
has comment: http://stackoverflow.com/comment/89297576
has comment: http://stackoverflow.com/comment/89296853
has comment: http://stackoverflow.com/comment/89294665
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89296934
has comment: http://stackoverflow.com/comment/89297168
has comment: http://stackoverflow.com/comment/89297021
has comment: http://stackoverflow.com/comment/89293370
type: Answer
has comment: http://stackoverflow.com/comment/89296144
has comment: http://stackoverflow.com/comment/89297112
has body: Use Context.subcommand_passed to get the text of an attempted subcommand. @bot.group(pass_context=True) async def cool(ctx): if ctx.invoked_subcommand is None: if ctx.subcommand_passed: await bot.say("**Wrong sub command: **{}".format(ctx.subcommand_passed)) else: await bot.say("Subcommand required") @cool.command(pass_context=True, name="bot") async def _bot(ctx): msg = "Hello ...".format(ctx.message) await bot.say(msg) An unrecognized top-level command will raise CommandNotFound, which you'll have to handle in on_command_error. I believe it should still populate ctx.command with the attempted command, but I can't check at the moment. You might also try ctx.invoked_with @bot.event async def on_command_error(error, ctx): if isinstance(error, commands.CommandNotFound): await bot.send_message(ctx.message.channel, "**Wrong command ** " + ctx.command)
has comment: http://stackoverflow.com/comment/89293803
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51149680
score: 1
answers question: http://stackoverflow.com/q/51149680

http://stackoverflow.com/q/51156339
tagged with: text
score: -4
possible better answer: http://stackoverflow.com/a/51156723
has title: duplicate individual paragraphs in txt file
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51156541
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/89296319
has comment: http://stackoverflow.com/comment/89296621
has answer: http://stackoverflow.com/a/51156541
tagged with: repeat
tagged with: python
has answer: http://stackoverflow.com/a/51156723
has body: I have a programme in which I need to duplicate each individual block of text multiple times so that it repeats. This is what I have. echo update echo snapshot echo gall echo clearobj echo read rot_003.speck echo update echo snapshot echo gall echo clearobj echo read rot_004.speck except there are 150 rot_"n".speck files, giving 150 individual paragraphs, so doing this manually is not possible. The form I need the data in is as follows: echo update echo snapshot echo gall echo clearobj echo read rot_003.speck echo update echo snapshot echo gall echo clearobj echo read rot_003.speck echo update echo snapshot echo gall echo clearobj echo read rot_003.speck echo update echo snapshot echo gall echo clearobj echo read rot_004.speck echo update echo snapshot echo gall echo clearobj echo read rot_004.speck echo update echo snapshot echo gall echo clearobj echo read rot_004.speck Is there a simple code for this. Preferably in python if possible. Thanks
favorite count: 0

http://stackoverflow.com/comment/89135978
type: AnswerComment
has text: huh? i'm not looking to abstract the paths, as you put. **also, it's `.text`, not `.txt`,** but since you're denying all of my edits... and this should be handled elsewhere in the code, but doesn't really matter if you leave it in your answer
type: Comment
comment on: http://stackoverflow.com/a/51073019
score: 0

http://stackoverflow.com/q/51114259
has title: I am stuck in while True loop
upvote count: 1
has answer: http://stackoverflow.com/a/51114511
has answer: http://stackoverflow.com/a/51114309
has answer: http://stackoverflow.com/a/51114582
tagged with: python-2.7
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89214800
answer count: 4
downvote count: 0
score: 1
type: Question
has body: Python 2.7. I am new to Python and I am stuck with while True loop. Simple program to calculate salary. When 'standard' entered as a letter, it catches the error and jumps again to the line 'Enter your rate'. I want it to be repeated only where the error was captured and not starting to input all info all over again. Can someone help please? while True: try: rate = float(raw_input("Enter your rate: ")) error = float(rate) standard = float(raw_input("Enter total standard hours 100%: ")) error = float(standart) except: print 'Not a number' continue else: sum = standard * rate print sum Thank you in advance.
has answer: http://stackoverflow.com/a/51114359

http://stackoverflow.com/a/51047499
type: Answer
has comment: http://stackoverflow.com/comment/89117018
answers question: http://stackoverflow.com/q/51047179
upvote count: 2
has comment: http://stackoverflow.com/comment/89087518
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89109138
has body: iterrows() return not just a row as you expect, but the tuple of row index and row itself. So this tuple of two values doesn't have index 6, so you get the Exception: "tuple index out of range" (pay attention to tuple) If you don't need row index, you can use any name, the best one is _ which is a correct variable name and it is used in python to mark variabales that you don't need. So the correct loop code is for _, row in XDFDF.iterrows(): for _, row2 in XDFDF.iterrows(): Or if the index is just a sequence of integers from 0, you can use it instead of ct1 and ct2 if you assume ct2 should be reset to 0 at the begining of each loop for row2 (by the way there is no ct2 = 0 before this loop which might be a logical error). To ensure the index is really like needed I would recomend force reset_index(drop=True) before the loop. Otherwise it would be difficult to find problem if you would manipulate with data before and break the index sequence. But in fact if you only need to find duplicate values (you code is not doing exactly that but I'm not sure if this is assumed or a logical error in the code) you can use pandas drop_duplicates which will do all the work for you. So we can create column "unique" and set True for those indexes which aren't dropped as duplicate XDFDF["unique"] = False indexes_of_unique = XDFDF.loc[:, 6].drop_duplicates(keep=False).index XDFDF.loc[indexes_of_unique, "unique"] = True This part is the most important XDFDF.loc[:, 6].drop_duplicates(keep=False).index. It gets the column 6, drops duplicate values (by default it keeps one duplicate value, but keep=False forces drop all values which have duplicates). So now we have the indexes of unique values and we can mark them. Important note, that indexes in pandas aren't guaranteed to be uniuqe, so I'd recomend to make XDFDF.reset_index(drop=True, inplace=True) to ensure there wouldn't be logical collisions with duplicate indexes.

http://stackoverflow.com/comment/89177370
type: Comment
comment on: http://stackoverflow.com/a/51094719
type: AnswerComment
has text: If previous char is equal to current char then i am removing the previous char from the new_answer. Replace function removes that char and substitutes with “” in its place. Also, since i want to only remove that character once at a specific location, that location information is provided by count.
score: 0

http://stackoverflow.com/q/51062807
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51062917
has body: So I'm currently trying to simulate an Insecure Deserialization attack. Here's the code I'm using: import yaml with open('malicious.yml') as yaml_file: contents = yaml.load(yaml_file) print(contents['foo']) The file malicious.yml contains the following: foo: !!python/object/apply:subprocess.check_output ['ls'] However, when I run the script, I get the following error: yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:subprocess.check_output' in "malicious.yml", line 1, column 6 I looked around a bit but still couldn't find why. Any help would be appreciated.
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51062917
tagged with: pyyaml
type: Question
has title: PyYAML giving constructor errors?
linked to: http://stackoverflow.com/q/51053903
duplicate of: http://stackoverflow.com/q/51053903
tagged with: yaml

http://stackoverflow.com/a/51311172
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51146949
type: Answer
has body: This amounts to choosing which three of the six entries above the diagonal are 1. From the list of above-the-diagonal positions in a 4 by 4 matrix: sage: positions = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] use Sage's Subsets to get all subsets of size 3 of those positions. sage: S = Subsets([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)], 3) Then build the corresponding matrices. sage: [matrix(ZZ, 4, lambda i, j: (i, j) in s or (j, i) in s) for s in S] [ [0 1 1 1] [0 1 1 0] [0 1 1 0] [0 1 1 0] [0 1 0 1] [0 1 0 1] [1 0 0 0] [1 0 1 0] [1 0 0 1] [1 0 0 0] [1 0 1 0] [1 0 0 1] [1 0 0 0] [1 1 0 0] [1 0 0 0] [1 0 0 1] [0 1 0 0] [0 0 0 0] [1 0 0 0], [0 0 0 0], [0 1 0 0], [0 0 1 0], [1 0 0 0], [1 1 0 0], [0 1 0 1] [0 1 0 0] [0 1 0 0] [0 1 0 0] [0 0 1 1] [0 0 1 1] [1 0 0 0] [1 0 1 1] [1 0 1 0] [1 0 0 1] [0 0 1 0] [0 0 0 1] [0 0 0 1] [0 1 0 0] [0 1 0 1] [0 0 0 1] [1 1 0 0] [1 0 0 0] [1 0 1 0], [0 1 0 0], [0 0 1 0], [0 1 1 0], [1 0 0 0], [1 1 0 0], [0 0 1 1] [0 0 1 0] [0 0 1 0] [0 0 1 0] [0 0 0 1] [0 0 0 1] [0 0 0 0] [0 0 1 1] [0 0 1 0] [0 0 0 1] [0 0 1 1] [0 0 1 0] [1 0 0 1] [1 1 0 0] [1 1 0 1] [1 0 0 1] [0 1 0 0] [0 1 0 1] [1 0 1 0], [0 1 0 0], [0 0 1 0], [0 1 1 0], [1 1 0 0], [1 0 1 0], [0 0 0 1] [0 0 0 0] [0 0 0 1] [0 0 1 1] [0 0 0 1] [0 1 0 1] [1 1 1 0], [0 1 1 0] ] Note that these are the adjacency matrices for all graphs with three edges on four labeled vertices. If you want un-labeled vertices, or equivalently the list of adjacency matrices of equivalence classes of graphs with three edges on four vertices, you could use Nauty to enumerate them. Here is how to do that from Sage: sage: G = graphs.nauty_geng("4 3:3") sage: G &lt;generator object nauty_geng at 0x21c89a0f0&gt; sage: [g.adjacency_matrix() for g in G] [ [0 0 0 1] [0 0 1 1] [0 0 1 1] [0 0 0 1] [0 0 0 1] [0 0 0 0] [0 0 0 1] [1 0 0 0] [1 0 0 1] [1 1 1 0], [1 1 0 0], [1 0 1 0] ]

http://stackoverflow.com/comment/89131412
has text: Go with @mostlyoxygen's masking solution.
type: Comment
comment on: http://stackoverflow.com/a/51058722
score: 0
type: AnswerComment

http://stackoverflow.com/q/51021749
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89035972
has comment: http://stackoverflow.com/comment/89036034
has answer: http://stackoverflow.com/a/51021927
has answer: http://stackoverflow.com/a/51021810
type: Question
has body: I'm working from a book, very much newbie stuff, and the code below is from the book, and defines a simple class. But for some reason, the author has decided to put a "helper method" called check_index outside the class. I cannot for the life of me figure out why he would do this, as the method seems integral to teh operation of the class. He writes: The index checking is taken care of by a utility function I’ve written for the purpose, check_index. I have tried putting it inside the class (the code below is as it is in the book), but the runtime refuses to find the method - it falls over with NameError: name 'check_index' is not defined My questions are, why did the author put this "helper method" outside the class, and why does the code not work when I move the method inside the class: class ArithmeticSequence: def __init__(self, start=0, step=1): self.start = start # Store the start value self.step = step # Store the step value self.changed = {} # No items have been modified def __getitem__(self, key): check_index(key) try: return self.changed[key] # Modified? except KeyError: # otherwise ... return self.start + key * self.step # ... calculate the value def __setitem__(self, key, value): check_index(key) self.changed[key] = value # Store the changed value def check_index(key): if not isinstance(key, int): raise TypeError if key &lt; 0: raise IndexError When I move the method inside the class, I just slot it in with the other methods. But it is not found by the runtime. Why? class ArithmeticSequence: def __init__(self, start=0, step=1): self.start = start # Store the start value self.step = step # Store the step value self.changed = {} # No items have been modified def check_index(key): if not isinstance(key, int): raise TypeError if key &lt; 0: raise IndexError def __getitem__(self, key): check_index(key) try: return self.changed[key] # Modified? except KeyError: # otherwise ... return self.start + key * self.step # ... calculate the value def __setitem__(self, k…
has comment: http://stackoverflow.com/comment/89036368
has answer: http://stackoverflow.com/a/51021936
has title: Python NameError: name is not defined - method not found
score: 0
answer count: 3
tagged with: python-3.x

http://stackoverflow.com/q/51098231
upvote count: 1
favorite count: 0
answer count: 3
has body: I am talking about the Class, not the object. The reason lies that I created a Class which produces some objects but for matters of efficiency I did assign some static variables to some of its methods. In some situations, I want to re-initialise the Class, i.e. set all its static variables to their initial value if any. How can I do that without re-assigning each variable one by one? For instance, if we have the below Class: class tst: def lol(self): self.lol.__dict__['static_magic'] = True After assigning some objects: # A demonstration of how these work and are the same if one is activated. &gt;&gt;&gt; a = tst() &gt;&gt;&gt; b = tst() &gt;&gt;&gt; a.lol() &gt;&gt;&gt; a.lol.__dict__ {'static_magic': True} # Then when running object b (without lol()) has also the variable static magic. &gt;&gt;&gt; b.lol.__dict__ {'static_magic': True} Afterwards, I decide that is time to re-initiate all its static variables and start assigning from the begging. What I want is the following. &gt;&gt;&gt; c = tst() &gt;&gt;&gt; c.lol.__dict__ {} What should do? Having a copy of the function won't work (static are cross-referenced), deleting and importing also fails and do not looks good.
possible better answer: http://stackoverflow.com/a/51098315
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/51098843
accepted answer: http://stackoverflow.com/a/51098843
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51098315
has answer: http://stackoverflow.com/a/51098615
score: 1
tagged with: class
type: Question
has title: How can one re-initiate a "Class"; its static variables

http://stackoverflow.com/comment/89176171
has text: As per your suggestion I've used `str(username)` and it works. But I've used it here: `for qs in queryset: username = str(qs.username) keyname = random_name('.pem') certname = random_name('.pem') password = random_name('') gen_cert(keyname, certname, password, username)` This even resolved the 2nd error.
comment on: http://stackoverflow.com/a/51087761
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51053344
tagged with: javascript
has answer: http://stackoverflow.com/a/51059913
score: 0
has title: Dynamically update models
tagged with: model
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/5478432
has comment: http://stackoverflow.com/comment/89097856
has answer: http://stackoverflow.com/a/51055288
has body: I have a signup form that works great. One feature of it is users can press "Add more +" and have more identical "instrument" and "level" select fields created. The model only saves the first "instrument" and "level" field and not the further ones created from the javascript function. How can I adjust my model to create further fields when the javascript function is called? I appreciate any help I get. models.py class User(AbstractBaseUser): instrument = models.CharField(max_length=255, choices=instrument_list) level = models.CharField(max_length=255, choices=level_list) HTML {{ form.instrument }} {{ form.level }} Add more + Javascript var i = 0; var original = document.getElementById('ins'); function add_instrument() { var clone = original.cloneNode(true); clone.id = "ins" + ++i; original.parentNode.appendChild(clone); }
type: Question
answer count: 2

http://stackoverflow.com/q/51029298
answer count: 1
tagged with: python-3.x
has title: How to add Tick Mark Number Labels to Graph?
tagged with: python
has body: I am trying to make a graph with this: import matplotlib.pyplot as plt from numpy import * from scipy.interpolate import * x= array([13, 15,18,20,25,30]) y= array([2.29E+60, 3.87E+60, 7.12E+60, 1.07E+61, 1.90E+61, 3.34E+61]) y2= 7.0867E+56 * x**3.177 plt.xlabel('M/Msun') plt.ylabel('Average Rate of Nucleosynthesis') plt.xscale('log') plt.yscale('log') plt.yticks((min(y),max(y), 1)) plt.plot(x,y, 'o', color='black') plt.plot((x),y2,'black') plt.show() And then I get this type of graph: The tickmarks on the y-axis do not show up. Any idea of how to fix this?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51034685
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/51034685
linked to: http://stackoverflow.com/q/14530113
score: 0

http://stackoverflow.com/q/51053492
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51053757
upvote count: 1
type: Question
has title: extracting a field from HTML with BeautifulSoup4
has body: I'm using BeautifulSoup4 for the first time, and get stuck with a something that must be straightforward. I have an Element Tag which looks like this: \n \n Phase 3\n \n<g fill="none" transform="translate(1 1 )">\n \n \n \n \n \n \n</g>\n I want to extract value "phase3" from the "data-value" field and a list of fill colors, like [ "#911C36", "#D6A960", ... ] What are the right queries for that?
accepted answer: http://stackoverflow.com/a/51053757
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89282228
comment on: http://stackoverflow.com/a/51137318
score: 0
type: Comment
has text: Why are you using `subprocess.call()`? Is it just to run the code in parallel? If so, you could import the modules you require and use the [threading module](https://docs.python.org/3/library/threading.html) instead.
type: AnswerComment

http://stackoverflow.com/a/51071441
score: 0
downvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51071385
type: Answer
answers question: http://stackoverflow.com/q/51071385
has body: After restarting the index, I indeed simply deleted/dropped the constraints and indices that were giving "already exists" errors and managed to migrate: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate Operations to perform: Apply all migrations: admin, auditlog, auth, contenttypes, defender, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor Running migrations: Applying lucy_web.0163_auto_20180627_1309... OK
upvote count: 2

http://stackoverflow.com/comment/89239410
type: QuestionComment
comment on: http://stackoverflow.com/q/51127209
score: 0
type: Comment
has text: @Likedapro see my answer

http://stackoverflow.com/comment/89214242
comment on: http://stackoverflow.com/q/51113885
has text: Can you show the full stack trace please
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89044861
comment on: http://stackoverflow.com/q/51025568
score: 0
has text: name has the final file name with the extension with it.It needs the rest of the path too maybe??
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89060082
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51033985
has text: This is a comment, not an answer.
type: Comment

http://stackoverflow.com/comment/89257417
type: Comment
has text: Thank you @jezrael, this function really helped me and the question is really duplicated!
type: QuestionComment
comment on: http://stackoverflow.com/q/51103259
score: 1

http://stackoverflow.com/a/51065493
has comment: http://stackoverflow.com/comment/89138217
has comment: http://stackoverflow.com/comment/89157497
upvote count: 1
has comment: http://stackoverflow.com/comment/89121042
score: 1
has comment: http://stackoverflow.com/comment/89138874
has comment: http://stackoverflow.com/comment/89121089
answers question: http://stackoverflow.com/q/51065102
downvote count: 0
has comment: http://stackoverflow.com/comment/89157626
has body: Here is a simple example of adding an image to the label. Keep in mind you will need to make sure that a reference to the image is saved or else you will not see an image in your app. Update: I believe this updated answer should work for you. The code will try to grab the image from clipboard using the ImageGrab method in PIL if there is one and then it saves the image to a temp folder. We then load that image to the label and then delete the image from the temp folder. import tkinter as tk import os from tkinter import messagebox from PIL import ImageTk, ImageGrab root = tk.Tk() tb8 = tk.Label(root, width=82) tb8.grid(row=0, column=0, sticky='nsew') def imgps(): try: temp_path = "./TempImage/some_image.gif" # Whatever temp path you want here im = ImageGrab.grabclipboard() # Get image from clipboard im.save(temp_path) # save image to temp folder load_for_label = ImageTk.PhotoImage(file=temp_path) # load image from temp folder tb8.config(image=load_for_label) # set image to label tb8.image = load_for_label # save reference to image in memory tb8.clipboard_clear() # clear clipboard os.remove(temp_path) # delete temp file except: messagebox.showinfo(message="Clipboard is Empty.") pbtn11 = tk.Button(root, text="IMAGE", command=imgps) pbtn11.grid(row=1, column=0, sticky='nsew') root.mainloop() I did try several ways to load the image directly from the clipboard but I kept running into errors. So my above solutions might not be 100% the fastest way to implement this but should work well enough.
has comment: http://stackoverflow.com/comment/89156871
has comment: http://stackoverflow.com/comment/89127117
type: Answer
has comment: http://stackoverflow.com/comment/89120889
has comment: http://stackoverflow.com/comment/89138472

http://stackoverflow.com/comment/89198722
has text: Wrong host, firewall/network connection issue, or no running server (http vs https?) on the target machine. *A TCP connection was not / could not be established to the server*, and thus there was no authentication attempt. If if was an HTTP/bearer authentication issue after a connection had been made, there would have been *a* HTTP response message with code - eg. a 403.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51105793
type: QuestionComment

string
tags question: http://stackoverflow.com/q/51119315
tags question: http://stackoverflow.com/q/51102806
tags question: http://stackoverflow.com/q/51056840
tags question: http://stackoverflow.com/q/51162285
tags question: http://stackoverflow.com/q/51051619
tags question: http://stackoverflow.com/q/51145039
tags question: http://stackoverflow.com/q/51133287
tags question: http://stackoverflow.com/q/51140707
tags question: http://stackoverflow.com/q/51062603
tags question: http://stackoverflow.com/q/51016482
tags question: http://stackoverflow.com/q/51078210
tags question: http://stackoverflow.com/q/51100847
tags question: http://stackoverflow.com/q/51035522
tags question: http://stackoverflow.com/q/51050397
tags question: http://stackoverflow.com/q/51063249
tags question: http://stackoverflow.com/q/51026089
tags question: http://stackoverflow.com/q/51144127
tags question: http://stackoverflow.com/q/51092258
tags question: http://stackoverflow.com/q/51068498
tags question: http://stackoverflow.com/q/51121911
tags question: http://stackoverflow.com/q/51046407
tags question: http://stackoverflow.com/q/51039943
tags question: http://stackoverflow.com/q/51062473
tags question: http://stackoverflow.com/q/51027151
tags question: http://stackoverflow.com/q/51090548
tags question: http://stackoverflow.com/q/51094430
tags question: http://stackoverflow.com/q/51139011
tag name: string
tags question: http://stackoverflow.com/q/51154528
tags question: http://stackoverflow.com/q/51114186
tags question: http://stackoverflow.com/q/51167397
tags question: http://stackoverflow.com/q/51119584
tags question: http://stackoverflow.com/q/51089650
tags question: http://stackoverflow.com/q/51112320
tags question: http://stackoverflow.com/q/51121200
tags question: http://stackoverflow.com/q/51167254
tags question: http://stackoverflow.com/q/51025882
tags question: http://stackoverflow.com/q/51062073
tags question: http://stackoverflow.com/q/51137021
tags question: http://stackoverflow.com/q/51062873
tags question: http://stackoverflow.com/q/51055596
type: Tag
tags question: http://stackoverflow.com/q/51039842
tags question: http://stackoverflow.com/q/51149550
tags question: http://stackoverflow.com/q/51069286
tags question: http://stackoverflow.com/q/51059924
tags question: http://stackoverflow.com/q/51094627
tags question: http://stackoverflow.com/q/51143317
tags question: http://stackoverflow.com/q/51156507
tags question: http://stackoverflow.com/q/51014201
tags question: http://stackoverflow.com/q/51070538
tags question: http://stackoverflow.com/q/51035731
tags question: http://stackoverflow.com/q/51091641
tags question: http://stackoverflow.com/q/51021662
tags question: http://stackoverflow.com/q/51143196
tags question: http://stackoverflow.com/q/51052112
tags question: http://stackoverflow.com/q/51095716
tags question: http://stackoverflow.com/q/51161854
tags question: http://stackoverflow.com/q/51093963
tags question: http://stackoverflow.com/q/51090971
tags question: http://stackoverflow.com/q/51140575
tags question: http://stackoverflow.com/q/51164294
tags question: http://stackoverflow.com/q/51086772
tags question: http://stackoverflow.com/q/51085180
tags question: http://stackoverflow.com/q/51104478
tags question: http://stackoverflow.com/q/51154179
tags question: http://stackoverflow.com/q/51045771
tags question: http://stackoverflow.com/q/51124037
tags question: http://stackoverflow.com/q/51042791
tags question: http://stackoverflow.com/q/51118801
tags question: http://stackoverflow.com/q/51042399
tags question: http://stackoverflow.com/q/51025536
tags question: http://stackoverflow.com/q/51085069
tags question: http://stackoverflow.com/q/51069117
tags question: http://stackoverflow.com/q/51102615
tags question: http://stackoverflow.com/q/51045207
tags question: http://stackoverflow.com/q/51050146
tags question: http://stackoverflow.com/q/51044731
tags question: http://stackoverflow.com/q/51125006
tags question: http://stackoverflow.com/q/51066934

http://stackoverflow.com/q/51119623
tagged with: python-itertools
has title: How to create columns based on combinations of values between 2 sets of columns?
has answer: http://stackoverflow.com/a/51119891
accepted answer: http://stackoverflow.com/a/51119669
tagged with: dataframe
has body: I have a dataframe with comma separated values that i split out out using pd.concat. original df: org country type Orange USA, GBR, AUS OWF, PMR, KIQ Red AUS, RUS, NZL DOG, MOP, LOF splitting out columns gives me a df, which we'll call df_wide, org country_1 country_2 country_3 type_1 type_2 type_3 Orange USA GBR AUS OWF PMR KIQ Watermelon AUS RUS NZL ODG MOP LOF From the above dataframe, i need to get every possible combination of a single country and single type in a long format: org country type Orange USA OWF Orange USA PMR Orange USA KIQ Orange GBR OWF Orange GBR PMR Orange GBR KIQ ..and so forth and this is where I'm stuck. I mistakenly thought that i could just transform the dataframe using pd.wide_to_long, but I think the answer my revolves around using itertools. I've searched the forums that relate to this issue, but I still haven't quite figured it out. Looking for any suggestions! also the commas separated values in the original df columns could be dozens of values and therefore I don’t know how many columns wide my wide df will be.
upvote count: 3
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/30808430
has answer: http://stackoverflow.com/a/51119669
favorite count: 0
possible better answer: http://stackoverflow.com/a/51119891
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51119728

http://stackoverflow.com/q/51091377
upvote count: 5
downvote count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51091744
has title: How to compute volume of 10-Dimentional sphere with Monte-Carlo-Method in Python?
has body: I am trying to compute the volume of a 10 dimensional sphere with python, but my computation doesn't work. Here is my code: def nSphereVolume(dim,iter): i = 0 j = 0 r = 0 total0 = 0 total1 = 0 while (i &lt; iter): total0 = 0; while (j &lt; dim): r = 2.0*np.random.uniform(0,1,iter) - 1.0 total0 += r*r j += 1 if (total0 &lt; 1): total1 += 1 i += 1 return np.pow(2.0,dim)*(total1/iter) nSphereVolume(10,1000) Here the error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-253-44104dc9a692&gt; in &lt;module&gt;() 20 return np.pow(2.0,dim)*(total1/iter) 21 ---&gt; 22 nSphereVolume(10,1000) &lt;ipython-input-253-44104dc9a692&gt; in nSphereVolume(dim, iter) 14 j += 1 15 ---&gt; 16 if (total0 &lt; 1): 17 total1 += 1 18 i += 1 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Could someone who knows this algorithm try to run it and tell me what would be corret to implement, to get the volume of this 10-dim sphere? Thanks!
favorite count: 0
type: Question
score: 5
tagged with: python
tagged with: montecarlo
answer count: 1
tagged with: math
has answer: http://stackoverflow.com/a/51091744
tagged with: numpy

http://stackoverflow.com/a/51045665
upvote count: 1
has body: Put app_name='accounts' variable in your /project/apps/accounts/ulrs.py file
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51045572
has comment: http://stackoverflow.com/comment/89082578
has comment: http://stackoverflow.com/comment/89087648
type: Answer

http://stackoverflow.com/comment/89724359
has text: Thanks, this makes sense, although feels a bit heavyweight for the underlying issue. Is it necessary to specify the encoding?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51305341

http://stackoverflow.com/a/51084798
type: AcceptedAnswer
has body: Yeah, turns out I defined dbSMS the wrong way. QuerySet returned me args and kwargs and I totally ignored them in __init__ and just blindly passed them to parent class. Here's how it works now: class dbSMS(db.DynamicDocument): sender = db.StringField(max_length=12, required=True) target = db.StringField(max_length=12, required=True) message = db.StringField(max_length=255, required=True) status = db.StringField(required=False) meta = { 'collection': 'sms', } I got rid of whole __init__ altogether and changed parent class to DynamicDocument (because I might require that kind of scalability). Now it works exactly as expected. Hope my stupid silly mistake helps someone.
type: Answer
answers question: http://stackoverflow.com/q/51065761
accepted answer of: http://stackoverflow.com/q/51065761
score: 0

http://stackoverflow.com/comment/89031967
comment on: http://stackoverflow.com/a/51019364
has text: the first is give different output that I expected, the third `AttributeError: 'DataFrame' object has no attribute 'locations'` but the second works very well
score: 1
type: AnswerComment
type: Comment

fractions
type: Tag
tags question: http://stackoverflow.com/q/51014628
tag name: fractions

http://stackoverflow.com/q/51117943
tagged with: numpy
has comment: http://stackoverflow.com/comment/89222025
answer count: 1
tagged with: arrays
downvote count: 0
has title: Numpy: Adding specific columns of rows conditionally
has comment: http://stackoverflow.com/comment/89222050
favorite count: 0
linked to: http://stackoverflow.com/q/50121980
has body: For a given numpy array: [[1, 1, 'IGNORE_THIS_COL', 100], [1, 1, 'IGNORE_THIS_COL', 101], [1, 2, 'IGNORE_THIS_COL', 100]] Is it possible to sum the rows (and columns conditionally)? Say column 0 is group and column 1 is user, then I would like to add the fourth column accordingly. The final 'summed' array should look like this. [[1, 1, 'IGNORE_THIS_COL', 201], [1, 2, 'IGNORE_THIS_COL', 100]] I have already checked multiple answers, including Numpy: conditional sum.
has comment: http://stackoverflow.com/comment/89222047
tagged with: python
accepted answer: http://stackoverflow.com/a/51117971
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51117971

http://stackoverflow.com/comment/89122141
score: 0
type: Comment
type: QuestionComment
has text: I have python installed on my Mac and thought by enabling it on WebServer it would run. I was able to get a simple Hello World script to run now but my other script will not. Perhaps it's due to calling a module?
comment on: http://stackoverflow.com/q/51064653

http://stackoverflow.com/comment/89258535
type: QuestionComment
has text: @n.m. yes as written by chepner I want to minimize the pairwise absolute difference between all points in a set (or alternatively as said also the sum of the difference can be used or even the standard deviation between the proposed points)
comment on: http://stackoverflow.com/q/51124015
score: 0
type: Comment

http://stackoverflow.com/comment/89031966
type: Comment
comment on: http://stackoverflow.com/a/51018581
score: 1
has text: As I predicted from doing the arithmetic I showed you: "Matplotlib represents dates using floating point numbers specifying the number of days since 0001-01-01 UTC, plus 1." And furthermore, I predicted: "There are a number of helper functions to convert between datetime objects and Matplotlib dates... num2date(): Convert Matplotlib dates to datetime objects."
type: AnswerComment

http://stackoverflow.com/comment/89301049
comment on: http://stackoverflow.com/a/51158760
score: 1
has text: Unfortunately I can't upgrade paramiko as Bees with Machine Guns uses a specific version. However I actually fixed it by going into that paramiko python file and changing async to be async_ so thanks for the heads up about the keyword change!
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51024019
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89040639
tagged with: python
has title: Finding the largest variable in a list while the output is still a variable not a number
has comment: http://stackoverflow.com/comment/89040532
downvote count: 2
type: Question
upvote count: 0
score: -2
tagged with: bubble-sort
has answer: http://stackoverflow.com/a/51024163
has comment: http://stackoverflow.com/comment/89040594
has body: I have been trying to make a code which sorts a list of variables. I am aware it is possible to do this in many ways, including bubble sort, which I'm trying to use. However when I use bubble sort to sort my list the output is always in numbers instead of the variable names. Sorry if the answer is obvious, I am new to Python. A = 5 B = 7 c= 8 def bubblesort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]&gt;alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = [B,A,c] bubblesort(alist) print(alist)
has comment: http://stackoverflow.com/comment/89040990
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51079104
accepted answer: http://stackoverflow.com/a/51080159
has body: I have a python project that uses Postgresql. I would like to use django-like unit tests where the database is created and destroyed at every test. However, I don't want to use sqlalchemy. I tried something along these lines: pg = psycopg2.connect( "host={} dbname={} user={} password={}".format( POSTGRES_HOST, 'postgres', POSTGRES_USER, POSTGRES_PASSWORD)) pg.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = pg.cursor() def reset_db(): cur.execute('DROP DATABASE IF EXISTS {} '.format(POSTGRES_DB)) cur.execute('CREATE DATABASE {}'.format(POSTGRES_DB)) newconn = psycopg2.connect( "host={} dbname={} user={} password={}".format( POSTGRES_HOST, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD)) newcur = newconn.cursor() # SCHEMAS is an imported dict containing schema creation instructions for schema in SCHEMAS: newcur.execute(SCHEMAS[schema]) return newcur class Test(TestCase): def setUp(self): os.environ['testing'] = 'true' self.cur = reset_db() Then the setUp method sets an environmental variable that informs my database layer to use the testing db. This seems to work fine. The only problem is the reset_db() takes about 0.8 seconds, which is far too much. Are there better approaches or ways to optimise my approach?
score: 0
has title: Django-like unit testing database in plain python
answer count: 2
tagged with: postgresql
has answer: http://stackoverflow.com/a/51080031
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: unit-testing
type: Question
possible better answer: http://stackoverflow.com/a/51080031
has answer: http://stackoverflow.com/a/51080159

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/51049195
tags question: http://stackoverflow.com/q/51055956
tags question: http://stackoverflow.com/q/51098959

http://stackoverflow.com/comment/121598935
score: 0
type: Comment
type: QuestionComment
has text: Examples must be use by Scenario outline. https://jenisys.github.io/behave.example/tutorials/tutorial04.html
comment on: http://stackoverflow.com/q/51141878

http://stackoverflow.com/q/51151510
has body: following code to start: products = [{ "id": x.id, "fabric": x.fabric.name, "fabricimg": x.fabric.fabric_cover.url, } for x in entry_obj.all()] cart_data = { "products": products, "total": cart_obj.total } return JsonResponse(cart_data) This works fine for creating my list products with the dictionaries from the x(objects) in entry_obj.all(). But now I have the scenario that I have some x(objects) with no x.fabric.name, and instead will have to use a filler for example a simple string like "noname". How can I use an if statement in the existing for loop to catch the case of name not existing and instead setting the key fabric to my string value? I thought of using: if hasattr(entry_obj,"name") &gt; "fabric": x.fabric.name else &gt; "fabric": "noname" But I'm unsure where to put it in the for loop plus how to iterate through the x(objects) in entry_obj for that matter so I can still give Json the right cart_data.
type: Question
has answer: http://stackoverflow.com/a/51151599
has title: Dictionary list from a for loop with if else hasattr
duplicate of: http://stackoverflow.com/q/4075190
accepted answer: http://stackoverflow.com/a/51151599
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/4075190
score: 2
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/51132974
upvote count: 1
has body: You can replace everything from token_map = {} and after with: return Counter(token for token in map(str.lower, tokens) if english_dict.check(token) if token not in stop_words ).most_common() Add this import to the top of the file: from collections import Counter
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51132676
score: 1

http://stackoverflow.com/q/51046266
accepted answer: http://stackoverflow.com/a/51047053
tagged with: networkx
type: AnsweredQuestion
has title: error with random.sample: raise NotImplementedError(" >= and <= don't work with 0.") NotImplementedError: >= and <= don't work with 0
has body: I have a problem with this code, I really dont understand why it cannot reach the second cycle of the most internal for: def remove_random_links(A,E): rs = random.sample(A.edges, E) A.remove_edges_from(rs) N = 30 L = [0,60,30,40,30,30,20,40] rep = 15 d = [] g = [] for j in range(rep): R = nx.grid_graph(dim=[N,N]) _deg = [] _gap = [] for i in L: remove_random_links(R,i) A = nx.adj_matrix(R) L = nx.laplacian_matrix(R) eigwd, eigv = LA.eigh(L.todense()) eigw = np.sort(eigwd) eigw0 = eigw[0] eigw1 = eigw[1] eigw2 = eigw[2] eigw3 = eigw[3] gap = eigw2 - eigw1 deg = eigw3 - eigw2 _deg.append(deg) _gap.append(gap) print("meow") d.append(_deg) g.append(_gap) print("M") mean_deg = [np.mean(d[i]) for i in range(rep)] mean_gap = [np.mean(g[i]) for i in range(rep)] std_deg = [np.std(d[i]) for i in range(rep)] std_gap = [np.std(g[i]) for i in range(rep)] It goes on its first for cycle (the one in j) and then into its first for cycle in i, it completes it and then it is not able to do the second one because of this error with the function remove_random_links(), which gives me the following error: File "/Users/Sofia/Desktop/delta.py", line 23, in remove_random_links(R,i) File "/Users/Sofia/Desktop/delta.py", line 9, in remove_random_links rs = random.sample(A.edges, E) File "/anaconda3/lib/python3.6/random.py", line 317, in sample if not 0 &lt;= k &lt;= n: File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 322, in ge "Comparing a sparse matrix with a scalar " File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 272, in _inequality raise NotImplementedError(" >= and &lt;= don't work with 0.") NotImplementedError: >= and &lt;= don't work with 0.
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/51047053
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/89084456
tagged with: random
tagged with: python
has comment: http://stackoverflow.com/comment/89084575

http://stackoverflow.com/q/51028400
favorite count: 0
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
upvote count: 1
type: Question
type: AnsweredQuestion
has body: I am working on converting an XML file into a CSV or pandas file. There are various categories that are necessary and others which are unwanted in the XML. Is there an efficient method to pick out the information in the code as formatted below. This needs to be done on a relatively large scale >10,000 documents. For example, I want to get the "family-id", "data", and <?xml version="1.0" encoding="UTF-8"?> <patent-document ucid="US-20030137706-A1" country="US" doc- number="20030137706" kind="A1" lang="EN" family-id="10973265" status="new" date-produced="20090605" date="20030724"> <bibliographic-data> US 20030137706 A1 20030724 US 18203002 A 20021204 <priority-claims status="new"> HU 0000532 A 20000207 </abstract> <description load-source="us" status="new" lang="EN"> TECHNICAL FIELD [0001] The object of the invention is a method for the holographic recording of data. In the method a hologram containing the date is recorded in a waveguide layer as an interference between an object beam and a reference beam. The object beam is essentially perpendicular to the plane of the hologram, while the reference beam is coupled in the waveguide. There is also proposed an apparatus for performing the method. The apparatus comprises a data storage medium with a waveguide holographic storage layer, and an optical system for writing and reading the holograms. The optical system comprises means for producing an object beam and a reference beam, and imaging the object beam and a reference beam on the storage medium. BACKGROUND ART [0002] Storage systems realised with tapes stand out from other data storage systems regarding their immense storage capacity. Such systems were used to realise the storage of data in the order of Terabytes. This large storage capacity is achieved partly by the storage density, and partly by the length of the storage tapes. The relative space requirements of tapes are small, because they may be wound up into a very small volume. Their disadvantage is the relat…
score: 1
has answer: http://stackoverflow.com/a/51028512
tagged with: export-to-csv
tagged with: xml-parsing
has title: How to parse a complicated XML with Python
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51028512
tagged with: python
has comment: http://stackoverflow.com/comment/89049235

http://stackoverflow.com/q/51080943
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/89150582
has comment: http://stackoverflow.com/comment/89150488
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51081584
has comment: http://stackoverflow.com/comment/89155170
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89150930
has body: I'm storing a Pandas DataFrame in a .csv file which has a column with integer data, but the database system treats as a float for legacy reasons, so the .csv needs to store it as a float too. When storing it with df.to_csv, it preserves the zero-padded decimal part, so the column in the .csv file is like: IntNumber 3.0 45.0 123.0 ... But when I load this with pandas.from_csv, it infers the type as int64 despite the trailing zero. I've looked through the pandas.read_csv docs and it looks like I can specify the datatype manually to be float64, but I think there are multiple instances of this needing to be detected as float instead of int64. It would be useful to have it automatically infer the type to be float when the trailing zero is present, is this possible? Snippet of how I'm loading the csv, at this point it's inferred the type of the column in dataframe to be int64 dataframe = pandas.read_csv("&lt;csv_name&gt;", index_col=0, parse_dates=True)
tagged with: dataframe
has answer: http://stackoverflow.com/a/51081340
type: Question
has title: pandas.read_csv converts decimal zero-padded float columns to int

http://stackoverflow.com/q/51089207
has comment: http://stackoverflow.com/comment/89252609
upvote count: 0
tagged with: scikit-learn
downvote count: 4
has body: I have the following scenario: My input is a set of points. Each point (Long_Lat coordinates) corresponds to the centroid of a subsection of a region, and has a demand for school. Like 50 children that need a school on the neighborhood. After using a cluster method (like k-means or DBscan) to aggregate these Points by proximity, I want to allocate demand points to schools, in such a way that the cluster demands (the sum of all points demands on that cluster) are satisfied. In other words, I want to create schools on that cluster and allocate the children (points) to these schools. Schools have a fixed capacity restriction. I.e.: I need 3 schools (capacity of 40), to suply the 100 children demand (P1, P2, P3) of cluster C4. Main objective is, of course, to know the location of these schools. But I can retrieve it using logic. What method should I use to fill the capacity of a cluster? Is this the correct approach?
answer count: 1
has comment: http://stackoverflow.com/comment/89172562
favorite count: 0
has comment: http://stackoverflow.com/comment/89186812
has title: Machine Learning Method to Classify using Demand
score: -4
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51141944
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51141944
tagged with: geojson
type: Question
has comment: http://stackoverflow.com/comment/89200677

http://stackoverflow.com/comment/89248112
type: Comment
comment on: http://stackoverflow.com/a/51129675
has text: Hi, I also try your script, but it shows error as below. I do not the reason why make this happen. Please help me to figure out. Thank you very much! **SyntaxError: invalid syntax**
score: 0
type: AnswerComment

http://stackoverflow.com/q/51161854
downvote count: 0
has body: I want to save a dictionary object as json, but I am not able to read the file with notepad++. All the Hebrew charcthers converted to \u.... This is how I save it: with open("users.json", "w", encoding='utf8') as write_file: json.dump(mydict, write_file) In pycharm I do see the Hebrew properly.
has title: Python save to text file with utf-8 Hebrew shows as unicode \u05d9\u05dc\
tagged with: hebrew
tagged with: string
tagged with: unicode
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/89307395
type: Question
has comment: http://stackoverflow.com/comment/89342081
has comment: http://stackoverflow.com/comment/89307645

http://stackoverflow.com/q/51013113
has body: I am trying to develop a small app which will basically plot some graphs based on set of data user provided or requested. The process_order function should be run concurrent different set of data. For some reason I get only the first graph not the second and successive one. I have opened a different browser session with different user got the same result. Example I tried to open a browser one from IE and another one from Chrome with logged in as user1 with set of 5 inputs - in IE (Expected 5 graphs) and as user2 with set of 20 input - in Chrome (Expected 20 Graphs) I was expecting 2 browser window with 5 graphs from one and 20 graphs from second window: I am new to python and flask apologies if its something have already asked/answered in different questions app = Flask(__name__) plot = None my_session = None session_id = None @app.route('/') def home(): if not session.get('logged_in'): return render_template('login.html') else: return render_template('template.html') @app.route('/login', methods=['POST']) def do_admin_login(): if request.form['password'] == 'password' and request.form['username'] in 'admin' : session['logged_in'] = True my_session = Bot(request.form['username']) my_session.session_id = request.form['username'] session['user'] = request.form['username'] return render_template('template.html') else: flash('wrong password!') return home() @app.route("/ask", methods=['POST','GET']) def ask(): string = str(request.form['message']) res = my_session.process(string) return jsonify({'status':'OK','answer':bot_res}) class Bot(): #Define user level def __init__(self,session_id): self.return_string = "" self.session_id = session_id def process(self, string): self.session_id = session['user'] self.string = string self.return_string = self.process_order() # This method I would like to execute as concurrent at the same time for multiple users/session with different set ot data return self.return_string def process_order(self): self.plot = Plot() self.plot.global_…
tagged with: flask
upvote count: 3
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/51013881
tagged with: multiprocessing
type: Question
score: 3
has title: Flask Multiprocessing

http://stackoverflow.com/q/51045054
upvote count: 5
tagged with: allocation
tagged with: memory
has comment: http://stackoverflow.com/comment/89081957
type: Question
has answer: http://stackoverflow.com/a/51126702
score: 5
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/15443246
tagged with: fork
has body: I encountered a memory allocation problem when forking processes in Python. I know the issue was already discussed in some other posts here, however I couldn't find a good solution in any of them. Here is a sample script illustrating the Problem: import os import psutil import subprocess pid = os.getpid() this_proc = psutil.Process(pid) MAX_MEM = int(psutil.virtual_memory().free*1E-9) # in GB def consume_memory(size): """ Size in GB """ memory_consumer = [] while get_mem_usage() &lt; size: memory_consumer.append(" "*1000000) # Adding ~1MB return(memory_consumer) def get_mem_usage(): return(this_proc.memory_info()[0]/2.**30) def get_free_mem(): return(psutil.virtual_memory().free/2.**30) if __name__ == "__main__": for i in range(1, MAX_MEM): consumer = consume_memory(i) mem_usage = get_mem_usage() print("\n## Memory usage %d/%d GB (%2d%%) ##" % (int(mem_usage), MAX_MEM, int(mem_usage*100/MAX_MEM))) try: subprocess.call(['echo', '[OK] Fork worked.']) except OSError as e: print("[ERROR] Fork failed. Got OSError.") print(e) del consumer The script was tested with Python 2.7 and 3.6 on Arch Linux and uses psutils to keep track of memory usage. It gradually increases memory usage of the Python process and tries to fork a process using subprocess.call(). Forking fails if more then 50% of the avail. memory is consumed by the parent process. ## Memory usage 1/19 GB ( 5%) ## [OK] Fork worked. ## Memory usage 2/19 GB (10%) ## [OK] Fork worked. ## Memory usage 3/19 GB (15%) ## [OK] Fork worked. [...] ## Memory usage 9/19 GB (47%) ## [OK] Fork worked. ## Memory usage 10/19 GB (52%) ## [ERROR] Fork failed. Got OSError. [Errno 12] Cannot allocate memory ## Memory usage 11/19 GB (57%) ## [ERROR] Fork failed. Got OSError. [Errno 12] Cannot allocate memory ## Memory usage 12/19 GB (63%) ## [ERROR] Fork failed. Got OSError. [Errno 12] Cannot allocate memory ## Memory usage 13/19 GB (68%) ## [ERROR] Fork failed. Got OSError. [Errno 12] Cannot allocate memory [...] Note that I had no Sw…
tagged with: python
favorite count: 0
has title: Python fork: 'Cannot allocate memory' if process consumes more than 50% avail. memory
has comment: http://stackoverflow.com/comment/126191839
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89081546
tagged with: popen

http://stackoverflow.com/comment/89124385
type: QuestionComment
comment on: http://stackoverflow.com/q/51066880
score: 0
has text: @Andersson but len_email = len(driver.find_elements_by_name('email')) returns 5
type: Comment

http://stackoverflow.com/comment/89252243
type: AnswerComment
has text: Oh but why do we need to `strfttime` twice, isnt it enough already in utc_date that you can directly make the changes from there?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51133362

http://stackoverflow.com/comment/89061553
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51034622
has text: This is not a good method of indexing. Use loc or iloc only. Don't mix indexers like this.

http://stackoverflow.com/q/51035439
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51035455
accepted answer: http://stackoverflow.com/a/51035455
tagged with: python
type: AnsweredQuestion
type: Question
has body: I was trying to map two data frame based on the Date. however, I had an error as follow: "InvalidIndexError: Reindexing only valid with uniquely valued Index objects" I am using the following df1 and create a new column "Fix Week" kickoffDate kickoffTime hometeam_team1 2016-08-13 11:30:00 Hull City 2016-08-13 14:00:00 Middlesbrough 2016-08-13 14:00:00 Middlesbrough 2016-08-13 14:00:00 Middlesbrough 2016-08-13 14:00:00 Middlesbrough The df2 that I am going to map is as follow: Round Date Home Team Away Team 1 2016-08-13 Hull Leicester 1 2016-08-13 Burnley Swansea 1 2016-08-13 Crystal Palace West Brom 1 2016-08-13 Everton Spurs To get a new column, I am using the following code: df1['fix'] = df1.kickoffDate.map(df2.set_index('Date').Round).astype(float) but it gave me error as I mentioned above. Would anyone advise me? Thanks Zep
score: 0
has title: Mapping using date to create a new column in data frame
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/51105517
has comment: http://stackoverflow.com/comment/89198705
has comment: http://stackoverflow.com/comment/89204682
tagged with: subprocess
has body: I have a routine that frequently executes a shell command and parses the output from it. For this I am using the subprocess.Popen to execute the shell command. Tested with the shell commands ls , systemctl status xxxx.service etc. Platform - Linux 3.14.4-yocto-standard x86_64 status_call = subprocess.Popen(shlex.split(&lt;shell_command&gt;), stdout=subprocess.PIPE, stderr=subprocess.PIPE) I used the communicate() to read the output and error from the above child process. I am considering error scenario if the length of output is 0 or length of error is not zero and I am printing the error and the return code. import subprocess import shlex def loop_process(): count = 0 iter = 0 print 'Test Case: Starting the script' while True: status_call = subprocess.Popen(shlex.split('ls'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = status_call.communicate() if len(error) != 0 or len(output) == 0: print 'Test Case : Unable to make the systemctl status call\n' print 'error is : ' + str(error) + 'with length of output as ' + str(len(output)) print 'return_code is ' + str(status_call.returncode) count = 0 iter = 0 else: count = count + 1 if count &gt; 1000: iter = iter + 1 print iter count = 0 if __name__ == '__main__': loop_process() The above logic is failing at random times and I am not getting any error message or the return code from the child process is zero as shown below I am seeing the issue in here roughly for every 200,000 times. I am running it on embedded equipment. I am not seeing this issue when I run on QEMU 114 115 Unable to make the systemctl status call error is : with length of output as 0 return_code is 0 1 2 Other occurrence 387 388 389 Test Case : Unable to make the systemctl status call error is : with length of output as 0 return_code is 0 1 2 Can anyone guide me how to resolve such issues? What is the direction I need to concentrate on finding the root cause and possibly a fix? I am strongly suspecting some problem with the PIPE.
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89200261
has comment: http://stackoverflow.com/comment/89199013
tagged with: popen
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89203551
has comment: http://stackoverflow.com/comment/89203003
linked to: http://stackoverflow.com/q/18421757
has comment: http://stackoverflow.com/comment/89200525
has comment: http://stackoverflow.com/comment/89198309
answer count: 0
has title: subprocess.Popen communicate fails randomly with zero returncode and no error
has comment: http://stackoverflow.com/comment/89198493
favorite count: 0
has comment: http://stackoverflow.com/comment/89200663
type: Question
has comment: http://stackoverflow.com/comment/89199219
tagged with: python

http://stackoverflow.com/comment/89075836
type: Comment
comment on: http://stackoverflow.com/q/51041225
score: 0
has text: Yeah, I have just used the code with the controller and it works fine now.
type: QuestionComment

http://stackoverflow.com/q/51063462
linked to: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/89117639
answer count: 1
downvote count: 0
has title: Python dictionary display nothing
has comment: http://stackoverflow.com/comment/89117258
has comment: http://stackoverflow.com/comment/89117337
favorite count: 0
has comment: http://stackoverflow.com/comment/89117533
tagged with: python
has comment: http://stackoverflow.com/comment/89118317
tagged with: tkinter-entry
has comment: http://stackoverflow.com/comment/89117792
has comment: http://stackoverflow.com/comment/89117577
has comment: http://stackoverflow.com/comment/89117999
tagged with: tkinter
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89118431
has comment: http://stackoverflow.com/comment/89116830
upvote count: 1
has comment: http://stackoverflow.com/comment/89117330
has comment: http://stackoverflow.com/comment/89118607
has comment: http://stackoverflow.com/comment/89117769
type: Question
has body: I am loading python dictionary with multiple polygons. Polygon points are obtained from mouse click on different position of image. The script displays image to user for selection of different points of polygons. The user will click on different position by mouse right click. When the user clicks left mouse button, a polygon is created and added to dictionary Dict_Polygons with a label. The list list_of_points is cleared as new points for new polygon will be added to this list. The issue is that Dict_Polygon is not loaded with items. Here is the complete code. import math import pickle from Tkinter import * import Image, ImageTk, ImageDraw import numpy as np coord=[] # for saving coord of each click position Dict_Polygon={} # Dictionary for saving polygon list_of_points=[] flag=True label=0 def draw_lines(event): mouse_xy = (event.x, event.y) func_Draw_lines(mouse_xy) def func_Draw_lines(mouse_xy): func_Draw_Dot(mouse_xy) center_x, center_y = mouse_xy if canvas.old_coords: x1, y1 = canvas.old_coords canvas.create_line(center_x, center_y, x1, y1) # add clicked positions to list if flag==True: list_of_points.append(mouse_xy) canvas.old_coords = center_x, center_y def func_Draw_Dot(coord): x_coord, y_coord=coord #draw dot over position which is clicked x1, y1 = (x_coord - 1), (y_coord - 1) x2, y2 = (x_coord + 1), (y_coord + 1) canvas.create_oval(x1, y1, x2, y2, fill='green', outline='green', width=5) # This function will be called when the user wants to specify class, so a polygon will be drawn. def func_draw_polygon(event): numberofPoint=len(list_of_points) if numberofPoint&gt;2: print ("test") canvas.create_polygon(list_of_points, fill='', outline='green', width=2) Dict_Polygon[label]=list_of_points list_of_points[:]=[] # del list_of_points[:] # clear list elements to add new polygon points canvas.old_coords=None global label label=label+1 print (Dict_Polygon.items()) else: print('Select minemum 3 points') # Main function if __name__ == '__main__': root = Tk() # Inpu…
has comment: http://stackoverflow.com/comment/89117114
has comment: http://stackoverflow.com/comment/89117920
has answer: http://stackoverflow.com/a/51064428
tagged with: canvas

http://stackoverflow.com/a/51209193
type: AcceptedAnswer
score: 0
type: Answer
has body: I was able to successfully save images to my local drive after making some changes. Although, the warning message still shows up (I think that's some issue with my setup). Please find the solution below. import tensorflow as tf filepath = "&lt;Some filepath&gt;" filename = "&lt;Some image filename&gt;" tensors = [] # decode image to RGB format image_decoded = tf.image.decode_jpeg(tf.read_file(filepath + filename), channels=3) # crop a random patch from the image of size 512*512 random_patch = tf.random_crop(image_decoded, [512,512,3]) # append the tensor to the list of rest of the tensors tensors.append(random_patch) # encode the random patch into JPEG format and then write the file to the local drive enc = tf.image.encode_jpeg(random_patch) # write the new cropped file at the directory random_patches created image = filepath + "random_patches/" + filename cropped_file = tf.constant(image) fwrite = tf.write_file(cropped_file, enc) sess = tf.Session() result = sess.run(fwrite)
accepted answer of: http://stackoverflow.com/q/51127595
answers question: http://stackoverflow.com/q/51127595

http://stackoverflow.com/comment/89277396
type: Comment
comment on: http://stackoverflow.com/a/51146553
type: AnswerComment
has text: data-id will be different everytime, so cant hardcode it in the code
score: 0

http://stackoverflow.com/comment/89021610
type: AnswerComment
has text: And while and try statements can have an else clause too by the way.
type: Comment
comment on: http://stackoverflow.com/a/51014418
score: 2

http://stackoverflow.com/a/75830761
has body: if you are taking any error like "WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 1" in notebook page Ctrl + Shift + P , choose "Use fallback runtime version" after try again.
type: Answer
answers question: http://stackoverflow.com/q/51046454
score: 0

http://stackoverflow.com/comment/89117436
type: Comment
has text: I would use `NamedTemporaryFile`. Looking at your use case you actually don't need *secure* temporary file. So there's no point in using `tempfile.mkstemp`
comment on: http://stackoverflow.com/a/51063621
type: AnswerComment
score: 0

http://stackoverflow.com/q/51085083
tagged with: sftp
has comment: http://stackoverflow.com/comment/89166526
linked to: http://stackoverflow.com/q/49381899
answer count: 1
has comment: http://stackoverflow.com/comment/89166441
favorite count: 0
has answer: http://stackoverflow.com/a/51095117
linked to: http://stackoverflow.com/q/10670217
tagged with: ssh
tagged with: python
has title: Downloading files from SFTP server listed by remote command with Paramiko in Python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/51095117
type: Question
has comment: http://stackoverflow.com/comment/89166364
has comment: http://stackoverflow.com/comment/89166452
has body: I am using Paramiko to connect to the SFTP server from my local machine and download txt files from remote path. I am able to make successful connection and can also print the remote path and the files but i cannot get the files locally. I can print the file_path and file_name but not able to download all the files. Below is the code I am using: import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=hostname, username=username, password=password, port=port) remotepath = '/home/blahblah' pattern = '"*.txt"' stdin,stdout,stderr = ssh.exec_command("find {remotepath} -name {pattern}".format(remotepath=remotepath, pattern=pattern)) ftp = ssh.open_sftp() for file_path in stdout.readlines(): file_name = file_path.split('/')[-1] print(file_path) print(file_name) ftp.get(file_path, "/home/mylocalpath/{file_name}".format(file_name=file_name)) I can see the file_path and file_name like below from print statement but get error while using ftp.get for multiple files. I can copy a single file by hardcoding the name on source and destination. file_path = '/home/blahblah/abc.txt' file_name = 'abc.txt' file_path = '/home/blahblah/def.txt' file_name = 'def.txt' I see one file is downloaded and then i get the following error: FileNotFoundErrorTraceback (most recent call last) Error trace: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "...anaconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 769, in get with open(localpath, 'wb') as fl: FileNotFoundError: [Errno 2] No such file or directory: 'localpath/abc.txt\n'
has comment: http://stackoverflow.com/comment/89166395
has comment: http://stackoverflow.com/comment/89178233
tagged with: paramiko
score: 0

http://stackoverflow.com/q/51117445
has answer: http://stackoverflow.com/a/56447496
has title: How do you find the first N prime numbers in python?
favorite count: 0
has comment: http://stackoverflow.com/comment/89221087
upvote count: 2
has comment: http://stackoverflow.com/comment/89221099
tagged with: python
accepted answer: http://stackoverflow.com/a/51117465
has answer: http://stackoverflow.com/a/53164920
tagged with: primes
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53712178
score: 1
has answer: http://stackoverflow.com/a/51117784
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/59512412
possible better answer: http://stackoverflow.com/a/51117784
has comment: http://stackoverflow.com/comment/89221140
answer count: 6
has body: I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers. The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this? max=int(input("How many prime numbers do you want: ")) min=2 while(min&lt;=(max)): for c in range(2, min): if min%c==0: break else: print min min=min+1
has answer: http://stackoverflow.com/a/51117465

http://stackoverflow.com/a/51120667
type: Answer
score: 3
downvote count: 0
has body: Two things you can do right off the bat: Don’t make a copy of the set every time through the list. That’s a big waste of time/memory. Instead, modify the set once after each iteration. Keep a separate set of people in each round. Looking up a person in a set will be an order of magnitude faster than looping through the entire round. Ex: def make_rounds(people): people_pairs = set(combinations(people, 2)) while people_pairs: round = set() people_covered = set() for pair in people_pairs: if pair[0] not in people_covered \ and pair[1] not in people_covered: round.add(pair) people_covered.update(pair) people_pairs -= round # remove thi yield round Comparison:
answers question: http://stackoverflow.com/q/51120404
upvote count: 3

http://stackoverflow.com/comment/89281314
has text: we are not here to do your homework. What have you tried so far ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51148685
score: 5

http://stackoverflow.com/q/51037737
has title: ValueError: x and y must have same first dimension, but have shapes (4200,) and (16800, 1)
tagged with: python
score: 2
has body: Ihave created an SVR model using SCIKIT-LEARN, I am trying to plot my data but for some reason I am receiving the error: ValueError: x and y must have same first dimension, but have shapes (4200,) and (16800, 1) I have split my data into training and testing data, training the model and making a prediction. My code is: X_feature = wind_speed X_feature = X_feature.reshape(-1, 1)## Reshaping array to be 1D from 2D y_label = Power y_label = y_label.reshape(-1,1) timeseries_split = TimeSeriesSplit(n_splits=3) ## Splitting training testing data into 3 splits for train_index, test_index in timeseries_split.split(X_feature):## for loop to obtain print the training and splitting of the data print("Training data:",train_index, "Testing data test:", test_index)# X_train, X_test = X_feature[train_index], X_feature[test_index] y_train, y_test = y_label[train_index], y_label [test_index] timeseries_split = TimeSeriesSplit(n_splits=3) ## Splitting training testing data into 3 splits scaler =pre.MinMaxScaler(feature_range=(0,1)).fit(X_train)## Data is being preprocessed then standard deviation scaled_wind_speed_train = scaler.transform(X_train)## Wind speed training data is being scaled and then transformed scaled_wind_speed_test = scaler.transform(X_test)## Wind speed test data is being scaled and then transformed SVR_model = svm.SVR(kernel='rbf',C=100,gamma=.001).fit(scaled_wind_speed_train,y_train) y_prediction = SVR_model.predict(scaled_wind_speed_test) SVR_model.score(scaled_wind_speed_test,y_test) rmse=numpy.sqrt(mean_squared_error(y_label,y_prediction)) print("RMSE:",rmse) fig, bx = plt.subplots(figsize=(19,8)) bx.plot(y_prediction, X_feature,'bs') fig.suptitle('Wind Power Prediction v Wind Speed', fontsize=20) plt.xlabel('Wind Power Data') plt.ylabel('Predicted Power') plt.xticks(rotation=30) plt.show() fig, bx = plt.subplots(figsize=(19,8)) bx.plot( y_prediction, y_label) fig.suptitle('Wind Power Prediction v Measured Wind Power ', fontsize=20) plt.xlabel('Wind Power Data…
upvote count: 2
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51037950
tagged with: svm
has answer: http://stackoverflow.com/a/51038012
answer count: 2
downvote count: 0
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/a/51794399
has comment: http://stackoverflow.com/comment/110323368
has comment: http://stackoverflow.com/comment/96534207
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/51034252
upvote count: 6
answers question: http://stackoverflow.com/q/51034252
has body: With the help of someone at anticaptcha.com, I solved this issue. api_key = '....' site_key = '6LeQLyEUAAAAAKTwLC-xVC0wGDFIqPg1q3Ofam5M' # grab from site client = AnticaptchaClient(api_key) task = NoCaptchaTaskProxylessTask(url, site_key) job = client.createTask(task) print("Waiting to solution by Anticaptcha workers") job.join() # Receive response response = job.get_solution_response() print("Received solution", response) # Inject response in webpage driver.execute_script('document.getElementById("g-recaptcha-response").innerHTML = "%s"' % response) # Wait a moment to execute the script (just in case). time.sleep(1) # Press submit button driver.find_element_by_xpath('//button[@type="submit" and @class="btn-std"]').click()
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/96519244

http://stackoverflow.com/comment/89105223
type: Comment
comment on: http://stackoverflow.com/q/51057351
type: QuestionComment
has text: I tried editing my groupby(["Model","Mode"]) but it doesnt work. Can someone help me with this too?
score: 0

http://stackoverflow.com/a/51226576
score: 0
answers question: http://stackoverflow.com/q/51116774
has body: Here is your original list: lis = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0] and you'd like to replace the first 4 items with: [4, 2, 2, 4] Let's assign the new values a new variable. Let's call it update. So: update = [4, 2, 2, 4] Here is your code: lis = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0] update = [4, 2, 2, 4] for i in range(0, len(update)): lis[i] = update[i] print(lis)
type: Answer

http://stackoverflow.com/comment/89259439
comment on: http://stackoverflow.com/q/51137395
has text: It depends on the used columns. If I cahnge usecols to 'speed' only it works fine.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89063862
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51035791
has text: `TypeError: not all arguments converted during string formatting` don't understand why it's not converting all elements :/
type: AnswerComment

http://stackoverflow.com/a/51146718
upvote count: 1
answers question: http://stackoverflow.com/q/51146572
has comment: http://stackoverflow.com/comment/89277646
has comment: http://stackoverflow.com/comment/89277933
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89277766
downvote count: 0
has body: .sum() applied to DF of strings Without Altering the original Q&amp;A... Here is an updated answer for your revised question: The issue is that you'll need to convert the strings to integers. That just makes it a two step process. I'll show all the steps so it's clear: In [83]: str_lst =[[ '7', '3', '2', '-1', '5', '8', '0'], [ '6', '8', '4', '0', '8', '7', '6'], [ '6', '1', '2', '8', '6', '-1', '2'], [ '0', '-1', '3', '5', '1', '3', '7'], [ '6', '5', '2', '8', '4', '2', '3'], [ '4', '-1', '-1', '3', '2', '3', '-1'], [ '8', '6', '6', '0', '8', '0', '0'], ['-1', '3', '3', '0', '4', '2', '4'], [ '2', '1', '2', '7', '0', '8', '5'], [ '3', '8', '1', '0', '8', '1', '8']] In [85]: df = pd.DataFrame(str_lst, columns=['1day', '2day', '3day', '4day', '5day', '6day', '7day']) In [93]: df = df.apply(pd.to_numeric) In [94]: df['Totals'] = df.sum(axis =1) If you do the total before the pd.to_numeric it is the summation of strings. If you do the total after teh pd.to_numeric it is the summation of integers. Original Response After you've created your DF. Try: df['Totals'] = df.sum(axis=1) This will add a column at the far right with a sum of the rows. Example In [63]: df = pd.DataFrame(np.random.randint(-1,9,size=(10, 7)), columns=['1day', '2day', '3day', '4day', '5day', '6day', '7day']) In [64]: df Out[64]: 1day 2day 3day 4day 5day 6day 7day 0 0 0 7 -1 2 2 -1 1 0 3 3 2 -1 3 6 2 0 8 0 -1 8 -1 1 3 3 8 -1 2 6 3 8 4 5 0 1 8 8 -1 3 5 7 8 1 4 8 1 8 6 5 7 5 -1 7 -1 1 7 6 3 2 2 8 1 5 8 3 7 3 3 3 -1 1 9 2 -1 8 1 1 0 5 In [65]: df['Totals'] = df.sum(axis=1) In [66]: df Out[66]: 1day 2day 3day 4day 5day 6day 7day Totals 0 0 0 7 -1 2 2 -1 9 1 0 3 3 2 -1 3 6 16 2 0 8 0 -1 8 -1 1 15 3 3 8 -1 2 6 3 8 29 4 5 0 1 8 8 -1 3 24 5 7 8 1 4 8 1 8 37 6 5 7 5 -1 7 -1 1 23 7 6 3 2 2 8 1 5 27 8 3 7 3 3 3 -1 1 19 9 2 -1 8 1 1 0 5 16
has comment: http://stackoverflow.com/comment/89279001
type: Answer
has comment: http://stackoverflow.com/comment/89277593
accepted answer of: http://stackoverflow.com/q/51146572
score: 1
has comment: http://stackoverflow.com/comment/89298222

http://stackoverflow.com/comment/89161943
comment on: http://stackoverflow.com/q/51081337
type: Comment
type: QuestionComment
has text: And if you're passing it per user, then you can just grab the id since you already have it.
score: 0

http://stackoverflow.com/comment/110820312
comment on: http://stackoverflow.com/q/51050948
score: 0
type: Comment
type: QuestionComment
has text: Thanks a lot guys, you save my day!, however I was working fine with this configuration since five months, I update my Windows some days ago and then, this error happened. For resolve, I installed MySQLdb in lib folder (GCP recommndations), because I was using integrated libs offer to GCP and misteriously not working anymore for me. Finally I configured my PYTHONPATH and worked like a charm locally. As tip: In your .gitignore add lines in order to ignore the mysql folders installation :-)

http://stackoverflow.com/comment/89096261
has text: what that does is makes one side bigger but doesn't move the sprite as a whole.
comment on: http://stackoverflow.com/a/51052575
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89138377
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51074511
score: 0
has text: have you ever tried using `break` ?

http://stackoverflow.com/comment/129407239
comment on: http://stackoverflow.com/a/71789875
score: 0
type: AnswerComment
has text: arrays_zip does not take list as input
type: Comment

http://stackoverflow.com/q/51103389
upvote count: 1
has comment: http://stackoverflow.com/comment/89194308
has comment: http://stackoverflow.com/comment/89194099
type: Question
has body: suppose I have a list: INPUT=[{'id': 1, 'context': 'this is q1', 'content': 'this is ch1'}, {'id': 1, 'context': 'this is q1', 'content': 'this is ch2'}, {'id': 1, 'context': 'this is q1', 'content': 'this is ch3'}, {'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}] Convert: OUTPUT=[{'id': 1, 'context': 'this is q1', 'content': ['this is ch1','this is ch2','this is ch3']}, {'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}] What is the easiest way on python to perform the above conversion?
has comment: http://stackoverflow.com/comment/89194526
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/51103644
has title: Summarize information in the list
has answer: http://stackoverflow.com/a/51103554
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/89194127
tagged with: dictionary
tagged with: list
has comment: http://stackoverflow.com/comment/89194212
has answer: http://stackoverflow.com/a/51103652

http://stackoverflow.com/a/51077745
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89149219
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51077547
answers question: http://stackoverflow.com/q/51077547
upvote count: 2
type: AcceptedAnswer
has body: Cronjobs should be more efficient. There are always being check out by the system, if you use sleep you would be still checking for cronjobs (even if there's no job to run) so sleep is innecesary.

http://stackoverflow.com/a/51143804
type: Answer
answers question: http://stackoverflow.com/q/51143508
score: 0
has body: To find the unique set of types from the dataframe so far, you could take a slice of the dataframe from the start to each row and then force it into a Set and take the length. If you already have your dataframe set up with the proper columns (all 0's) you can insert the length of the this set into the right place: for index, row in df.iterrows(): l = len(set(df['type'].head(index))) t = row['type'] df['num_'.format(t)][index] = t Let me know if this helps, I can add more if you need.

http://stackoverflow.com/q/51072816
type: Question
has title: How to sort a json file with spark in python?
score: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/89136838
tagged with: python
has body: I have a json file as following and I would like to sort it using rdd. How would I do it? I tried the following but it does not sort the words :( rdd = self.sc.textFile(self.dic_path).sortByKey() { "biennials": 0, "tripolitan": 0, "oblocutor": 0, "leucosyenite": 0, "chilitis": 0, "fabianist": 0, "diazeutic": 0, "alible": 0, "woods": 4601, "preadjournment": 0, "spiders": 0, "fabianism": 0, }
linked to: http://stackoverflow.com/q/37872461
has comment: http://stackoverflow.com/comment/89137012
answer count: 0
type: UnansweredQuestion
tagged with: apache-spark-sql
tagged with: pyspark

http://stackoverflow.com/comment/89205827
comment on: http://stackoverflow.com/q/51108880
score: 0
type: Comment
type: QuestionComment
has text: The whole point of process substitution is so you can avoid creating all those temporary files.

http://stackoverflow.com/comment/89152057
score: 0
type: QuestionComment
has text: Is [this document](https://docs.ansible.com/ansible/latest/user_guide/become.html) insufficient?
type: Comment
comment on: http://stackoverflow.com/q/51081678

http://stackoverflow.com/comment/89205927
type: QuestionComment
has text: /usr/bin/xyz.py <----- the python file. whenever i open this with vi. It shows unreadable character. I thot it is binary.
comment on: http://stackoverflow.com/q/51109420
score: 0
type: Comment

http://stackoverflow.com/comment/89450969
type: Comment
comment on: http://stackoverflow.com/a/51075912
has text: (I've been away for a few days for the holiday). As noted above, I able to connect to the Event Hub, but when I do I see only summary information about the events and not the detailed telemetry events that I expect to see. We need all the monitoring information that is here: learn.microsoft.com/en-us/azure/iot-hub/…, e.g. device identity, device to cloud communications, cloud to device communications, file uploads and message routing. Is Event Hub the correct way to get that?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51252362
has body: You can follow the discussion here The gist of it is that not all operators support higher order gradients at the moment. In Gluon you can try the following: with mx.autograd.record(): output = net(x) loss = loss_func(output) dz = mx.autograd.grad(loss, [z], create_graph=True) # where [z] is the parameter(s) you want dz[0].backward() # now the actual parameters should have second order gradients Taken from this forum thread
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51126186
upvote count: 1

http://stackoverflow.com/comment/89081406
type: QuestionComment
comment on: http://stackoverflow.com/q/51039409
has text: I added the whole code. I will be very grateful for your help
score: 0
type: Comment

http://stackoverflow.com/q/51104911
tagged with: python
score: 1
favorite count: 0
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51104973
tagged with: selection
has title: Select hourly data based on days
accepted answer: http://stackoverflow.com/a/51104973
tagged with: time-series
downvote count: 0
has body: I have a time series hourly_df, containing some hourly data: import pandas as pd import numpy as np hourly_index = pd.date_range(start='2018-01-01', end='2018-01-07', freq='H') hourly_data = np.random.rand(hourly_index.shape[0]) hourly_df = pd.DataFrame(hourly_data, index=hourly_index) and I have a DatetimeIndex, containing some dates (as days as I wish), e.g. daily_index = pd.to_datetime(['2018-01-01', '2018-01-05', '2018-01-06']) I want to select each row of hourly_df, which date of its index is in daily_index, so in my case all hourly data from 1st, 5th and 6th January. What is the best way to do this? If I naively use hourly_df.loc[daily_index], I only get the rows at 0:00:00 for each of the three days. What I want is the hourly data for the whole day for each of the days in daily_index. One possibility to solve this, is to create a filter that takes the date of each element in the index of hourly_df and compares whether of not this date is in daily_index. day_filter = [hour.date() in daily_index.date for hour in hourly_df.index] hourly_df[day_filter] This produces the desired output, but it seems the usage of the filter is avoidable and can be done in an expression similar to hourly_df.loc[daily_index.date].
tagged with: filter
tagged with: pandas
type: AnsweredQuestion

pythonnet
type: Tag
tag name: pythonnet
tags question: http://stackoverflow.com/q/51061494
tags question: http://stackoverflow.com/q/51064311

http://stackoverflow.com/q/51094388
tagged with: python
favorite count: 0
tagged with: package
upvote count: 1
has comment: http://stackoverflow.com/comment/89177403
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51094990
has body: A couple of months ago, I happened to use BeautifulSoup in some Python project and I noticed the library was organized in a somewhat unique manner. In order to use the BeautifulSoup class you only have to import the top-level package, like this: from bs4 import BeautifulSoup soup = BeautifulSoup(html) I knew that it was because the BeautifulSoup class, which is basically the only class provided by the library, is directly placed in __init__.py within the bs4 directory with the clear intent to make importing the library simple. I wondered if such practice is considered appropriate when I build my own library. Obviously placing classes at the package scope by writing the class body in __init__.py will inflate the file indefinitely, but I do not either like the usual Python way in which there is usually only one class (or whatever unit of code) per module. In short, I do not like to write redundant import statements like this, which seems inevitable when placing one class per module: from mylibrary.splendidparser import splendidparser from mylibrary.supremetimer import supremetimer from mylibrary.superbrenderer import superbrenderer And instead, I prefer the BeautifulSoup way: from mylibrary import splendidparser from mylibrary import supremetimer from mylibrary import superbrenderer Is there any way I can package my library to enable this importing style without inflating __init__.py?
has comment: http://stackoverflow.com/comment/89176705
type: Question
has comment: http://stackoverflow.com/comment/89176769
has comment: http://stackoverflow.com/comment/89176912
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51094990
has title: How can I place all symbols exported from a Python package at the package scope?

http://stackoverflow.com/comment/89223807
type: Comment
comment on: http://stackoverflow.com/a/51118405
score: 0
type: AnswerComment
has text: Works well, just needed to change to "find_element_by_xpath", rather than "find_elements_by_xpath". (The latter returns a list.) Thanks.

lstm
tags question: http://stackoverflow.com/q/51123517
tags question: http://stackoverflow.com/q/51132802
tags question: http://stackoverflow.com/q/51074105
tags question: http://stackoverflow.com/q/51057713
tags question: http://stackoverflow.com/q/51136435
tags question: http://stackoverflow.com/q/51056161
tags question: http://stackoverflow.com/q/51104648
tags question: http://stackoverflow.com/q/51015928
tags question: http://stackoverflow.com/q/51073614
tags question: http://stackoverflow.com/q/51064016
tags question: http://stackoverflow.com/q/51015259
tags question: http://stackoverflow.com/q/51139888
tags question: http://stackoverflow.com/q/51141408
tags question: http://stackoverflow.com/q/51151945
tag name: lstm
tags question: http://stackoverflow.com/q/51025335
tags question: http://stackoverflow.com/q/51029779
tags question: http://stackoverflow.com/q/51014044
tags question: http://stackoverflow.com/q/51145007
tags question: http://stackoverflow.com/q/51020482
tags question: http://stackoverflow.com/q/51125227
type: Tag
tags question: http://stackoverflow.com/q/51101177
tags question: http://stackoverflow.com/q/51064649

http://stackoverflow.com/q/51115949
accepted answer: http://stackoverflow.com/a/51116483
tagged with: memory
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: biopython
type: AnsweredQuestion
upvote count: 3
type: Question
has body: I am trying to run pairwise global alignment method in biopython in loop for about 10000 pair of strings. Each string on an average is 20 characters long. Running the method for a single pair of sequences works fine. But running this in a loop, for as low as 4 pairs, results in segmentation fault. How can this be solved? from Bio import pairwise2 def myTrial(source,targ): if source == targ: return [source,targ,source] alignments = pairwise2.align.globalmx(source, targ,1,-0.5) return alignments sour = ['najprzytulniejszy', 'sadystyczny', 'wyrzucić', 'świat'] targ = ['najprzytulniejszym', 'sadystycznemu', 'wyrzucisz', 'świat'] for i in range(4): a = myTrial(sour[i],targ[i])
has answer: http://stackoverflow.com/a/51116483
score: 3
has title: Biopython pairwise alignment results in segmentation fault when run in loop

http://stackoverflow.com/q/51134270
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51159339
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: pyinstaller
score: -3
tagged with: python
tagged with: pygame
has title: Python to EXE - Space Invaders Pygame
has body: I have no clue on how to compile multiple python files into an exe. I am making a space-invaders game. The main.py is the main-menu which imports the game-mode modules: single player multiplayer etc via the command (which is in the code of main.py and import subprocess is at the top) subprocess.call("whatever game mode", shell=True) there are also dependancies on 2 resource folder named "Resource" and "Yasin" from which the various modules call images from. I am having trouble with combining all the resource folders and modules into one executable. All the examples I see are with simple python code that have only 1 python file where no images are used https://i.sstatic.net/nQ5ZL.png

http://stackoverflow.com/q/51067175
tagged with: python
tagged with: checkbox
has body: The following code generates a bokeh plot with checkboxes that can make graphs visible/invisible. It works great, but I would like to know if it's possible to limit the number of allowed checked checkboxes, for example no more than 2 at the time. import numpy as np from bokeh.io import output_file, show from bokeh.layouts import row from bokeh.palettes import Viridis3 from bokeh.plotting import figure from bokeh.models import CheckboxGroup, CustomJS output_file("line_on_off.html", title="line_on_off.py example") p = figure() props = dict(line_width=4, line_alpha=0.7) x = np.linspace(0, 4 * np.pi, 100) l0 = p.line(x, np.sin(x), color=Viridis3[0], legend="Line 0", **props) l1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend="Line 1", **props) l2 = p.line(x, np.tan(x), color=Viridis3[2], legend="Line 2", **props) checkbox = CheckboxGroup(labels=["Line 0", "Line 1", "Line 2"], active=[0, 1, 2], width=100) checkbox.callback = CustomJS.from_coffeescript(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), code=""" l0.visible = 0 in checkbox.active; l1.visible = 1 in checkbox.active; l2.visible = 2 in checkbox.active; """) layout = row(checkbox, p) show(layout) I think this can be done in javascript, but I don't know how to acces the javascript involved here. Could I just write javascript and integrate it with my bokeh plot somehow? I would really appreciate the help!
has title: Limit number of checked checkboxes for bokeh plot
has answer: http://stackoverflow.com/a/51072605
tagged with: bokeh
type: Question
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/51117498
score: 0
has comment: http://stackoverflow.com/comment/89221128
tagged with: python
linked to: http://stackoverflow.com/q/1964996
type: UnansweredQuestion
upvote count: 1
duplicate of: http://stackoverflow.com/q/1964996
has answer: http://stackoverflow.com/a/51117557
has answer: http://stackoverflow.com/a/51117565
downvote count: 1
type: Question
has body: I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me. The current script I have is: x = input() print(x) print(type(x)) However, regardless of i input a string, integer or float it will always print string? Any suggestions?
has comment: http://stackoverflow.com/comment/89221150
has title: Everything appears to be defined as a string? Python
has comment: http://stackoverflow.com/comment/89221146
has comment: http://stackoverflow.com/comment/89221114
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/89070260
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51038979
has text: When you say `specific radius`, in which units would you like that to be? Data coordinates? Axis fractions? Fraction of display with? Pixels? As you have discovered, `markersize` is proportional to the axis such that if you zoom in, the markers stay the same size.

http://stackoverflow.com/q/51091680
has comment: http://stackoverflow.com/comment/89171643
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89175010
has comment: http://stackoverflow.com/comment/89171841
has title: Activating VT100 via os.system('')?
type: Question
upvote count: 6
tagged with: console
has comment: http://stackoverflow.com/comment/89173082
tagged with: windows
tagged with: vt100
tagged with: windows-10
favorite count: 0
has body: After Win10 conhost got VT100 support, I played around with it a bit. Eventually I found out os.system('') activated the support in Python and got the following result: import os print('\033[36mTest\033[0m') os.system('') print('\033[36mTest\033[0m') Output [36mTest[0m Test (Second Test was printed in blue.) I have read here that Python does not request that Windows enables VT100, so why does os.system activate it anyways?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/118807995
has comment: http://stackoverflow.com/comment/89172101
score: 6
has comment: http://stackoverflow.com/comment/89172827
tagged with: python

http://stackoverflow.com/q/51111386
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89209789
linked to: http://stackoverflow.com/q/8306654
has title: Combinations without duplicates of all elements in Python
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: To clarify the picture, if i have a string: 'pac' I would want to get the list of every permutation of it, in this example: ['p', 'a', 'c', 'pa', 'pc', 'pac'] Just like i would type any of it in some search engine like the one on Ebay and it would pop up "pac" as a suggestion. Code bellow is what i achieved thus far, but it's obviously not working as it should. 'Names' is just a list with multiple names, for instance: ['pac', 'greg', 'witch'] letters = {} for name in names: temp = [] letter = [] temp2 = [] for let in name: let = let.lower() temp.append(let) letter.append(let) for i in range(0, len(name)): for j in range(1, len(name) - i): print(i, j, end=' ') to_add = letter[i] + temp[j] print(to_add, temp2) temp2.append(to_add) letter.append(to_add) temp = temp2 temp2 = [] letters[name] = letter return letters If there is built-in function feel free to share it with me, but that's not the core of the problem.
has comment: http://stackoverflow.com/comment/89209903
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51111413
has comment: http://stackoverflow.com/comment/89209806
has comment: http://stackoverflow.com/comment/89209795

http://stackoverflow.com/q/51089470
type: Question
has title: How do I edit my function in python such that my output dataframe shows N/A?
score: 0
tagged with: pandas
tagged with: api
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51089551
tagged with: python
has body: I have defined a function below in python to extract hours of operation based on business_id that I have already retrieved: def hours_operation(business_id): day = day_open(business_id) start = day_start(business_id) end = day_end(business_id) day1 = [] for i in day: try: value = "start"+str(i) except: value = 'None' day1.append(value) dict1 = {} for i in range(len(day1)): dict1[day1[i]]=start[i] start_df = pd.DataFrame(dict1, index=[0]) day2 = [] for i in day: day2.append("end"+str(i)) dict2 = {} for i in range(len(day2)): dict2[day2[i]]=end[i] end_df = pd.DataFrame(dict2, index=[0]) for i in day: start_df['end'+str(i)]=end_df['end'+str(i)] return start_df The issue is that my output appears like this: Out[36]: start0 start1 start2 start3 start4 ... end2 end3 end4 end5 end6 0 1100 1100 1100 1100 1100 ... 2200 2200 2200 2200 2100 I like this format, however, in cases where a business works only 4 days a week and not 7. I want it to return start and end as N/A. This is what my desired output should look like if a business works only 4 days a weel: start0 start1 start2 start3 start4 start5 start6 end1 end2 end3 end4 end5 end6 0 1100 1100 1100 1100 1100 N/A N/A 2200 2200 2200 N/a N/A

http://stackoverflow.com/a/51026244
type: Answer
has comment: http://stackoverflow.com/comment/89048740
has comment: http://stackoverflow.com/comment/89049047
answers question: http://stackoverflow.com/q/51026172
has comment: http://stackoverflow.com/comment/89049174
score: 0
has body: You need to place your content within a table, take a look at the examples here. Years of Experience Employment Status Previous Employers Level of Education {% for data in f %} {{data.experience}} {{data.employment}} {{data.previous}} {{data.education}} {% endfor %}
has comment: http://stackoverflow.com/comment/89048317

http://stackoverflow.com/comment/89088550
score: 1
has text: @PatrickMevzek - I see it for py 3.6 as well (same code) : https://github.com/python/cpython/blob/3.6/Lib/xml/etree/ElementTree.py#L175
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51048678

http://stackoverflow.com/a/51049146
has comment: http://stackoverflow.com/comment/106123989
has body: cursor.execute( 'SELECT * FROM pools WHERE wpc_id IN ({})'.format( ','.join('?'*len(wpc_ids))), wpc_ids ) Explanation: There is a PEP about databases, PEP249, you can read it here https://www.python.org/dev/peps/pep-0249/ This PEP defines how API of database modules should be. pyodbc is the database module you're using, and it is compatible with PEP249. One of the things the PEP defines is that each module should have a paramstyle. pyodbc.paramstyle is qmark so that is why you use '?' with pyodbc. More details https://www.python.org/dev/peps/pep-0249/#paramstyle Now, instead of building a query as a string and sending it to the database, the idea is to use parameter passing, which is a way to send the query and the parameters separately... It uses the paramstyle to put placeholders in the query, then you pass a sequence of parameters as a second parameter to execute. Example: sql = 'SELECT * FROM foo WHERE id = ? AND text_col = ?' params = (12, 'testing') cursor.execute(sql, params) Note that this is not mixing the params with the string. The code is passing them as two separate arguments to .execute(). That means it will be the database's job to do the interpolation safely. Since you want to pass multiple values to the query, you must generate a string containing the number of placeholders separated by comma, same number as the elements in the list: ','.join('?'*len(wpc_ids))) # will generate ?,?,?,?,? according with length of list
type: Answer
has comment: http://stackoverflow.com/comment/89096386
score: 3
has comment: http://stackoverflow.com/comment/89092979
upvote count: 3
has comment: http://stackoverflow.com/comment/89098281
has comment: http://stackoverflow.com/comment/89090616
has comment: http://stackoverflow.com/comment/89091864
accepted answer of: http://stackoverflow.com/q/51048963
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51048963
downvote count: 0

http://stackoverflow.com/q/51025112
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55854639
has body: I have a relatively large Jupyter/Notebook (about 40GB of Pandas DFs in RAM). I'm running a Python 3.6 kernel installed with Conda. I have about 115 cells that I'm executing. If I restart the kernel and run the cells, my whole notebook runs in about 3 minutes. If I re-run a simple cell that's not doing much work (i.e. a function definition), it takes an extremely long time to execute (~15 minutes). I cannot find any documentation online that has Jupyer notebook installation best practices. My disk usage is low, available RAM is high and CPU load is very low. My swap space does seem to be maxed out, but I'm not sure what would be causing this. Any recommendations on troubleshooting a poor-performing Jupyter notebook server? This seems to be related to re-running cells only.
type: Question
upvote count: 15
accepted answer: http://stackoverflow.com/a/55854639
downvote count: 0
score: 15
answer count: 1
favorite count: 0
tagged with: jupyter-notebook
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89042897
tagged with: python
has title: Jupyter notebook is extremely slow when re-running cells

http://stackoverflow.com/comment/89086688
type: Comment
comment on: http://stackoverflow.com/a/51045407
has text: It's evident from your code that the files you want to transfer from are in a subdirectory of the current local directory. It doesn't matter whether you change the current local directory or not. You just have to make sure you open the correct file in your `open` call, and have the correct target in the STOR command.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51043403
answers question: http://stackoverflow.com/q/51042791
upvote count: 1
has comment: http://stackoverflow.com/comment/89078729
score: 1
has comment: http://stackoverflow.com/comment/89078928
has comment: http://stackoverflow.com/comment/89078503
downvote count: 0
has comment: http://stackoverflow.com/comment/89079103
has body: With Python 3.6 f-strings Create a dictionary from cell_df m = dict(cell_df.values) def fmt(rec): pre, txt = rec.split(maxsplit=1) return pre + ' ' + ', '.join( f'{a} from {b} to {c} {m[a]}' for a, b, c in map(str.split, map(str.strip, txt.split(','))) ) record_df.record_values.apply(fmt) 0 start abc1b from 1 to 2 (h 1, a 2, a4), daf1g ... 1 start adc2g from 6 to 7 (h 2, a 4, a5), adg2d ... 2 start abc1b from 10 to 13 (h 1, a 2, a4), adc2... Name: record_values, dtype: object pre, txt = rec.split(maxsplit=1) lops off that initial start bit and puts it into the pre name. This leaves txt with the triples we want to reformat. Then I want to split(',') the value in txt For each element in that split I want to strip off excess spaces Then I want to split those results by spaces This should result in a list of lists or Iterable of Iterables where each Iterable should be of length 3 I can unpack those 3 values into a, b, and c Then I reformat those with an f-string or str.format function Put everything back together with a ', '.join Pre-Python 3.6 m = dict(cell_df.values) def fmt(rec): pre, txt = rec.split(None, 1) return pre + ' ' + ', '.join( '{} from {} to {} {}'.format(a, b, c, m[a]) for a, b, c in map(str.split, map(str.strip, txt.split(','))) ) record_df.record_values.apply(fmt) Tailored for OP m = dict(cell_df.values) def fmt(rec): pre, txt = rec.split(None, 1) return pre + ' ' + ', '.join( '{} from {} to {} {}'.format(a, b, c, m[a]) for a, b, c in map(str.split, map(str.strip, map(str, txt.split(',')))) ) record_df.record_values.apply(fmt)
has comment: http://stackoverflow.com/comment/89079608
type: Answer
has comment: http://stackoverflow.com/comment/89079375
has comment: http://stackoverflow.com/comment/89078841

linechart
tag name: linechart
tags question: http://stackoverflow.com/q/51065591
type: Tag

http://stackoverflow.com/comment/89058300
type: AnswerComment
comment on: http://stackoverflow.com/a/51032809
score: 0
type: Comment
has text: @Solaiman Try to replace `parsed['links']['next']` in `{% set url ....` string with `next` and initialize `next` above using `set`. I've updated my answer.

http://stackoverflow.com/comment/89118132
has text: It is not easy to infer from this code only. can you post the code for whole model architecture?
score: 0
comment on: http://stackoverflow.com/q/51063969
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89194779
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51095970
has text: The output from that command is: `Skipping fiona as it is not installed Skipping geopandas as it is not installed Skipping shapely as it is not installed`
score: 0

http://stackoverflow.com/a/51165145
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51165040
accepted answer of: http://stackoverflow.com/q/51165040
type: Answer
score: 1
has body: You have two problems: You're using end.lower instead of end.lower(). This means that Python will see the method str.lower instead of its result. You use is instead of ==. This forces Python to check if the two are the same object, i.e., in the same physical space on your computer. == checks if they have the same value. In general, you pretty much always want ==.

http://stackoverflow.com/q/51108451
type: Question
upvote count: 2
answer count: 1
has title: Remove \n from dictionary python
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51108453
accepted answer: http://stackoverflow.com/a/51108453
downvote count: 0
has body: My dictionary looks like below: '{\n "bindings": [\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/browser"\n },\n {\n "members": [\n "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",\n "user:rohithmn03@gmail.com"\n ],\n "role": "roles/owner"\n },\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/viewer"\n }\n ],\n "etag": "BwVvsH-HhI0=",\n "version": 1\n}\n' I need to remove \n from it; But strip() is not working on it. Do we have any other way top remove it..!? Regards, Rohith

http://stackoverflow.com/comment/89109307
type: Comment
comment on: http://stackoverflow.com/a/51058992
score: 0
type: AnswerComment
has text: This is with firefox can you give some solution with chrome browser?

http://stackoverflow.com/q/51070029
score: 1
has comment: http://stackoverflow.com/comment/89130050
type: Question
accepted answer: http://stackoverflow.com/a/51070076
upvote count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/51070076
answer count: 1
has comment: http://stackoverflow.com/comment/89130009
favorite count: 0
has body: I'm currently writing up a Discord bot in Python and am building an ip info command. However, when I try to run it, it shows this error: 'dict' object has no attribute 'status' This is my current python code: import discord import datetime import pymysql import time from datetime import timedelta, timezone import asyncio import re import os import requests import json if message.content.startswith('!ipinfo'): input = message.content.replace('!ipinfo', '').strip() try: req = requests.get('http://ip-api.com/json/{}'.format(input)) resp = json.loads(req.content.decode()) if resp.status.code == 200: if resp['status'] == 'success': # valid ip await channel.send(content='IP Logging Here.') elif resp['status'] == 'fail': await channel.send(content='API Request Failed.') else : await channel.send(content='HTTP Request Failed: Error {}'.format(req.status_code)) except Exception as e: print(e) This is the data I should be getting from the API: (Test IP) { "as":"AS15169 Google LLC", "city":"Mountain View", "country":"United States", "countryCode":"US", "isp":"Google", "lat":37.4192, "lon":-122.0574, "org":"Google", "query":"74.125.224.72", "region":"CA", "regionName":"California", "status":"success", "timezone":"America/Los_Angeles", "zip":"94043" } Does anybody know how to fix this error?
has title: Python 'dict' object has no attribute 'status'
has comment: http://stackoverflow.com/comment/89129993
tagged with: python
type: AnsweredQuestion

postgresql
tags question: http://stackoverflow.com/q/51124725
tags question: http://stackoverflow.com/q/51016095
tags question: http://stackoverflow.com/q/51139470
tags question: http://stackoverflow.com/q/51045848
tags question: http://stackoverflow.com/q/51081315
tags question: http://stackoverflow.com/q/51167342
tags question: http://stackoverflow.com/q/51155556
tags question: http://stackoverflow.com/q/51118815
tags question: http://stackoverflow.com/q/51117659
tags question: http://stackoverflow.com/q/51108552
tags question: http://stackoverflow.com/q/51136153
tags question: http://stackoverflow.com/q/51079104
tags question: http://stackoverflow.com/q/51099754
tag name: postgresql
tags question: http://stackoverflow.com/q/51100450
tags question: http://stackoverflow.com/q/51130636
tags question: http://stackoverflow.com/q/51147291
tags question: http://stackoverflow.com/q/51164792
tags question: http://stackoverflow.com/q/51088340
tags question: http://stackoverflow.com/q/51037568
tags question: http://stackoverflow.com/q/51141174
type: Tag
tags question: http://stackoverflow.com/q/51164239
tags question: http://stackoverflow.com/q/51145234
tags question: http://stackoverflow.com/q/51094522
tags question: http://stackoverflow.com/q/51027889
tags question: http://stackoverflow.com/q/51120245
tags question: http://stackoverflow.com/q/51140037
tags question: http://stackoverflow.com/q/51014492

http://stackoverflow.com/comment/89236647
type: Comment
type: QuestionComment
has text: You might be interested in this Github repo, which uses NCBI's E-utilities endpoints which, I believe, returns much of the same information: https://github.com/jordibc/entrez
comment on: http://stackoverflow.com/q/51100224
score: 0

http://stackoverflow.com/q/51109420
has comment: http://stackoverflow.com/comment/89205891
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89205899
has comment: http://stackoverflow.com/comment/89206265
has comment: http://stackoverflow.com/comment/89206048
upvote count: 1
has comment: http://stackoverflow.com/comment/89206219
has comment: http://stackoverflow.com/comment/89206423
downvote count: 1
has answer: http://stackoverflow.com/a/51109466
has comment: http://stackoverflow.com/comment/89206297
has title: How to know file path from binary python file?
type: Question
has comment: http://stackoverflow.com/comment/89206010
has body: I am noobie in python. I have seen a file in my /usr/bin/xyz.py. Whenever I execute it, It get some work done(not related to the question.) My question is I want to find where the code of this file (which is generating this python file. I am saying so whenever I write name of file in my terminal and press enter it start executing it. and also i tried open it with vim. The file has unreadable characters) Is it possible to find the code ? I get this whenever I open a file with vim. I am remotely opening it.
answer count: 1
has comment: http://stackoverflow.com/comment/89206304
has comment: http://stackoverflow.com/comment/89206357
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89206623
tagged with: python
has comment: http://stackoverflow.com/comment/89205927

http://stackoverflow.com/q/51118565
favorite count: 0
tagged with: python-3.x
has body: So I want to use Dataset API for batching my large dataset (~8GB) as I am suffering from large idle times when using my GPU as I am passing data from python to Tensorflow using feed_dict. When I follow the tutorial as mentioned here: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/5_DataManagement/tensorflow_dataset_api.py When running my simple code: one_hot_dataset = np.load("one_hot_dataset.npy") dataset = tf.data.Dataset.from_tensor_slices(one_hot_dataset) I am getting the error message with TensorFlow 1.8 and Python 3.5: Traceback (most recent call last): File "&lt;ipython-input-17-412a606c772f&gt;", line 1, in &lt;module&gt; dataset = tf.data.Dataset.from_tensor_slices((one_hot_dataset)) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 235, in from_tensor_slices return TensorSliceDataset(tensors) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1030, in __init__ for i, t in enumerate(nest.flatten(tensors)) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1030, in &lt;listcomp&gt; for i, t in enumerate(nest.flatten(tensors)) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1014, in convert_to_tensor as_ref=False) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1104, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 235, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 214, in constant value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "/anaconda2/envs/tf/lib/python3.5/site-packages/tensorflo…
tagged with: python
type: AnsweredQuestion
tagged with: tensorflow
type: Question
tagged with: pipeline
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/53382823
downvote count: 0
has title: Tensorflow Dataset API - .from_tensor_slices() / .from_tensor() - cannot create a tensor proto whose content is larger than 2gb
tagged with: tensorflow-datasets
has comment: http://stackoverflow.com/comment/108294520
accepted answer: http://stackoverflow.com/a/53382823
answer count: 1

http://stackoverflow.com/comment/89228787
comment on: http://stackoverflow.com/a/51121619
has text: My apologies: I swapped `C` and `X` when copying my solution here. It should be fixed now.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51143881
has title: Display variable error pyautogui
has comment: http://stackoverflow.com/comment/89273664
tagged with: pytest
tagged with: jenkins
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: pyautogui
answer count: 2
tagged with: environment-variables
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57830653
has body: I am using pyautogui and pytest to automate the testing of a GUI app (python pyqt, pyside). My tests run without errors when I run from command line but gives me following error while importing pyautogui when I am running through jenkins: tests/test_enlighten.py:1: in &lt;module&gt; import re, sys, signal, logging, argparse, pyautogui, subprocess /usr/lib/python2.7/site-packages/pyautogui/__init__.py:115: in &lt;module&gt; from . import _pyautogui_x11 as platformModule /usr/lib/python2.7/site-packages/pyautogui/_pyautogui_x11.py:160: in &lt;module&gt; _display = Display(os.environ['DISPLAY']) /usr/lib64/python2.7/UserDict.py:23: in __getitem__ raise KeyError(key) E KeyError: 'DISPLAY' I read about setting DISPLAY variable and tried this new_env = dict(os.environ) new_env['DISPLAY'] = '0.0' I tried 'localhost:0' value instead but it still failed. E DisplayConnectionError: Can't connect to display "localhost:0": [Errno 111] Connection refused Any direct help or recommended reading would be appreciated.
has answer: http://stackoverflow.com/a/57852535
tagged with: python
has comment: http://stackoverflow.com/comment/89274437

http://stackoverflow.com/a/51181834
score: 5
type: Answer
answers question: http://stackoverflow.com/q/51162500
upvote count: 5
downvote count: 0
has body: The Dataset.list_files() API uses the tf.matching_files() op to list the files matching the given pattern. You can also get the list of files as a tf.Tensor using that op, and pass it directly to sess.run(): filenames_as_tensor = tf.matching_files("../*.png") filenames_as_array = sess.run(filenames_as_tensor) for filename in filenames_as_array: print(filename)

http://stackoverflow.com/q/51046320
upvote count: 1
downvote count: 1
type: Question
tagged with: automation
has body: I am working on automating a manual task. I extract a model number, example " ABCDXY" from an image. This model number has to go into "www.designlights.org" (That website has a list of energy efficient lights). (I have a code to extract the text from the image) There is a search bar on the homepage of that website. If the model number I search is found, some details about the model will be displayed. If there is a matching result, then its an energy efficient light. Ideal case:I need a screenshot of the result. But if there is a matching result, its okay to either display the result or send a message "OK" to the user. To summarise: Search for that model number in the website, return the result. The search term would be dynamic and automatic. Need a code snippet to make this work
score: 0
linked to: http://stackoverflow.com/q/40497712
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89083864
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89083691
tagged with: python
has title: python code to fill a search bar and get results
answer count: 0
has comment: http://stackoverflow.com/comment/89198350

http://stackoverflow.com/comment/138643961
score: 0
type: AnswerComment
has text: @elelias I haven't thought about this deeply, so I may be wrong, but I think you're correct in the case that your list always starts with an object of this type. However, if you're going to be using the class in combination with other objects, you might introduce odd bugs down the line if `__radd__` always returns itself and doesn't actually try to do any addition with the thing to its left.
type: Comment
comment on: http://stackoverflow.com/a/60513363

http://stackoverflow.com/q/51158299
has comment: http://stackoverflow.com/comment/89300450
tagged with: django
tagged with: python
answer count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/89304585
type: Question
tagged with: django-models
has title: Django models access outside Django without access to the settings file
score: 0
has body: I would like to allow people that don't have access to the Django project root folder (so no access to settings.py file and no DB password) to use specific models outside of Django. I would like some users to be able to query certain tables in the database using the powerful Django structure (querysets etc...) without giving full access to all the tables. Would any of the following strategies work? Is it even possible to do that? And what are the best practices for this kind of issues? Idea 1: Setting-up django using my_project.settings. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") django.setup() The problem is that it requires access to the project root folder and give access to all the database Idea 2: Setting-up django using a different database user with restricted access from django.conf import settings settings.configure( DATABASE_ENGINE = 'django.db.backends.mysql', DATABASE_NAME = '&lt;db_name&gt;', DATABASE_USER = 'new_user', DATABASE_PASSWORD = '&lt;psw&gt;', DATABASE_HOST = '&lt;host&gt;', INSTALLED_APPS = ... ) I didn't manage to make this work yet but I feel like the django.setup() will fail because the DB user won't have access to all the tables. Also it still needs access to the project root folder. Idea 3: Using the database (MySQL) directly from python, no link at all with Django. This is probably not advised but that's the only solution I have so far. Is there any django-like python package that would allow querying the database in a similar way to Django? Idea 4: Maybe something using a custom manage.py command?
type: UnansweredQuestion

apache
tag name: apache
tags question: http://stackoverflow.com/q/51151289
tags question: http://stackoverflow.com/q/51026770
tags question: http://stackoverflow.com/q/51141429
tags question: http://stackoverflow.com/q/51088005
tags question: http://stackoverflow.com/q/51063327
tags question: http://stackoverflow.com/q/51029132
tags question: http://stackoverflow.com/q/51024719
type: Tag
tags question: http://stackoverflow.com/q/51051436

http://stackoverflow.com/comment/89208587
has text: @AdamSmith - yes, but casefold() also has unintended side effects, such as changing the length of the string.
comment on: http://stackoverflow.com/q/51071358
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51116380
has answer: http://stackoverflow.com/a/51116767
tagged with: python
has title: How to retrieve a price from inside an html block circumventing an tag
has comment: http://stackoverflow.com/comment/89219060
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51116696
type: Question
answer count: 2
has body: I'm using Python with BeautifulSoup. I have a page with several of these html blocks: &lt;div class="col-sm-6 col-md-3"&gt; &lt;div class="thumbnail box-hover thumb-article-product"&gt; &lt;div class="ProductPicWrapper"&gt; &lt;div class="test"&gt; &lt;a href="product_info.php?products_id=5055856419716"&gt;&lt;img width="120" height="120" src="https://cdn.smartoys.be/catalog/images/thumbs/120_120/products/x5055856419716.JPG.pagespeed.ic.uX1UW7-Gxw.webp" title="The Elder Scrolls Online : Summerset" alt="The Elder Scrolls Online : Summerset" class="img-responsive" data-pagespeed-url-hash="3637984103" onload="pagespeed.CriticalImages.checkImageForCriticality(this);"/&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="caption"&gt; &lt;p class="text-center nameart"&gt;&lt;a href="product_info.php?products_id=5055856419716"&gt;The Elder Scrolls Online : Summerset&lt;/a&gt;&lt;/p&gt; &lt;p class="group inner list-group-item-heading nameart-ean text-center"&gt;5055856419716&lt;/br&gt;Playstation 4&lt;/p&gt; &lt;hr&gt; &lt;p class="text-center article-price article-price-used "&gt;Dès &lt;span itemprop="price"&gt;10&lt;span class="product-price-sm"&gt;.00&amp;euro;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt; &lt;p class="text-center"&gt; &lt;span class="label"&gt;&lt;/span&gt; &lt;/p&gt; &lt;div class="text-center"&gt; &lt;div class="btn-group"&gt; &lt;a href="product_info.php?products_id=5055856419716" class="btn btn-danger" role="button"&gt;Voir le produit&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;/div&gt; I would like to retrieve the price. I managed to do it from a page I saved locally from Chrome, but the html code is very different when getting it directly online. From the downloaded page I just did the following to get the price (took out the loops for simplicity): productblocks = soup.find_all("div",{"class": "col-sm-6 col-md-3"}) gameprice = productblocks[i].find("p", {"class": "text-center article-price article-price-used "}).text.encode('utf-8')…
score: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/51116767
has answer: http://stackoverflow.com/a/51116696

http://stackoverflow.com/comment/89024910
comment on: http://stackoverflow.com/q/51016044
has text: i build those tuples becase they store the indicies (row, column index) of the data I need to extract from another dataframe..am i supposed to be using a non-tuple way of doing this?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89233919
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51124403
has text: @Neo I have only 1 python version installed. So that souldn't be an issue.
score: 0

http://stackoverflow.com/q/51135118
type: UnansweredQuestion
has title: Gensim Word2vec Freeze some wordvectors and Update others
tagged with: word2vec
tagged with: python
tagged with: gensim
type: Question
has answer: http://stackoverflow.com/a/51139393
score: 0
answer count: 1
has body: Regarding word2vec with gensim, Suppose you already trained a model on a big corpus, and you want to update it with new words from new sentences, but not update the words which already have a vector. Is it possible to freeze the vectors of some words and update only some chosen words (like the new words) when calling model.train ? Or maybe is there a trick to do it ? Thanks.

http://stackoverflow.com/a/51033684
accepted answer of: http://stackoverflow.com/q/51030493
answers question: http://stackoverflow.com/q/51030493
type: Answer
downvote count: 0
score: 2
upvote count: 2
has body: The Sum passes doit() to the object it is trying to sum, which is where the error occurs. So, a minimal example is x = symbols('x') f = Poly(0, x) f.doit() # GeneratorsNeeded: can't initialize from 'dict' without generators Looks like a bug, an edge case not being addressed correctly. But there is a workaround: pass an expression to Sum (which is what it expects anyway), not a Poly object. A Poly is turned into an expression with as_expr(). f = Poly(0, m) Sum(f.as_expr(), (m, 0, n)).doit() # 0
type: AcceptedAnswer

http://stackoverflow.com/q/51163397
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51163489
has body: I've recently stumbled upon coding task, and I've struggled to get it right. It goes like this: Given a non-empty string s and a list word_list containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the word_list does not contain duplicates, but each word can be used more than once. For example, given: s = 'whataniceday' word_list = ['a', 'what', 'an', 'nice', 'day'] Return True, because 'whataniceday' can be segmented as 'what a nice day'. I came up with a pretty naive solution, that works for this particular example, but it is not hard to make it fail, for example by adding a word to word_list that other word in the list starts with (i.e. ['a', 'wha', 'what', 'an', 'nice', 'day']). There are plenty of other things that can mess up my solution, but anyway here goes: s = "whataniceday" word_list = ["h", "a", "what", "an", "nice", "day"] def can_be_segmented(s, word_list): tested_str = s buildup_str = '' for letter in tested_str: buildup_str += letter if buildup_str not in word_list: continue tested_str = tested_str[len(buildup_str):] buildup_str = '' return bool(tested_str == '' and buildup_str == '') print(can_be_segmented(s, word_list)) Do you guys have an idea of how to fix it? Or maybe there is a better approach to this problem?
accepted answer: http://stackoverflow.com/a/51163520
has answer: http://stackoverflow.com/a/66539802
type: Question
score: 5
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/51163521
has answer: http://stackoverflow.com/a/51163520
has comment: http://stackoverflow.com/comment/89310119
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51163489
tagged with: python
has title: Check if string can be splitted into sentence using words in provided list
answer count: 4

http://stackoverflow.com/a/51139297
has body: One option is to use itertools.repeat to repeat each array whose length is less than length of the longest array. from itertools import izip_longest, repeat, chain cols = df.columns def zip_with_repeat(row, cols): M = max(len(row[c]) for c in cols) return izip_longest( *[list(chain(*repeat(row[c], (M - len(row[c])) + 1)))[:M] for c in cols] ) df.rdd.flatMap(lambda row: zip_with_repeat(row, cols)).toDF(cols).show() #+---+---+---+ #| a| b| c| #+---+---+---+ #| 1| 3| 7| #| 1| 4| 8| #| 1| 5| 9| #| 1| 6| 10| #+---+---+---+ For illustrative purposes, suppose you instead had the following DataFrame: #+--------+------------+-------------+ #| a| b| c| #+--------+------------+-------------+ #| [1]|[3, 4, 5, 6]|[7, 8, 9, 10]| #|[10, 20]|[30, 40, 50]| [70, 80, 90]| #+--------+------------+-------------+ The code would produce: #+---+---+---+ #| a| b| c| #+---+---+---+ #| 1| 3| 7| #| 1| 4| 8| #| 1| 5| 9| #| 1| 6| 10| #| 10| 30| 70| #| 20| 40| 80| #| 10| 50| 90| #+---+---+---+ Notice that the 10 repeated once to fill in the array in column a to the appropriate length.
answers question: http://stackoverflow.com/q/51137909
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51137909

http://stackoverflow.com/q/51156940
has comment: http://stackoverflow.com/comment/89297404
score: 0
tagged with: django-class-based-views
tagged with: python
has answer: http://stackoverflow.com/a/51156980
tagged with: django
type: Question
type: AnsweredQuestion
tagged with: caching
accepted answer: http://stackoverflow.com/a/51156980
has title: How can I access the response object in DetailView?
has body: I want to access the response object rendered in a DetailView so that I can manually cache it (and delete it from cache on specific uses). What's the best way to access the response object that gets created by the DetailView?
answer count: 1

http://stackoverflow.com/comment/89284238
has text: I removed the part where I stated this may be the reason behind error.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51149916

http://stackoverflow.com/comment/89084575
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51046266
score: 0
has text: I added the missing part of the code. The nodes and edges of the graph are the ones created by the networkx function R = nx.grid_graph(dim=[N,N]) So they are like (0,0),(0,1),(0,2)...(0,N),(1,0).. and so on and their links are [(0,0),(0,1)]...

http://stackoverflow.com/a/54724052
has body: Try pip install --only-binary :all: mysqlclient Worked for me
type: Answer
has comment: http://stackoverflow.com/comment/106564761
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51062920
downvote count: 0

http://stackoverflow.com/q/51107701
has title: How to share a variable across modules in Kivy
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51124306
possible better answer: http://stackoverflow.com/a/51107942
has answer: http://stackoverflow.com/a/51107942
type: Question
answer count: 2
tagged with: variables
score: 0
has answer: http://stackoverflow.com/a/51124306
tagged with: kivy
has body: I am trying to declare a variable in my .py file that can be used in my .kv file. I am declaring the variable in my App class and calling it in my .kv file, but I am getting an error. Here is my .py class SwitchScreenU553(Screen): pass presentation = Builder.load_file("kivy.kv") class MainApp(App): MY_NUMBER = .8 def build(self): return presentation and here is my .kv &lt;SwitchScreenU553&gt;: name: "switchU553" canvas.before: Rectangle: pos: self.pos size: self.size source: 'background.png' FloatLayout: ToggleButton: text: "HB" color: 1,1,1,1 font_size: app.MY_NUMBER size_hint: 0.13,0.4 pos_hint: {"center_x":(0.3/8)+.05, "center_y":.8} When I try to use this I get the following error: This seems to work for others, but I am obviously doing something wrong.

http://stackoverflow.com/q/51048648
tagged with: python
has comment: http://stackoverflow.com/comment/89101173
tagged with: matplotlib-basemap
has title: Basemap cannot locate .shp file
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89104350
score: 1
has comment: http://stackoverflow.com/comment/89197036
has comment: http://stackoverflow.com/comment/89103352
has answer: http://stackoverflow.com/a/51105075
has body: I am trying to load a shapefile and plot it using basemap, but everytime I try to load the shapefile basemap throws the error that it cannot loacte the .shp file even though the .shp file is in the folder that I am giving it the path to. Can anyone tell me what I am doing wrong here? My code: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(llcrnrlon=-86.637575,llcrnrlat=41.855400,urcrnrlon=-82.946169,urcrnrlat=45.116972, resolution='l', projection='tmerc', lat_0 = 43.513523, lon_0 = -84.660036) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='#ddaa66',lake_color='aqua') map.drawcoastlines() # Shape file location map.readshapefile('../Desktop/Neighborhoods-MI', 'Neighborhoods') The Neighborhoods-MI folder has Neighborhoods-MI.shp, Neighborhoods-MI.shx, Neighborhoods-MI.prj, and Neighborhoods-MI.dbf files in it. I've also tried just using 'Neighborhoods-MI' instead of the entire path to the file, but nothing works. Note: I get a deprecated warning as well, but I don't think this is the issue /anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1708: MatplotlibDeprecationWarning: The axesPatch function was deprecated in version 2.1. Use Axes.patch instead. limb = ax.axesPatch /anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1711: MatplotlibDeprecationWarning: The axesPatch function was deprecated in version 2.1. Use Axes.patch instead. if limb is not ax.axesPatch:
answer count: 1
downvote count: 0
favorite count: 0
tagged with: shapefile
accepted answer: http://stackoverflow.com/a/51105075

http://stackoverflow.com/q/51111522
has answer: http://stackoverflow.com/a/51116905
has body: When you want to select some text from HTML using regex and it is of importance what comes after the potential selection I would imagine that you'd have to do something like this: selected = re.findall(r'&lt;a (.*?) &gt;About', text) Obviously this does not work but what is the right way to do this?
accepted answer: http://stackoverflow.com/a/51116776
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89210005
score: 1
possible better answer: http://stackoverflow.com/a/51111551
has answer: http://stackoverflow.com/a/51111551
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89210048
has comment: http://stackoverflow.com/comment/89210713
answer count: 3
has answer: http://stackoverflow.com/a/51116776
tagged with: python
tagged with: regex
favorite count: 0
has title: Looking at what comes after potential selection regex
upvote count: 1

pyqt4
tags question: http://stackoverflow.com/q/51164466
tags question: http://stackoverflow.com/q/51157987
tags question: http://stackoverflow.com/q/51125144
tags question: http://stackoverflow.com/q/51093034
type: Tag
tags question: http://stackoverflow.com/q/51012350
tags question: http://stackoverflow.com/q/51108259
tags question: http://stackoverflow.com/q/51046440
tags question: http://stackoverflow.com/q/51058236
tags question: http://stackoverflow.com/q/51111152
tags question: http://stackoverflow.com/q/51092302
tags question: http://stackoverflow.com/q/51144903
tags question: http://stackoverflow.com/q/51032311
tags question: http://stackoverflow.com/q/51025716
tags question: http://stackoverflow.com/q/51135026
tags question: http://stackoverflow.com/q/51144569
tag name: pyqt4

http://stackoverflow.com/q/51089318
upvote count: 0
score: -2
tagged with: pandas
answer count: 1
has body: df=pd.concat([index,text['word']],1) Index word 0 0 I 1 1 am 2 2 so 3 3 good 4 4 and 5 5 smart df_series=[] for d in range(0,2): df_series.append(df) def pos(x): position=[] for u in x: position.append(np.random.choice(u[0])) return position df1 0 0 5 1 2 0 0 1 1 0 final=[] L=['NA','****'] for eachtable in df_series: # print(eachtable) eachtable.loc[pos(df1),'word'] = random.choice(L) final.append(eachtable) final Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA As of now I am getting like this only.Position is changing only for first table and repeating the same position for all the iteration.I want to changed position for each iteration. Can anyone find the mistake in my code and help me with this. I want like something like this print(final) Index word 0 **** 1 NA 2 so 3 good 4 and 5 NA Index word 0 I 1 am 2 **** 3 good 4 NA 5 smart
favorite count: 0
has comment: http://stackoverflow.com/comment/89222360
downvote count: 2
has title: how to replace the column value in a set of dataframe with compared with another set of dataframe
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51135076
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51135076
type: Question

http://stackoverflow.com/q/51028699
tagged with: python
type: UnansweredQuestion
type: Question
has body: I have a python script that communicates to a device over serial interface. There is a function my_fn() to be exectuted which sends some commands to the serial interface and waits for recieved_fn() to be triggered by device. If recieved_fn() is not triggered within 5 sec then execute my_fn() again. How should I monitor if recieved_fn() is executed or not within a time period of 5 seconds. I am running python 2.7 on windows 10. Thanks
tagged with: python-2.7
has title: python script to monitor execution of a function on windows
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51029160

http://stackoverflow.com/comment/125547986
type: Comment
score: 1
has text: can you limit results to only say `.json` files ?
type: AnswerComment
comment on: http://stackoverflow.com/a/62498656

http://stackoverflow.com/comment/89308184
has text: Create a dictionary and append them
comment on: http://stackoverflow.com/q/51162397
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51122822
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51122413
score: 0
has body: Try Regex: ^(?:\d{1,2}(?:(?:-|/)|(?:th|st|nd|rd)?\s))?(?:(?:(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?:(?:-|/)|(?:,|\.)?\s)?)?(?:\d{1,2}(?:(?:-|/)|(?:th|st|nd|rd)?\s))?)(?:\d{2,4})$ Demo
type: Answer

http://stackoverflow.com/q/51013093
upvote count: 2
linked to: http://stackoverflow.com/q/3080450
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51015620
has title: Simultaneous replacement of SymPy logic function
type: Question
tagged with: sympy
downvote count: 0
has body: I came across a problem substituting variables in logical formulas in Sympy. Here's a minimal example - from sympy import * x, y = symbols('x y') Nand(x, y).subs({x: Nand(x, y)}, simultaneous=True) This fails both in my local interperter, and in the live shell on SymPy Docs, with the error message Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/base/data/home/apps/s~sympy-live-hrd/49.400254913747479351/sympy/sympy/core/basic.py", line 889, in subs d = Dummy(commutative=new.is_commutative) File "/base/data/home/apps/s~sympy-live-hrd/49.400254913747479351/sympy/sympy/core/symbol.py", line 205, in __new__ cls._sanitize(assumptions, cls) File "/base/data/home/apps/s~sympy-live-hrd/49.400254913747479351/sympy/sympy/core/symbol.py", line 65, in _sanitize '%scommutativity must be True or False.' % whose) ValueError: Dummy commutativity must be True or False. Other formulations I've tried, like replacing "Nand"s with "And", don't fail. Setting simultaneous=False also doesn't fail, but will not give the desired result if I want to replace y at the same time (see this question for details why). Is this a bug in SymPy, or am misunderstanding something?
answer count: 1
has answer: http://stackoverflow.com/a/51015620
favorite count: 0

http://stackoverflow.com/comment/89128484
score: 0
type: Comment
has text: I get this error while trying to do that ^ SyntaxError: unexpected EOF while parsing
type: QuestionComment
comment on: http://stackoverflow.com/q/51069286

http://stackoverflow.com/q/51123382
linked to: http://stackoverflow.com/q/21798222
duplicate of: http://stackoverflow.com/q/21798222
has title: Python string scrambling
tagged with: python
has body: I want to Write a function that will take two string arguments and returns a list containing all the letters in both strings. All the letters returned should be lowercase and there should be no duplicate letters in the resulting list. Example: string_scramble('GraSS', 'grilled cheese') Should return: ['g','r','s'] My Solution: def string_scramble(string_one, string_two): l = [] str_concat = string_one + string_two str_lower = str_concat.lower() str_space = sorted(str_lower.replace(" ", "")) for i in str_space: if i not in l: l.append(i) print(l) return l string_scramble("GraSS","grilled cheese") This returns: ['a', 'c', 'd', 'e', 'g', 'h', 'i', 'l', 'r', 's']
favorite count: 0
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/51123445
has answer: http://stackoverflow.com/a/51123448
score: -1
type: Question
answer count: 2
upvote count: 0

http://stackoverflow.com/a/63291004
has comment: http://stackoverflow.com/comment/111920976
type: Answer
answers question: http://stackoverflow.com/q/51126056
has body: It seems like,there is issue related to PATH.You can try to install package with the IDE terminal.In your case just try to install a package with pycharm terminal. After that try to execute below script: import cx_Oracle import db_config user="test" pw="test" dsn="localhost:port/TEST" #here TEST is service id con = cx_Oracle.connect(user, pw, dsn) cur = con.cursor() cur.execute("select * from test_table") res = cur.fetchall() for row in res: print(row) Still having an issue then you can refer : [https://oracle.github.io/python-cx_Oracle/samples/tutorial/Python-and-Oracle-Database-Scripting-for-the-Future.html]
score: 0

http://stackoverflow.com/q/51157473
has body: I want to convert my list to a dataframe.The challenge is that the items in my list is as below and I need to extract the string value of each item of the list to a column of a data frame. List looks like Keyword = [('Hello',2.0),('Welcome',3.0),('To',3.0),('Python',4.0)] Need the Dataframe as Output: Keyword Score 0 Hello 2.0 1 Welcome 3.0 2 To 3.0 3 Python 4.0 Can someone please throw some solution.
type: UnansweredQuestion
tagged with: python
downvote count: 0
has title: Python list to data frame
score: 1
has answer: http://stackoverflow.com/a/51157506
type: Question
has answer: http://stackoverflow.com/a/51157603
has comment: http://stackoverflow.com/comment/89298886
answer count: 2
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/89209815
comment on: http://stackoverflow.com/q/51111398
has text: instead of print(df.head()) use print(df)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89175250
type: QuestionComment
comment on: http://stackoverflow.com/q/51093034
type: Comment
score: 0
has text: My question was: what functionality do you want to add to the original code? Maybe this is going the wrong way and we could indicate the correct way, that is called [XY problem](http://xyproblem.info/), please answer my question.

http://stackoverflow.com/a/78999262
type: Answer
has body: Here is my final version for this practice project: def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 print('Enter number:') try: n = input() while True: n = collatz(int(n)) print(n) if n == 1: break except ValueError: print('Please enter a number')
answers question: http://stackoverflow.com/q/51111163
score: 0

http://stackoverflow.com/a/51163959
upvote count: 2
has body: I think you're looking for groupby and nunique: df.groupby('NomeMembro')['SiglaComissao'].nunique() Which returns: NomeMembro Abelardo Camarinha 6 Vaz de Lima 11
accepted answer of: http://stackoverflow.com/q/51163941
has comment: http://stackoverflow.com/comment/89311271
answers question: http://stackoverflow.com/q/51163941
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89311263
score: 2

http://stackoverflow.com/q/51089173
linked to: http://stackoverflow.com/q/44651760
type: Question
has title: Django InconsistentMigrationHistory: Migration X is applied before its dependency Y on database 'default'
tagged with: database-migration
has answer: http://stackoverflow.com/a/64595401
upvote count: 2
has answer: http://stackoverflow.com/a/67883918
has answer: http://stackoverflow.com/a/51090569
favorite count: 0
has answer: http://stackoverflow.com/a/56126008
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: This question is similar to Django manage.py: Migration applied before its dependency and django.db.migrations.exceptions.InconsistentMigrationHistory, except that I haven't squashed migrations; I also find the answers to those questions not very specific. I have an app lucy_web for which python manage.py showmigrations yields lucy_web [X] 0001_initial [X] 0002_auto_20170614_2116 [X] 0003_auto_20170614_2139 [X] 0004_auto_20170614_2228 [X] 0005_auto_20170614_2329 [X] 0006_auto_20170615_2326 [X] 0007_auto_20170616_1827 [X] 0008_family_birth_parent [X] 0009_auto_20170621_2035 [X] 0010_family_account_holder [X] 0011_auto_20170621_2218 [X] 0012_auto_20170621_2219 [X] 0006_auto_20170616_0008 [X] 0007_auto_20170616_0016 [X] 0008_auto_20170616_0441 [X] 0009_merge_20170619_1835 [X] 0013_merge_20170621_2225 [X] 0010_auto_20170621_0101 [X] 0014_merge_20170626_1858 [X] 0010_family_user [X] 0014_merge_20170623_1748 [X] 0015_merge_20170627_0605 [X] 0016_auto_20170710_1447 [X] 0017_auto_20170710_1448 [X] 0018_session_expert_type [X] 0019_auto_20170726_1641 [X] 0020_auto_20170727_1457 [X] 0021_auto_20170727_1511 [X] 0022_auto_20170727_1518 [X] 0023_auto_20170728_1300 [X] 0024_auto_20170730_0939 [X] 0025_auto_20170730_1011 [X] 0026_auto_20170731_1433 [X] 0027_auto_20170731_2117 [X] 0026_category [X] 0028_merge_20170801_0732 [X] 0029_auto_20170801_0736 [X] 0030_family_lucy_guide [X] 0031_family_baby_name [X] 0032_auto_20170801_2215 [X] 0033_auto_20170801_2218 [X] 0034_auto_20170801_2230 [X] 0035_remove_expert_activation_date [X] 0035_category_inactive [X] 0036_merge_20170802_1543 [X] 0037_auto_20170802_1544 [X] 0038_auto_20170803_2127 [X] 0039_family_profile_link [X] 0040_family_account_holder_string [X] 0041_auto_20170808_0825 [X] 0024_expertsessiontype_packagesessiontype [X] 0042_merge_20170808_1302 [X] 0043_auto_20170808_1311 [X] 0044_auto_20170809_0750 [X] 0045_auto_20170809_1119 [X] 0046_auto_20170810_1159 [X] 0047_auto_20170811_0851 [X] 0048_auto_20170811_0851 [X] 0049_auto_201…
answer count: 4
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/38996599

http://stackoverflow.com/comment/89219049
score: 0
has text: I tried with lxml but got an error.
comment on: http://stackoverflow.com/q/51116376
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51079862
has comment: http://stackoverflow.com/comment/104228641
upvote count: 2
has comment: http://stackoverflow.com/comment/89369908
type: Answer
has body: There's many different issues that may or may not be happening. You're best bet is to plain-old troubleshoot. I saw you're comment on GitHub, so let's try a new angle; it's more than likely a building/debugging file path or directory setting which is incorrect. I noticed a file/directory setting named set_tracking_uri. def get_tracking_uri(): """ Returns the current tracking URI. Note that this may not correspond to the tracking URI of the currently active run, since the tracking URI may be updated via `set_tracking_uri`. :return: the tracking URI """ mlflow/tracking/__init__.py - lines 52-56 You could also check out the package.json for the server file path. "proxy": "http://localhost:5000", "homepage": "/static-files", "jest": { "collectCoverageFrom": [ "src/**/*.{js,jsx}", "!**/*.test.{js,jsx}", "!**/__tests__/*.{js,jsx}" ] mlflow/mlflow/server/js/package.json - lines 37-44 Make sure your files are in the correct directory compared to your settings and I'm sure it will resolve the issue.
has comment: http://stackoverflow.com/comment/104229090
score: 2
answers question: http://stackoverflow.com/q/51079061
downvote count: 0

http://stackoverflow.com/q/51098051
answer count: 2
accepted answer: http://stackoverflow.com/a/51098099
downvote count: 0
possible better answer: http://stackoverflow.com/a/51098146
tagged with: pointers
favorite count: 0
has answer: http://stackoverflow.com/a/51098099
tagged with: python
has title: How to improve code and reduce number of code?
linked to: http://stackoverflow.com/q/706721
has body: That code is exactly the same, so I want to refactor it in a simple way to reduce the number of lines. One thing which is different is min/max function execution. Is it available pointer to function in python to call min/max as a pointer to function like in C? def calculate_min(a, b, c, d, e, f): try: v = a[e][f] b[d] = v if np.isnan(b[d]) else min(b[d], v) #min() except KeyError as exc: logger.error("keyerror") def calculate_max(a, b, c, d, e, f): try: v = a[e][f] b[d] = v if np.isnan(b[d]) else max(b[d], v) #max() except KeyError as exc: logger.error("keyerror")
score: 2
tagged with: coding-style
type: AnsweredQuestion
tagged with: refactoring
has answer: http://stackoverflow.com/a/51098146
has comment: http://stackoverflow.com/comment/89183737
type: Question
upvote count: 2

http://stackoverflow.com/q/51054559
has title: How to ship bokeh server application?
has answer: http://stackoverflow.com/a/51072535
tagged with: vagrant
linked to: http://stackoverflow.com/q/38417200
tagged with: bokeh
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51075099
score: 0
tagged with: deployment
has body: What's the preferred way to deploy an application supposed to be run with bokeh serve --show to other people? I've only found a 2014 year topic of someone using Vagrant for this aim. Are there any better alternatives? Update I need 'offline' mode so that another person could launch it on his/her computer, not web access.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51046109
has comment: http://stackoverflow.com/comment/89083484
upvote count: 2
has body: Just use reversed: this_map = map(int, reversed("2 4 1 3 5".split())) for item in this_map: print(item)
type: Answer
has comment: http://stackoverflow.com/comment/89083701
downvote count: 0
answers question: http://stackoverflow.com/q/51046087
score: 2

http://stackoverflow.com/comment/89275949
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51145815
has text: I think it makes a lot more sense for the OP to configure their editor to save what they expect, than to let their editor force a crappy encoding on them and then configure Python to handle it. With a coding declaration, their code won't be portable to people who copy it from Stack Overflow or repl.it or other online sites that are in UTF-8, and he won't be able to use characters that aren't in his OEM code page, etc.

http://stackoverflow.com/comment/89166749
has text: @HackSaw -- I can certainly try. Do you mean the larger problem I'm trying to solve or the code itself to get to the point of asking the question (or something else?) I'm new here and want to make sure I understand the question (and where best to put it). Thanks for your comment.
comment on: http://stackoverflow.com/q/51087484
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89084850
type: QuestionComment
comment on: http://stackoverflow.com/q/51040326
has text: What's the expected shape of output array?
type: Comment
score: 0

http://stackoverflow.com/comment/89175143
type: AnswerComment
has text: float math can be inaccurate, I would recommend using the decimal library
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51093448

http://stackoverflow.com/q/51047041
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/94253703
downvote count: 0
tagged with: keras
has title: Results of training a Keras model different on Google Cloud
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53733468
tagged with: python
has body: I've created a script to train a keras neural net and have run it successfully on my machine (at the end of training there is roughly 0.8 validation accuracy). However, when I try to run the exact same code (on the same data) on a Google Cloud VM instance I get drastically worse results (~0.2 validation accuracy). Git status confirms that the repo in the VM is up to date with master (same with my local machine), and I have verified that its versions of tf and keras are up to date (and same as my local machine). I've also set the numpy and tensorflow random seeds before importing Keras. Has anyone run into a problem like this before? I'm at a loss for what could be causing this... the only difference I can think of is that my machine is running Python 3.6 whereas the VM is running Python 2.7. Could that account for the vast difference is training results?

http://stackoverflow.com/comment/89103365
has text: Thanks, it's more clear now.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51056095

http://stackoverflow.com/comment/89083439
type: AnswerComment
comment on: http://stackoverflow.com/a/51045922
score: 0
has text: Sounds like you should read more about what to _do_ than just read my answer about what to _say_ -- check out [this](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) stack overflow answer for more ways to do this, some of which are probably better than what I suggested. And do some reading about iterators and generators to get a better idea of how to apply them to your project.
type: Comment

http://stackoverflow.com/comment/89117769
has text: I did it by print statments. You can also test the code.
type: Comment
comment on: http://stackoverflow.com/q/51063462
score: 0
type: QuestionComment

http://stackoverflow.com/q/51059001
type: AnsweredQuestion
has body: I want to transform a pandas column that contains Nan from string to float. This is the code I tried but it keeps returning me an invalid syntax error data.VAL_DEAL=data.VAL_DEAL.apply(lambda x: float(x.replace(",","")) if math.isnan(x)!=True)
has comment: http://stackoverflow.com/comment/89108223
type: Question
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51059111
score: 0
has title: Python - apply lambda with an if condition
answer count: 1
accepted answer: http://stackoverflow.com/a/51059111

http://stackoverflow.com/q/51019458
has body: help function Hi, I'm new to python, but have been following a tutorial. I'm trying to use the help() module but I get an error message. i just can't figure it out. Does someone have a clue to my problem or what I'm doing wrong?
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/89031993
score: 1
type: Question
has answer: http://stackoverflow.com/a/51020907
has comment: http://stackoverflow.com/comment/89033182
tagged with: python-3.6
has title: Module help() under python not working

http://stackoverflow.com/comment/89071053
score: 0
has text: Maddie, I don't know if you can read the comments to the deleted answer you gave yourself (and which wasn't a proper answer) and in which you tried to ask followup questions. This isn't how StackOverflow is supposed to work, that's why the answer got deleted. Please walk through https://stackoverflow.com/tour to understand how this here works. StackOverflow wants to be a _collection_ of useful questions and answers, so forum-like discussions are only allowed in comments, not in answers.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51027245

http://stackoverflow.com/comment/89111448
has text: I am showing you the console output. The log file is writable.
comment on: http://stackoverflow.com/q/51036967
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/98500739
comment on: http://stackoverflow.com/a/51160027
type: AnswerComment
has text: Hey there! While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
score: 0
type: Comment

http://stackoverflow.com/comment/89124006
comment on: http://stackoverflow.com/q/51066880
score: 0
type: QuestionComment
type: Comment
has text: @Andersson it returns 1 in my case

http://stackoverflow.com/a/51045274
downvote count: 0
has body: I think you are looking for the __in field lookup: b = Servicio.objects.filter(nombre__startswith='Inventario').values('id') r = Informe.objects.filter(servicio_id__in=b) Django will convert the first query to a subquery resulting in SQL looking something like this: SELECT ... FROM dashboard_informe inf WHERE inf.id IN ( SELECT s.id FROM dashboard_servicio s WHERE s.nombre LIKE 'Inventario%' );
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51045209

http://stackoverflow.com/q/51119074
accepted answer: http://stackoverflow.com/a/51119156
upvote count: 0
has body: I have two dictionaries there response is like Array1= {'date': '30-06-18 22:23:01 (UTC)', 'FullName': 'NoMatch', 'image': 'Events/mili/DSC_0150.jpg', 'EventName': 'mili'} ,{'date': '30-06-18 22:23:01 (UTC)', 'FullName': 'NoMatch', 'image': 'Events/mili/DSC_0154.jpg', 'EventName': 'mili'} Array2= {'date': '30-06-18 22:23:01 (UTC)', 'FullName': 'NoMatch', 'image': 'Events/mili/DSC_0151.jpg', 'EventName': 'mili'} ,{'date': '30-06-18 22:23:01 (UTC)', 'FullName': 'NoMatch', 'image': 'Events/mili/DSC_0154.jpg', 'EventName': 'mili'} And same way in other dictionary , I want to do that is i want to get Array1 having no Array2[k]['image'] same value . Mean no image of array2 should in array1 . Result dictionary should be Array3 = {'date': '30-06-18 22:23:01 (UTC)', 'FullName': 'NoMatch', 'image': 'Events/mili/DSC_0150.jpg', 'EventName': 'mili'} i tried to do this list3 = [item for item in list1 if item not in list2] but i cant access indexs and value in this loop
has title: Remove duplicate value from another dictionary
has comment: http://stackoverflow.com/comment/89224381
has comment: http://stackoverflow.com/comment/89224086
has answer: http://stackoverflow.com/a/51119156
has comment: http://stackoverflow.com/comment/89224314
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/51119189
has comment: http://stackoverflow.com/comment/89224338
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89224367
has answer: http://stackoverflow.com/a/51119189
has comment: http://stackoverflow.com/comment/89224357
score: -1
has comment: http://stackoverflow.com/comment/89224050
type: Question
answer count: 2

http://stackoverflow.com/q/51129043
downvote count: 0
accepted answer: http://stackoverflow.com/a/51141526
favorite count: 0
tagged with: tensor
linked to: http://stackoverflow.com/q/51160386
tagged with: python
has body: I have tried it out as below. It seems to me they're the same. What's the difference between torch.Tensor() vs torch.empty() in pytorch?
score: 19
has answer: http://stackoverflow.com/a/51141526
has answer: http://stackoverflow.com/a/53296653
type: AnsweredQuestion
has title: what's the difference between torch.Tensor() vs torch.empty() in pytorch?
tagged with: pytorch
tagged with: torch
type: Question
upvote count: 19
possible better answer: http://stackoverflow.com/a/53296653
answer count: 2

http://stackoverflow.com/comment/102465765
comment on: http://stackoverflow.com/a/51504929
type: Comment
has text: then reset the style to default. `plt.style.use('default')`
score: 0
type: AnswerComment

http://stackoverflow.com/q/51133829
downvote count: 1
type: Question
has title: How can I add files to GitLab with `python-gitlab`?
has comment: http://stackoverflow.com/comment/89252540
answer count: 2
has comment: http://stackoverflow.com/comment/89256371
has answer: http://stackoverflow.com/a/51135136
has comment: http://stackoverflow.com/comment/89252229
tagged with: database
has body: Using Django, I’d like to sync the files in the database with git repositories on my GitLab instance via python-gitlab. Here you can find my Python code: import gitlab import base64 import os from .models import Meme from django.conf import settings class Sync: def sync () : gl = gitlab.Gitlab('&lt;GitLab URL&gt;', private_token='xxxxxxxxxxxxxx') for meme in Meme.objects.all(): meme_title = meme.meme_title meme_file = str(meme.meme_file) root = settings.MEDIA_ROOT place = os.path.join(root, meme_file) # Create a new project on GitLab. project = gl.projects.create({'name': meme_title }) data = { 'branch': 'master', 'commit_message': 'Automatic commit via sync.py.', 'actions': [ { # Binary files need to be base64 encoded 'action': 'create', 'file_path': place, 'content': base64.b64encode(open(place, "rb").read()), 'encoding': 'base64', } ] } commit = project.commits.create(data) I’m getting the following traceback: Traceback (most recent call last): File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/keno/memeweb/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_excep…
has comment: http://stackoverflow.com/comment/89252664
tagged with: gitlab-api
has comment: http://stackoverflow.com/comment/89252551
favorite count: 0
accepted answer: http://stackoverflow.com/a/51135136
upvote count: 2
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/70051543
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70051543
has comment: http://stackoverflow.com/comment/89254318
score: 1

http://stackoverflow.com/comment/89130638
score: 0
type: Comment
type: QuestionComment
has text: If there was a way of giving a name to a batch of data you could save each batch in a file with that name. Upon restart the program could list these files and deduce the next file name to start. (You would have to be careful to use a temp name first, then rename to the real batch name after closing the temp file).
comment on: http://stackoverflow.com/q/51070285

http://stackoverflow.com/q/51126909
tagged with: python-3.x
type: UnansweredQuestion
has title: python nested conditionals homework
has answer: http://stackoverflow.com/a/51127142
tagged with: if-statement
has answer: http://stackoverflow.com/a/51127323
type: Question
answer count: 2
has body: I am learning conditionals in python and got stuck on one exercise which is very simple but I can't get it right. I am hoping someone can point out what I am doing wrong. I need to write a code that will print either "You may see that movie!" or "You may not see that movie!" based on the criteria below. However, I am not allowed to use and operator anywhere in this code. Any child can see a G-rated movie. To see a PG-rated movie, your child must be 8 or older. To see a PG-13-rated movie, your child must be 13 or older. To see an R-rated movie, your child must be 17 or older. Your child may never see an NC-17 movie. My code: if rating == "G": print("You may see that movie!") elif rating == "PG": if age &gt;= 8: print("You may see that movie!") elif rating == "PG-13": if age &gt;= 13: print("You may see that movie!") elif rating == "R": if age &gt;= 17: print("You may see that movie!") else: print("You may not see that movie!")
score: 0
tagged with: python

http://stackoverflow.com/q/51151226
type: Question
has comment: http://stackoverflow.com/comment/89285910
linked to: http://stackoverflow.com/q/14962485
linked to: http://stackoverflow.com/q/33940483
has comment: http://stackoverflow.com/comment/89285967
has title: Searching through nested dictionaries in python
has body: I'm trying to search through multiple nested dictionaries like this one dict1 = {'x':'y1'} dict2 = {'a':{'x':'y2'}} dict3 = {'a':'b','c':{'d':{'x':'y3'}}} ... So the problem is when I try to look for 'x', the location of 'x' in each dictionary changes. Is there a simple way to find 'x' in every dictionary like .findall('.//tag') when it comes to finding a tag through XML?
score: 0
has comment: http://stackoverflow.com/comment/89285986
has comment: http://stackoverflow.com/comment/89286322
has comment: http://stackoverflow.com/comment/89286965
has comment: http://stackoverflow.com/comment/89286513
has comment: http://stackoverflow.com/comment/89286052
duplicate of: http://stackoverflow.com/q/14962485
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/45230554
tagged with: python-3.x
answer count: 0
linked to: http://stackoverflow.com/q/11929904
has comment: http://stackoverflow.com/comment/89286033
type: UnansweredQuestion

http://stackoverflow.com/comment/89225364
has text: Did you try to downgrade the `oauth2client` package to match the dependency? [Here's](https://stackoverflow.com/questions/5226311/installing-specific-package-versions-with-pip) on how to install specific versions of packages.
comment on: http://stackoverflow.com/q/51119849
score: 0
type: Comment
type: QuestionComment

command-line
tags question: http://stackoverflow.com/q/51071560
tags question: http://stackoverflow.com/q/51138424
type: Tag
tags question: http://stackoverflow.com/q/51068339
tags question: http://stackoverflow.com/q/51102667
tags question: http://stackoverflow.com/q/51116277
tags question: http://stackoverflow.com/q/51037001
tags question: http://stackoverflow.com/q/51068077
tag name: command-line
tags question: http://stackoverflow.com/q/51035629
tags question: http://stackoverflow.com/q/51053515

http://stackoverflow.com/a/51059111
answers question: http://stackoverflow.com/q/51059001
has body: The following lambda expression should work: lambda x: float(x.replace(",","") if not math.isnan(x) else x) Note the mandatory else-part. This assumes that you want the nan's unchanged. See the docs on Conditional Expressions.
accepted answer of: http://stackoverflow.com/q/51059001
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51087158
has title: Installing numpy with pip on windows 10 for python 3.7
has answer: http://stackoverflow.com/a/51091218
upvote count: 14
has answer: http://stackoverflow.com/a/58040293
accepted answer: http://stackoverflow.com/a/51091218
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/135346090
has answer: http://stackoverflow.com/a/51089259
has body: I installed python 3.7 on my Windows 10 laptop since it has been officially released as of today (06/28/2018). Then i tried to install numpy package using pip pip install numpy The install proceeds but finally fails with the below error : source = func(extension, build_dir) File "numpy\core\setup.py", line 675, in get_mathlib_info raise RuntimeError("Broken toolchain: cannot link a simple C program") RuntimeError: Broken toolchain: cannot link a simple C program ---------------------------------------- Command ""c:\program files\python37\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\pcheg\\AppData\\Local\\Temp\\pip-install-7wjkw5wn\\numpy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\pcheg\AppData\Local\Temp\pip-record-uhj8233f\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\pcheg\AppData\Local\Temp\pip-install-7wjkw5wn\numpy\ Any ideas as to how to overcome this install Error? Thanks.
has comment: http://stackoverflow.com/comment/113641816
has answer: http://stackoverflow.com/a/70124155
type: Question
linked to: http://stackoverflow.com/q/64225826
tagged with: numpy
possible better answer: http://stackoverflow.com/a/70124155
favorite count: 0
score: 13
tagged with: python-3.7
tagged with: python
answer count: 4

http://stackoverflow.com/comment/89017771
has text: what is you expected output
comment on: http://stackoverflow.com/q/51012189
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89137492
comment on: http://stackoverflow.com/q/51073982
type: QuestionComment
score: 3
has text: Just use `\d+` this should work, demo: https://regex101.com/r/wza9Ec/1/
type: Comment

http://stackoverflow.com/comment/98562061
has text: hmm have you taken fees into consideration ? Maybe the web interface is using BNB for fees, but perhaps you have to specify that via the api call and that's why you get the error.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51014226

multidimensional-array
tags question: http://stackoverflow.com/q/51038920
tags question: http://stackoverflow.com/q/51072549
tags question: http://stackoverflow.com/q/51012084
tags question: http://stackoverflow.com/q/51087653
tags question: http://stackoverflow.com/q/51029703
type: Tag
tags question: http://stackoverflow.com/q/51143206
tags question: http://stackoverflow.com/q/51023113
tags question: http://stackoverflow.com/q/51024649
tags question: http://stackoverflow.com/q/51140927
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/51144862

http://stackoverflow.com/comment/89163267
type: QuestionComment
comment on: http://stackoverflow.com/q/51087391
score: 1
has text: I guess username is an User object?
type: Comment

http://stackoverflow.com/comment/89291918
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51145606
has text: @T4rk1n, based on your suggestion I removed the reference to plotly_figure and instead include the actual line of code that plotly_figure references and the syntax error no longer appear. Does this provide you with additional clues to why I got the syntax error with by referencing the variable name?
score: 0

http://stackoverflow.com/q/51126353
has answer: http://stackoverflow.com/a/51126436
has title: Django dynamically add field from dictionary value
favorite count: 0
has body: I'm trying to refactor some code to be DRY I have an importer that imports from an API that has keys that are different than the destination. Working code looks like this: this_event = AnEvent() wp_event = Requests.get('someurl').json() if 'title' in wp_event.keys(): this_event.name = wp_event['title'] if 'description' in wp_event.keys(): this_event.description = wp_event['description'] ... and so on What I am trying to do is this: scrape_fields = [ { 'wp' : 'description', 'django' : 'description' }, { 'wp' : 'title', 'django' : 'name' } ... etc ] for field in scrape_fields: if field['wp'] in wp_event.keys(): # I knew this would not work when I wrote it but not sure what to do this_event[field['django']] = wp_event[field['wp']] But Django throws an exception: 'AnEvent' object does not support item assignment Is anyone able to advise on how to assign to a field dynamically like this?
possible better answer: http://stackoverflow.com/a/51126436
has answer: http://stackoverflow.com/a/51126451
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51126451
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89238151
answer count: 2
downvote count: 0

http://stackoverflow.com/q/51051996
tagged with: sockets
has comment: http://stackoverflow.com/comment/89095292
tagged with: python
has title: Python Socket Closes after One Connection/Command
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51052168
type: Question
has comment: http://stackoverflow.com/comment/89095194
tagged with: network-programming
has body: The Client and Server can successfully connect however only one command can be issued. Been at this for a while and wanted some outside help, any feedback or suggested improvements would be great thanks in advance. Been looking at other posts which suggest I may have prematurely closed the connection but I don't believe this to be true due to the fact the program doesn't throw any disconnection errors though I may be wrong. client.py import socket import sys import os # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ##server = input("Enter server IP: ") ##print(server) ## ##port = int(input("Enter port: ")) ##print(port) def send_msg(msg): sock.sendall(msg.encode()) def get_msg(): msg = sock.recv(2048).decode() return msg server = "127.0.0.1" port = 100 sock.connect((server, port)) print("Connecting to " + server + " on port " + str(port) + "\n") while True: #Send data msg = input(os.getcwd() + "&gt; ") print("Sending '" + msg + "'") send_msg(msg) #Response #amnt_exp = len(msg) #data = sock.recv(2048) data = get_msg() if data == "exit": print("\nClosing connection") sock.close() else: print("Received: \n" + data) server.py import socket import sys import os import subprocess #Create a TCP/IP Socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ##server = input("Enter server IP: ") ##print(server) ## ##port = int(input("Enter port: ")) ##print(port) def send_msg(msg): conn.sendall(msg.encode()) def get_msg(): msg = conn.recv(2048).decode() return msg server = "127.0.0.1" port = 100 #Config sock.bind((server, port)) print("Bound to " + server + " on port " + str(port) + "\n") sock.listen(1) print("Waiting for a connection...") while True: conn, caddr = sock.accept() print("Connected!\n") print("Waiting for a command...") #data = conn.recv(2048).decode() data = get_msg() #Exit if data == "exit": print("\nConnection closed") conn.close() print("Received '" + data + "'") #Command Exec call = subprocess.Popen(data, stdout = subp…
has comment: http://stackoverflow.com/comment/89095241
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89095309

http://stackoverflow.com/q/51105876
has answer: http://stackoverflow.com/a/79221498
score: 2
has body: Does Python has a Package to solve sequence which are defined using recurrence relation? For example "Maxima" can solve a recurrence relation directly using the package "solve_rec". Is something similar available for Python? Maxima Code: kill(all); load("solve_rec")$ a[n]-a[n-1]-a[n-2]=0; solve_rec(%, a[n],a[1]=2,a[2]=3); Output: a[n]-a[n-1]-a[n-2]=0 a[n]=((sqrt(5)+1)^n*(3*sqrt(5)+5)*2^(-n-1))/5-((sqrt(5)-1)^n*(3*sqrt(5)-5)*2^(-n-1)*(-1)^n)/5
downvote count: 0
type: UnansweredQuestion
has title: Does Python have a Package to solve sequence which are defined using recurrence relation?
type: Question
has answer: http://stackoverflow.com/a/51108601
favorite count: 0
upvote count: 2
tagged with: package
answer count: 2
tagged with: recurrence
tagged with: python

http://stackoverflow.com/q/51016896
type: UnansweredQuestion
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/51017085
has answer: http://stackoverflow.com/a/51026753
has answer: http://stackoverflow.com/a/51017434
tagged with: django-models
has comment: http://stackoverflow.com/comment/89027071
upvote count: 4
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89027010
tagged with: django-rest-framework
score: 4
has title: How to serialize Inherited models in Django REST Framework
favorite count: 0
tagged with: rest
has body: I'm working on a Django Rest Framework project, in which I have created the following models as: from django.db import models # Base Models... choices = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class UserAccountModel(models.Model): deployment_name = models.CharField(max_length=150, blank=True) credentials = models.FileField(upload_to='media/credentials/', name='credentials'), project_name = models.CharField(max_length=150, blank=True) project_id = models.CharField(max_length=100, blank=False, name='project_id') cluster_name = models.CharField(max_length=150, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=100, choices=choices) def __str__(self): return self.deployment_name class AwdModel(UserAccountModel): source_zip = models.FileField(upload_to='media/awdSource/', name='awd_source') routing = models.TextField(name='routing', null=True) def __str__(self): return self.deployment_name def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) # def clean(self): # if self.services == 'Multiple' and self.routing is None: # raise ValidationError('You must have to provide routing for multiple services deployment.') class AwodModel(UserAccountModel): source_zip = models.FileField(upload_to='media/awodSource/', name='awod_source') routing = models.TextField({'type': 'textarea'}, name='routing') def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) I need to serialize these models, Here's how I have implemented serializers for these models: from rest_framework import serializers from .models import UserAccountModel, AwdModel, AwodModel class UserAccountSerializer(serializers.ModelSerializer): class M…
tagged with: python
has comment: http://stackoverflow.com/comment/89027108

http://stackoverflow.com/comment/89231154
type: QuestionComment
comment on: http://stackoverflow.com/q/51123027
score: 1
has text: Please read the [minimal, complete and verifiable example page](https://stackoverflow.com/help/mcve). Try to remove everything that's not relevant for the current problem, but the program should still be runnable.
type: Comment

http://stackoverflow.com/q/51155556
type: Question
has comment: http://stackoverflow.com/comment/89306982
tagged with: postgresql
score: 0
has body: I want to add some data to database using python, but I have a problem. The data to one table is successfully inserted but the problem is with the other table. There are two tables vehicles and vehicle_price as follows: My code is as follows: def insert_vehicles_to_db(vehicle): conn = db_connection() cur = conn.cursor() if vehicle_not_exists(vehicle, conn, cur): try: insert_vehicle(vehicle, conn, cur) insert_vehicle_price(vehicle, conn, cur) except Exception as e: pass conn.close() Function insert_vehicle is as follows: def insert_vehicle(vehicle, conn, cur): try: query = "INSERT INTO vehicles (reference, data, price, reference_url, timestamp) VALUES (%s, %s, %s, %s, %s);" cur.execute(query, (vehicle['reference'], "", vehicle['price'], vehicle['reference_url'], datetime.datetime.now())) conn.commit() except Exception as e: pass That works fine, the vehicles are always inserted. But the problem is in the next one, in insert_vehicle_price which looks as follows: def insert_vehicle_price(vehicle, conn, cur): try: vehicle_data = get_vehicles(vehicle['reference'], vehicle['reference_url'], conn, cur)[0] # get the last vehicle vehicle_id = vehicle_data[0] vehicle_price = Decimal(vehicle['price'] + ".00") query = "INSERT INTO vehicle_price (price, timestamp, vehicle_id) VALUES (%s, %s, %s);" cur.execute(query, (vehicle_price, datetime.datetime.now(), vehicle_id)) conn.commit() except Exception as e: pass Thus for some reason the prices aren't inserted. Any idea why? UPDATE The function get_vehicles looks as follows: def get_vehicles(reference, reference_url, conn, cur): try: sql_get_vehicles = "SELECT * FROM vehicles WHERE reference = %s and reference_url = %s" cur.execute(sql_get_vehicles, (reference, reference_url)) return cur.fetchall() except Exception as e: # TODO Handle error pdb.set_trace() pass
has comment: http://stackoverflow.com/comment/89294532
has comment: http://stackoverflow.com/comment/89307046
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89317579
tagged with: python
has comment: http://stackoverflow.com/comment/89317440
tagged with: mysql
has comment: http://stackoverflow.com/comment/89294623
has title: Data isn't inserted to database - python

http://stackoverflow.com/comment/89121662
type: Comment
has text: I pasted in an Excel snapshot. Thank you so much for working with me on this.
comment on: http://stackoverflow.com/a/51064548
score: 0
type: AnswerComment

http://stackoverflow.com/q/51019134
type: Question
has title: How to plot audio waveform in PyQtGraph
accepted answer: http://stackoverflow.com/a/51032990
answer count: 1
favorite count: 0
has body: I am working on my thesis project that needs to manipulate audio waveform. And I am really having a trouble plotting my audio waveform with PyQtGraph and could not find any solution. I have tried plotting it with matplotlib and works really fine. Here is a code by plotting with matplotlib embedded on a tkinter window (Won't post the complete code for tkinter canvas embedding because I don't think it's not the focus of my problem): def waveform(self, audio): self.waveFile = wave.open(audio, 'rb') # reading wave file format = p.get_format_from_width(self.waveFile.getsampwidth()) channel = self.waveFile.getnchannels() rate = self.waveFile.getframerate() self.frame = self.waveFile.getnframes() self.stream = p.open(format=format, # DATA needed for streaming channels=channel, rate=rate, output=True) durationF = self.frame / float(rate) plt.title('Audio Waveform') self.data_int = self.waveFile.readframes(self.frame) self.data_plot = np.fromstring(self.data_int, dtype=np.short) self.data_plot.shape = -1, 2 self.data_plot = self.data_plot.T self.time = np.arange(0, self.frame) * (1.0 / rate) self.fig = Figure(figsize=(30, 6), dpi=30) self.fig.set_size_inches(34, 5.3) self.fig.subplots_adjust(left=0.05, bottom=0.09, right=1.05, top=1.00, wspace=0, hspace=0) self.fig.tight_layout() self.xticks = np.arange(0, self.timeDuration, 15) self.wavePlot = self.fig.add_subplot(111) self.wavePlot.set_xticks(self.xticks) if (channel == 1): print 'Just mono files only' self.wavePlot.plot(self.time, self.data_plot[0]) elif (channel == 2): print 'Just stereo files only' self.wavePlot.plot(self.time, self.data_plot[1], c="b") self.wavePlot.tick_params(axis='both', which="major", labelsize=20) self.wavePlot.tick_params(axis='both', which="minor", labelsize=30) self.canvas = FigureCanvasTkAgg(self.fig, self.waveFrame) self.canvas.get_tk_widget().grid(row=0, column=0, sticky="nsew") And when I discovered PyQtGraph, I switched to it for more interactive and fast plotting. Now when I do this with …
upvote count: 2
tagged with: python
tagged with: pyqtgraph
downvote count: 1
tagged with: plot
tagged with: audio
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51032990
score: 1
tagged with: matplotlib

http://stackoverflow.com/comment/89056303
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51030324
has text: i tried that, but im still getting an error " conda create -n tf100 tensorflow=1.0.0 Fetching package metadata ............. PackageNotFoundError: Packages missing in current channels: - tensorflow 1.0.0* We have searched for the packages in the following channels: - https://repo.continuum.io/pkgs/main/win-64 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/win-64 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/win-64 - https://repo.continuum.io/pkgs/r/noarch"

http://stackoverflow.com/q/51052416
score: 1
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51052516
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
has title: Pandas dataframe groupby into list, with list in cell data
tagged with: python
has body: Consider this input df my_input_df = pd.DataFrame({ 'export_services': [[1],[2,4,5],[4,6], [2,4,5],[1]], 'seaport':['china','africa','europe', 'mexico','europe'], 'price_of_fish':['100','200','250','125','75']}) How to group on a column which contains lists and combine the other columns into a list? my_output_df = pd.DataFrame({ 'export_services': [[1],[2,4,5],[4,6]], 'seaport':[['china','europe'],['africa','mexico'],'europe'], 'price_of_fish':[['100','75'],'200',['250','125']]}) I have tried with my_input_df.groupby('export_services').apply(list) which gives TypeError: unhashable type: 'list' Any ideas? Notes: It's OK if all the grouped rows in my_output_df are lists, even for a single entry.
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51052516

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/51068964
tags question: http://stackoverflow.com/q/51160000
tags question: http://stackoverflow.com/q/51153543
tag name: azure-iot-hub

http://stackoverflow.com/comment/89200051
comment on: http://stackoverflow.com/a/51092256
score: 0
type: AnswerComment
has text: I found a new problem. when using GRAY, the match degree is 0.9, and when use BGR, the match is only 0.4. This means that when using GRAY, the grayscale will make the error a lot more. ...@WhoIsJack
type: Comment

http://stackoverflow.com/comment/89256642
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51135799
has text: @Sayse like this? album_id = models.ForeignKey(Album, on_delete=models.CASCADE, default='') then, how to count the purchase number?

http://stackoverflow.com/q/51135309
tagged with: dataframe
tagged with: export
score: 0
tagged with: pandas
has title: Python extract and append data into data frame
tagged with: python
has comment: http://stackoverflow.com/comment/89256394
has comment: http://stackoverflow.com/comment/89256471
answer count: 0
type: UnansweredQuestion
has body: I've scraped the website for my research but I couldn't find the right way to extract it into data frame. I believe that my problem is related with list objects that are between lines 36 and 38. The print line has worked very nice that I can see the final version of data frame in the Python console. The solution can be really easy but I couldn't figure it out. Thanks in advance for all help. from time import sleep from bs4 import BeautifulSoup, SoupStrainer import requests import pandas as pd # Insert the hisghest page number for website highest_number = 12 def total_page_number(url): all_webpage_links = [] all_webpage_links.insert(0, url) pages = [str(each_number) for each_number in range(2, highest_number)] for page in pages: link = ''.join(url + '&amp;page=' + page) all_webpage_links.append(link) return all_webpage_links # Use total_page_number function to create page list for website All_page = total_page_number( 'https://www.imdb.com/search/title?countries=tr&amp;languages=tr&amp;locations=Turkey&amp;count=250&amp;view=simple') def clean_text(text): """ Removes white-spaces before, after, and between characters :param text: the string to remove clean :return: a "cleaned" string with no more than one white space between characters """ return ' '.join(text.split()) # Create list objects for data # Problem occurs in this line !!!!!! actor_names = [] titles = [] dates = [] def get_cast_from_link(movie_link): """ Go to the IMDb Movie page in link, and find the cast overview list. Prints tab-separated movie_title, actor_name, and character_played to stdout as a result. Nothing returned :param movie_link: string of the link to IMDb movie page (http://imdb.com ...) :return: void """ movie_page = requests.get(movie_link) # Use SoupStrainer to strain the cast_list table from the movie_page # This can save some time in bigger scraping projects cast_strainer = SoupStrainer('table', class_='cast_list') movie_soup = BeautifulSoup(movie_page.content, 'html.parser', parse_only…
tagged with: loops
type: Question

http://stackoverflow.com/a/51161725
answers question: http://stackoverflow.com/q/51161676
accepted answer of: http://stackoverflow.com/q/51161676
has body: You can verify if the file exists with an if statement then run the other two functions. You will have to update check_file() to return True or False def check_file(): file_exists = False for deploy_file in os.listdir("C:\\test1\\test.txt"): if deploy_file.startswith("test"): file_exists = True else: file_exists = False return file_exists Then you can use this as your main function def main(): if check_file(): copy_file() run_script() else: exit(1)
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51051176
answer count: 0
tagged with: out-of-memory
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: tensorflow
type: Question
has body: When Running a model trained for object detection I'm running out of memory when calling tf.run() 2018-06-26 18:32:16.914049: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.55GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:17.393037: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.31GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:23.825495: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.31GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:24.659582: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 3.11GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:29.902840: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.20GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:30.955526: W tensorflow/core/common_runtime/bfc_allocator.cc:219] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.29GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available. 2018-06-26 18:32:37.434223: W tensorflow/core/framework/op_kernel.cc:1328] OP_REQUIRES failed at where_op.cc:286 : Internal: WhereOp: Could not launch cub::DeviceReduce::Sum to count number of true / nonzero in…
tagged with: nvidia-jetson
downvote count: 0
has title: Tensorflow model uses entire memory and OOMs system
has comment: http://stackoverflow.com/comment/89093511
has comment: http://stackoverflow.com/comment/89094555
favorite count: 0
tagged with: memory-management

http://stackoverflow.com/a/56358371
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51084663
has body: you should use scale in first update counter += 1 if counter == 1: ImageItem = pg.ImageItem() ImageItem.scale((data_storage.x[-1] - data_storage.x[0]) / len(data_storage.x), 1)

http://stackoverflow.com/comment/89029547
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51018027
type: AnswerComment
has text: So from what you're saying, `link_list` returns 600 links, and then `GetData()` processes each in turn?

http://stackoverflow.com/comment/89205051
comment on: http://stackoverflow.com/q/51108880
has text: @Fallenreaper Process substitution captures both output to stdout and stderr, see for example `diff <(echo blah >&2) <(echo blahx)`, so I don't think that's the problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51055979
accepted answer of: http://stackoverflow.com/q/51055788
has body: I believe need: m1 = Internaldf['Status']=='deny' m2 = Internaldf['SrcIP']!="NA" #if want check non NaNs #m2 = Internaldf['SrcIP'].notnull() m3 = Internaldf['DstIP']!="NA" #if want check non NaNs #m3 = Internaldf['DstIP'].notnull() m4 = Internaldf['TimeStamp']-Internaldf['TimeStamp'].iloc[0] &lt; pd.Timedelta(minutes=30) #chain condition with &amp; for AND or by | for OR, for column use reset_index df=Internaldf[m1 &amp; m2 &amp; m3 &amp; m4].groupby(['DstPort','SrcIP']).size().reset_index(name='Count') Internaldfdeny=df.pivot_table('Count','DstPort','SrcIP').fillna(0).to_sparse(fill_value=0) print (Internaldfdeny) SrcIP 10.208.2.56 10.208.2.70 10.208.23.136 DstPort 137 0.0 1.0 0.0 8081 1.0 0.0 0.0 8888 0.0 0.0 1.0
type: Answer
has comment: http://stackoverflow.com/comment/89102500
answers question: http://stackoverflow.com/q/51055788
has comment: http://stackoverflow.com/comment/89104725
score: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89102475
downvote count: 1
has comment: http://stackoverflow.com/comment/89103101
has comment: http://stackoverflow.com/comment/89102777
has comment: http://stackoverflow.com/comment/89102914

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

http://stackoverflow.com/comment/89269737
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51139203
has text: Sorry, I added the needed line to the JS. You need to change the onclick attribute as well, and point it to a second JS function like unfollow_ajax which points to the unfollow flask route and reverses the text and onclick attribute changes.
type: AnswerComment

http://stackoverflow.com/comment/89071139
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51038212
has text: check this: df['End of Month Part 1']= df.groupby(by=['SKU']).filter(lambda x: (x['SKU'] == x['SKU']).any()).iloc[0]['Inventory']- df['Sales'] - df['Incoming'], I have done one column..
score: 0

http://stackoverflow.com/comment/89305207
comment on: http://stackoverflow.com/a/51156909
type: AnswerComment
score: 0
type: Comment
has text: Looks like you found your answer (looking at the answer you added below). Python can get weird when you install multiple instances of it. Have you tried using Anaconda (if you're looking at getting different versions of python)? Best of luck with learning Python, it's pretty fun to pick up.

http://stackoverflow.com/q/51144766
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89274684
downvote count: 0
has answer: http://stackoverflow.com/a/51161986
favorite count: 0
tagged with: python
has title: Proper usage of list_ssheets() with a parent_id in pygsheets
tagged with: pygsheets
has body: I've been trying to get a handle on how to use list_ssheets() with a parent_id filter. The following works well, and returns a list of all the sheets (including the ones I'm trying to isolate from a folder): the_list_of_sheets = gc.list_ssheets() list_ssheets() on its own works well and returns all of the sheets, but the follow returns an empty list (the xxxx being the containing folder id): the_list_of_sheets = gc.list_ssheets('xxxxxxxxxxxxxxxxxxxxxxxxxxx') I've tried a number of different ways to get this to work, but can't seem to hit the right syntax. What is the proper way to use list_ssheets() with a parent_id to return all sheets in a particular directory? Thanks!
upvote count: 1
tagged with: google-sheets-api
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51161986

http://stackoverflow.com/q/51160343
tagged with: tensorflow
tagged with: audio
has comment: http://stackoverflow.com/comment/89335783
tagged with: signal-processing
type: Question
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/51180457
has body: Trying to implement a paper and running into some brick-walls due to some dimensionality problems. My input is mono audio data where 128 frames of 50ms of 16kHz sampled audio is fed into the network. So my input shape is: [128,0.005*16000, 1] Here's the layer details - 1.) conv-bank block : Conv1d-bank-8, LeReLU, IN (instance normalization) I achieve this using : bank_width = 8 conv_bank_outputs = tf.concat([ tf.layers.conv1d(input,1,k,activation=tf.nn.leaky_relu,padding="same") for k in range(1, bank_width + 1)], axes = -1) 2.) conv-block: C-512-5, LReLu --> C-512-5,stride=2, LReLu, IN, RES (Residual) This is where I get stuck, the shapes of the output of second convolution and input to the (2) layer is mismatched. I can't get my head around it. I achieve this using: block_1 = tf.layers.conv1d(input,filters=512,kernel_size=5,activation=tf.nn.leaky_relu,padding="same") block_2 = tf.layers.conv1d(block_1,filters=512,kernel_size=5,strides=2,activation=tf.nn.leaky_relu,padding="same") IN = tf.contrib.layers.instance_norm(block_2) RES = IN + input Error: ValueError: Dimensions must be equal, but are 400 and 800 for 'add' (op: 'Add') with input shapes: [128,400,512], [128,800,1024].
tagged with: python
has title: Conv1D confusion in Tensorflow
type: UnansweredQuestion
score: 0

http://stackoverflow.com/q/51141745
type: Question
tagged with: flask
has answer: http://stackoverflow.com/a/71410307
tagged with: docker
has body: I've been trying to solve this issue for quite some time, and I'm pretty sure it's just a really stupid mistake but I'm really giving up on life. Background: I have a Flask python app providing RESTful services. This app is running inside a docker container. some GET functions return Json responses and they're simple and work fine. some, however, are a bit more complex. There's a file inside the docker container called "generated" what get_files does here is it compresses it in a Zip file, then downloads the generated zip file. from flask import Flask, render_template, request, jsonify, redirect, url_for, send_from_directory import zipfile app = Flask(__name__) #app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER #gets all elements @app.route('/elementsdb/ecu',methods=['GET']) def getAllElements(): return jsonify({'ecus':elementsDB}) #-------------------------------------------# #Get files @app.route('/get_files', methods=['GET']) def download(): zf = zipfile.ZipFile('gen.zip', mode = 'w') zf.write('generated/one.c') zf.write('generated/two.c') zf.write('generated/three.c') zf.write('generated/four.h') zf.close() return send_from_directory("/Users/abeer/downloads/testD", "gen.zip", as_attachment=True) Issue: /get_files works fine when running independently on localhost. http://localhost:5000/get_files but because the app is in a docker container, it downloads the file inside the docker image. When I try to access the file via postman or curl, I get a 404 error I've also tried to change the path to download the file outside the image but that doesn't work either. It's probably a publish/expose port thing in Docker but I'm so clueless in that matter. This is my dockerfile: FROM python:2.7 ADD . /todo WORKDIR /todo RUN pip install -r requirements.txt my docker-compose.yml web: build: . command: python -u flaskdb.py ports: - "5000:5000" volumes: - .:/todo links: - db db: image: mongo:3.0.2
upvote count: 3
answer count: 1
type: UnansweredQuestion
has title: can't access/download a generated folder that is inside a Docker container using REST API calls
tagged with: python
tagged with: dockerfile
score: 3
tagged with: docker-compose
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51043974
has comment: http://stackoverflow.com/comment/89082751
tagged with: django-models
has title: TypeError: create_superuser() missing 1 required positional argument: 'name'
has comment: http://stackoverflow.com/comment/89080506
type: Question
has body: i get the following error even after adding name to my create_superuser function in my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class UserProfileManager(BaseUserManager): def create_user(self,email,name,password=None): if not email: raise ValueError("email is required") email=self.normalize_email(email) user=self.model(email=email,name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): """creates new super user with details """ user=self.create_user(email,name,password) user.is_superuser=True user.is_staff=True user.save(using=self._db) return user class UserProfiles(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True) name=models.CharField(max_length=255) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) objects=UserProfileManager() USERNAME_FIELD='email' REQUIRED_FIELD=['name'] def get_fullname(self): return self.name def get_shortname(self): return self.name def __str__ (self): return self.email and i get the following kind of error when i tried to run python manage.py createsuperuser command TypeError: create_superuser() missing 1 required positional argument: 'name' i dont know where i my mistake is ? any kind of help is appreciated thanks in advance
has comment: http://stackoverflow.com/comment/89081755
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/89080722
score: 0
has comment: http://stackoverflow.com/comment/89079010
has comment: http://stackoverflow.com/comment/89083520
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89079190
has comment: http://stackoverflow.com/comment/89083689
tagged with: django
has comment: http://stackoverflow.com/comment/89079974
tagged with: python

http://stackoverflow.com/q/51037886
tagged with: python
has answer: http://stackoverflow.com/a/54124524
upvote count: 6
tagged with: c++
has title: Trouble with linking boost::python::numpy
tagged with: boost
tagged with: numpy
answer count: 4
has answer: http://stackoverflow.com/a/51038150
score: 6
possible better answer: http://stackoverflow.com/a/53963135
accepted answer: http://stackoverflow.com/a/51038150
has answer: http://stackoverflow.com/a/53963135
type: AnsweredQuestion
downvote count: 0
has body: I wrote a small example to show what's going on. my_test.cpp #include &lt;iostream&gt; #include &lt;boost/python/numpy.hpp&gt; namespace np = boost::python::numpy; int my_Foo() { Py_Initialize(); np::initialize(); std::cout &lt;&lt; "hello\n"; return 0; } BOOST_PYTHON_MODULE(my_test) { using namespace boost::python; def("my_Foo", my_Foo); } py_test.py import my_test as t t.my_Foo(); I compile all with command : g++ -shared -fPIC -o my_test.so my_test.cpp -lboost_python -lpython2.7 -I/usr/include/python2.7 And I get this error : ImportError: /home/my_test.so: undefined symbol: _ZN5boost6python5numpy10initializeEb And it works when I comment this line //np::initialize(); I have no idea how to fix it. I have read similar questions on the forum, but none of the solutions helped me. I tried update boost, update python, link libraries, put generated module before other module during compilation - nothing helps. I will be grateful for any help.
favorite count: 0
tagged with: undefined-symbol
type: Question
has answer: http://stackoverflow.com/a/58818286

http://stackoverflow.com/a/51050645
type: Answer
has comment: http://stackoverflow.com/comment/89093490
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51050569
downvote count: 0
has body: You need to save some representation of the game's current state. This can be any format you want -- if you have a game state object, you can serialize and save it using the pickle module, described here. If you have something simple that you could describe in a text file, e.g. something that reads like score = 300 level = 10 lives = 2 then you could just save it in a text file when the user exits, and then load it when they start again.
has comment: http://stackoverflow.com/comment/89093350
has comment: http://stackoverflow.com/comment/89094941
has comment: http://stackoverflow.com/comment/89094564

http://stackoverflow.com/a/54104873
has body: To be honest, I was struggling on this issue for a long time... Luckily I found the panacea expected finally. For anyone who would like to make the minimal changes on their original codes with Sequential, here comes the solution: def linear_model_combined(optimizer='Adadelta'): from keras.models import Model, Sequential from keras.layers.core import Dense, Flatten, Activation, Dropout from keras.layers import add modela = Sequential() modela.add(Flatten(input_shape=(100, 34))) modela.add(Dense(1024)) modela.add(Activation('relu')) modela.add(Dense(512)) modelb = Sequential() modelb.add(Flatten(input_shape=(100, 34))) modelb.add(Dense(1024)) modelb.add(Activation('relu')) modelb.add(Dense(512)) merged_output = add([modela.output, modelb.output]) model_combined = Sequential() model_combined.add(Activation('relu')) model_combined.add(Dense(256)) model_combined.add(Activation('relu')) model_combined.add(Dense(4)) model_combined.add(Activation('softmax')) final_model = Model([modela.input, modelb.input], model_combined(merged_output)) final_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return final_model For more information, refer to https://github.com/keras-team/keras/issues/3921#issuecomment-335457553 for farizrahman4u's comment. ;)
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51075666
type: Answer
score: 2

http://stackoverflow.com/a/51211163
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51104671
type: Answer
answers question: http://stackoverflow.com/q/51104671
score: 0
has body: I wouldn't bother with it. Maybe it misses the _all argument. Try to simply bind canvas.move() function to a canvas.bind_all()

http://stackoverflow.com/a/51047999
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51047954
answers question: http://stackoverflow.com/q/51047954
has body: repeating_value = "k" #Assign the value which do you want to be repeated total_times=5 #how many times do you want expected_list=[repeating_value*i for i in range(1,total_times+1)] print(expected_list)
type: AcceptedAnswer

http://stackoverflow.com/a/51155038
has body: I dropped all of my database tables, and issued the python manage.py makemigrations and python manage.py migrate and my problem got fixed. I don't know what precisely caused the problem.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51153111
answers question: http://stackoverflow.com/q/51153111

http://stackoverflow.com/a/70925085
downvote count: 1
has comment: http://stackoverflow.com/comment/129132910
score: 1
answers question: http://stackoverflow.com/q/51062920
has body: I had look a like problem, on MacOs Catalina, solved with this: ARCHFLAGS="-arch x86_64" pip3 install mysqlclient
type: Answer
upvote count: 2

http://stackoverflow.com/comment/89222800
has text: sorry I missed that. Now it works in a file. 3 problems in csv. 1) the output is in comma separated option, can it be in "TAB" separated while writing in file?? 2) The output header has quote sign in strings`"C(1,1)"` how to remove that. 3) The order in the file it saves in the column is alphabetical. if I want to save the way I put in the target(if you see the question). The output in csv in the text editor is: `freq,"C(1,1)","C(1,2)","C(2,1)","C(2,2)","G(1,1)","G(1,2)","G(2,1)","G(2,2)","L(1,1)","L(1,2)","L(2,1)","L(2,2)","R(1,1)","R(1,2)","R(2,1)","R(2,2)"`
comment on: http://stackoverflow.com/a/51116992
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51014386
has comment: http://stackoverflow.com/comment/89021652
score: 0
has comment: http://stackoverflow.com/comment/89021907
has comment: http://stackoverflow.com/comment/89021858
has comment: http://stackoverflow.com/comment/89021501
tagged with: pip
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89021680
has comment: http://stackoverflow.com/comment/89021631
has comment: http://stackoverflow.com/comment/89021744
has title: Python pip is messed up
has comment: http://stackoverflow.com/comment/89021675
has comment: http://stackoverflow.com/comment/89021820
has comment: http://stackoverflow.com/comment/89021670
has comment: http://stackoverflow.com/comment/89021625
answer count: 0
has comment: http://stackoverflow.com/comment/89021671
has comment: http://stackoverflow.com/comment/89021493
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89021753
favorite count: 0
has comment: http://stackoverflow.com/comment/89021752
has body: I'm trying to run uninstall flask 0.9.1 to install 0.9.0 instead because i get the error ascii_attachments = current_app.extensions['mail'].ascii_attachments KeyError: 'mail' and i read from this post= 'Python Flask Email KeyError KeyError: 'mail'' that this was the solution Error: The file/path provided (routes) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py so I checked pip and I got this error: bash: usr/local/bin/pip: No such file or directory I thought it might be due to the cash, so I typed: hash -r however, the same problem occurs afterward. Any ideas on what I can do? EDIT: whenver i type: $ which pip i get this directory back: /usr/local/bin/pip
has comment: http://stackoverflow.com/comment/89021698
type: Question
has comment: http://stackoverflow.com/comment/89021502
tagged with: python
has comment: http://stackoverflow.com/comment/89021720
linked to: http://stackoverflow.com/q/28466384

http://stackoverflow.com/a/51063833
downvote count: 0
answers question: http://stackoverflow.com/q/51063378
type: Answer
has comment: http://stackoverflow.com/comment/89118218
score: 5
upvote count: 5
has body: Given that you use os.fdopen after you call mkstemp(), you may be better off using tempfile.NamedTemporaryFile(delete=False). It returns a Python file object instead of an fd. Either way, the returned file will have mode=0600, so you will need to change it. Use os.fchmod(temp_file.fileno(), 0640) or similar (change the mode as per your needs).
accepted answer of: http://stackoverflow.com/q/51063378
type: AcceptedAnswer

http://stackoverflow.com/comment/89229458
type: QuestionComment
type: Comment
has text: that was just an assumption. as I am getting an interval, derived from the outputs of two distinct models, one would suggest that the two models should have any connection (e.g. the same set of parameters). In option two, I will have two completely different models(trained on the same data though). Does that still make sense to combine the outputs in order to derive an interval?
comment on: http://stackoverflow.com/q/51100483
score: 0

http://stackoverflow.com/comment/89312808
type: Comment
has text: This seems like a data issue. Can you put data in questiob that duplicates this error?
comment on: http://stackoverflow.com/a/51145398
score: 0
type: AnswerComment

http://stackoverflow.com/a/51114940
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89218921
upvote count: 2
answers question: http://stackoverflow.com/q/51114445
has body: This can be solved quite easily in NumPy: import numpy as np import skimage grid = [[1,3,2,5,4,6,9,8,7], [4,6,5,8,7,9,3,2,1], [7,9,8,2,1,3,6,5,4], [9,2,1,4,3,5,8,7,6], [3,5,4,7,6,8,2,1,9], [6,8,7,1,9,2,5,4,3], [5,7,6,9,8,1,4,3,2], [2,4,3,6,5,7,1,9,8], [8,1,9,3,2,4,7,6,5]] # Create NumPy array grid = np.array(grid) # Cut into 3x3 sublocks, and flatten each subblock subgrids = skimage.util.view_as_blocks(grid, (3, 3)).reshape(3, 3, -1) # Sort each subblock then compare each one with [1, 2, ..., 9]. If all are equal, it is a valid subblock valid_blocks = np.all(np.sort(subgrids, axis=-1) == np.arange(1, 10), axis=-1) # array([[ True, True, True], # [ True, True, True], # [ True, True, True]]) # Sort rows, then compare each one valid_rows = np.all(np.sort(grid, axis=1) == np.arange(1, 10), axis=1) # array([ True, True, True, True, True, True, True, True, True]) # Sort columns, then compare each one valid_columns = np.all(np.sort(grid, axis=0) == np.arange(1, 10)[:, None], axis=0) # array([ True, True, True, True, True, True, True, True, True]) # Check if all comparisons were all true all_valid = np.all(valid_blocks) &amp; np.all(valid_rows) &amp; np.all(valid_columns) # True
type: Answer
has comment: http://stackoverflow.com/comment/89217816

http://stackoverflow.com/comment/89255967
type: QuestionComment
has text: Voted to close because there's no way this can be answered (because there's too much missing information) and it's not generally useful ("how do I install Python modules on my macOS computer" does not generalize). A different SO site might help, perhaps superuser.
type: Comment
comment on: http://stackoverflow.com/q/51129713
score: 0

http://stackoverflow.com/q/51164980
score: 1
upvote count: 1
type: Question
tagged with: ctypes
has title: Ctypes pass float into function returns random numbers
tagged with: http://stackoverflow.com/tag/c
tagged with: python-2.7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51165271
favorite count: 0
tagged with: typeerror
accepted answer: http://stackoverflow.com/a/51165271
tagged with: python
has body: To give some background, I am using linux and I have a C code as follows: int c_func(const char* dir, float a, float b, float c, float d ) { printf("%s\n", dir); printf("%f\n",a); printf("%f\n",b); printf("%f\n",c); printf("%f\n",d); return 0; } This is a simple function that takes in a string and 4 floats as arguments and prints them out as I am trying to test my phython/C interface. My python code is as follows: calling_function = ctypes.CDLL("/home/ruven/Documents/Sonar/C interface/Interface.so") calling_function.c_func.argtypes = [ctypes.c_char_p, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float] calling_function.c_func.restype = ctypes.c_float for _fv in _testFV: _predOut = calling_function.c_func("hello",_fv[0], _fv[1], _fv[2], _fv[3]) exit(1) To clarify, _fv[0], _fv[1], _fv[2], _fv[3] are [1.969591, 112.7779, 1.8701470000000002, 111.7575] respectively. And _testFV is a list of 117 other lists. I am just looking to extract the first list from _testFV. After running this code, I am able to correctly print the string but the floats seem to be large random numbers (1849375168, 3, 4805786, 9397952) instead of the actual values of _fv[0], _fv[1], _fv[2], _fv[3]. So to check if I am passing the right values into the calling_function.c_func function,I included a print statement to print the value of _fv[0], _fv[1], _fv[2], _fv[3] and their types. I checked and the values are floats and the correct numbers are being inputted into the function but random numbers are being printed out. I thought that I might have declared restype wrongly, but I thought that restype should be declared as int as the C code returns 0. Question 1: Why does the function print out random numbers instead of the floats that I input into the function. Question 2: The function is supposed to print out 1 string and 4 floats so am I supposed to declare restype as 1 string and 4 floats? Things I have tried: Changing all the float variables to doubles. Changing restype to int and double…
type: AnsweredQuestion

http://stackoverflow.com/comment/89090439
type: QuestionComment
comment on: http://stackoverflow.com/q/51049603
has text: And what do you want to happen when it you're at the range 1605-1615? Do you want it to either stay there or increase since a decrease would take it out of bounds?
score: 0
type: Comment

http://stackoverflow.com/a/51161398
has comment: http://stackoverflow.com/comment/126384032
type: Answer
accepted answer of: http://stackoverflow.com/q/51157813
upvote count: 0
answers question: http://stackoverflow.com/q/51157813
score: -2
downvote count: 2
has body: import os import pandas as pd files = os.path.listdir('./') train = pd.DataFrame() test = pd.DataFrame() for file in files: df = pd.read_csv(file, sep=",",names=['voltage','current']) if i &lt; 900: train.append(df) else: test.append(df)
type: AcceptedAnswer

http://stackoverflow.com/comment/89098345
type: QuestionComment
comment on: http://stackoverflow.com/q/51050569
has text: Possible duplicate of [how to make save / load game functions in pygame?](https://stackoverflow.com/questions/6420311/how-to-make-save-load-game-functions-in-pygame)
score: 0
type: Comment

http://stackoverflow.com/comment/89052928
has text: Note that the coefficient associated with the last entry will always be the last element in your list. Use that to develop your logic.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51029979
type: AnswerComment

http://stackoverflow.com/q/51145527
upvote count: 5
type: UnansweredQuestion
has body: I'm doing an image segmentation with UNet-like CNN architecture by Pytorch 0.4.0.It mark foreground as 1 and background as 0 in the final segmentation result.I use a pre-trained VGG's feature extractor as my encoder, so I need to upsampling the encoder output many times.But the result shows a weird lattice parttern in the result like this: I suspect these different shape of black parttern were caused by the deconvolutional layers.It's said that deconv layer add (s-1) zeros between the input pixel in the official documentation.the deconvolutional layer's hyperparameter are listed below: kernel_size=3,stride=2,padding=1,output_padding=1 (the output_padding is used to fit the skip connection feature size, for instance, with a input size 40*30,I want it size enlarge twice in one deconvolutional layer,under my calculation with the formula:out=s(in-1)+k-2p,I must use padding 1 and output-padding 1 to keep size,or there might be other better choice I don’t know.) I'm wondering the reason that generate the black lattice.They looks like a grid or square parttern.And how to solve it.Besides,I need to adjust all deconv layer hyperparamater to one uniform or modify them separately? environment:Ubuntu 16.04,Pytorch 0.4.0,GTX 1080Ti, the architecture of upsampling is three deconv layer,they are one after another. Update after I modified the deconv hyperparameter,(inspired by noise in image segmentation result use kernel_size=4,stride=2,padding=1 thus to avoid output-padding and satisfy the size.But after 100 epoch I met similiar problem. after another 30 epoch training, it seems like this, the black points just scattered,It seems these black points just change their parttern and jump into another parttern,I don't know why it occurs.I'm don't know how to modify my network hyperparameter. self.conv1=Basic(1024,512,kernel_size=3,stride=1,padding=1) self.conv2=Basic(512,512,kernel_size=3,stride=1,padding=1) self.deconv1=Basic(512,256,kernel_size=4,stride=2,conv=False,padding=1) self.…
tagged with: semantic-segmentation
has comment: http://stackoverflow.com/comment/89293511
tagged with: python
has comment: http://stackoverflow.com/comment/89293621
answer count: 0
tagged with: pytorch
type: Question
score: 5
has title: My Image segmentation result map contains black lattice in in the white patch
has comment: http://stackoverflow.com/comment/89294152
has comment: http://stackoverflow.com/comment/89294065
tagged with: deconvolution
tagged with: image-segmentation
has comment: http://stackoverflow.com/comment/89292755
has comment: http://stackoverflow.com/comment/89293245
has comment: http://stackoverflow.com/comment/89292856
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/49554650
has comment: http://stackoverflow.com/comment/89293449

http://stackoverflow.com/a/61489619
score: 7
has body: Another alternative is to simply use docker-java-python image from docker hub. https://hub.docker.com/r/rappdw/docker-java-python FROM rappdw/docker-java-python:openjdk1.8.0_171-python3.6.6 RUN java -version RUN python --version
has comment: http://stackoverflow.com/comment/124406597
upvote count: 8
has comment: http://stackoverflow.com/comment/118634193
downvote count: 1
answers question: http://stackoverflow.com/q/51121875
type: Answer

http://stackoverflow.com/comment/89300971
has text: I have tested the code before and including reading the input it only took less than a minute or so. This is really strange. I will rerunning the code to see how long it took for the rest.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51143668

http://stackoverflow.com/comment/89187080
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51099916
type: QuestionComment
has text: What do you mean by `value of a`? Are there specific key-value pairs which need to be identical?

http://stackoverflow.com/q/51136268
score: 1
has comment: http://stackoverflow.com/comment/89299787
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
has body: I'm using python click framework to define commands. I want to define this kind of command: config bgp neighbor neighbor_addr detail local_addr as_number ... for example: config bgp neighbor 1.1.1.1 detail 1.1.1.10 300 ... So I use codes like this: # # 'bgp' group # @cli.group() def bgp(): """BGP-related configuration tasks""" pass # # 'neighbor' subcommand # @bgp.command() @click.pass_context @click.argument('neighbor_addr', type=str, required=True) def neighboraddr(neighbor_addr): """Config BGP neighbor infomations""" ctx.obj['NEIGHBOR_ADDR'] = neighbor_addr # neighborinfo subcommand @neighboraddr.command() @click.pass_context @click.argument('name', type=str, required=True) @click.argument('local_peer_addr', metavar='&lt;ipaddr_or_hostname&gt;', required=True) @click.argument('asn', type=int, required=True) @click.argument('admin_status', type=str, required=False) @click.argument('rrclient', type=int, required=False) @click.argument('nhopself', type=int, required=False) @click.argument('holdtime', type=int, required=False) @click.argument('keepalive', type=int, required=False) def neighborinfo(ctx, name, local_peer_addr, asn, admin_status, rrclient, nhopself, holdtime, keepalive): """Config BGP neighbor infomations details""" _config_bgp_neighbor_info(ctx.obj['NEIGHBOR_ADDR'], name, local_peer_addr, asn, admin_status, rrclient, nhopself, holdtime, keepalive) But I got errors like this: root@switch1:~# config bgp neighboraddr 1.1.1.1 neighborinfo ? Traceback (most recent call last): File "/usr/bin/config", line 9, in load_entry_point('sonic-utilities==1.2', 'console_scripts', 'config')() File "/usr/lib/python2.7/dist-packages/click/core.py", line 716, in call return self.main(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/click/core.py", line 696, in main rv = self.invoke(ctx) File "/usr/lib/python2.7/dist-packages/click/core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/lib/python2.7/dist-packages/click/core…
has answer: http://stackoverflow.com/a/51274635
has comment: http://stackoverflow.com/comment/89275360
has comment: http://stackoverflow.com/comment/89257075
tagged with: python-click
has title: How to define this command by python click framework?
answer count: 1

http://stackoverflow.com/comment/89254289
type: QuestionComment
comment on: http://stackoverflow.com/q/51130383
score: 0
has text: I'm not sure why you're running the MPLD3 server. The `fig_to_html` function should only return the HTML code which gets parsed in the browser to display the chart. There shouldn't be any other server running except for Flask.
type: Comment

http://stackoverflow.com/comment/92098760
type: Comment
type: QuestionComment
has text: @halfer Yes, I have learned that as of now. Thanks, for letting me know though.
score: 1
comment on: http://stackoverflow.com/q/51089238

http://stackoverflow.com/a/51060553
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51060477
answers question: http://stackoverflow.com/q/51060477
upvote count: 4
has body: Use List Comprehension prefix = ['A', 'B', 'C'] suffix = ['a', 'b'] result = [val+" "+val2 for val in prefix for val2 in suffix ] print(result) OUTPUT ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
score: 4
type: AcceptedAnswer

http://stackoverflow.com/q/51101791
tagged with: conditional-statements
tagged with: arrays
answer count: 2
has body: I want to find the indexes of an array which satisfy a condition. I have a numpy.ndarray B: (m = number of rows = 8 and 3 columns) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 1.], [ 0., 1., 1.], [ 0., 1., 0.], [ 1., 1., 0.], [ 1., 1., 1.], [ 1., 0., 1.], [ 1., 0., 0.]]) For each column I want to find the index of the rows for which the elements satisfy the following condition: for col in columns: B(row,col)=1 and B(row+1,col)=1 for all rows=1,2,..,m-1 and B(row,col)=1 for rows=0 and m. So the desired outcome is: Sets1=[[5, 6, 7, 8], [3, 4, 5], [2, 6]] So far I've tried this: Sets1=[] for j in range(3): Sets1.append([i for i, x in enumerate(K[1:-1]) if B[x,j]==1 and B[x+1,j]==1]) But this is only the first part of the condition and gives the following wrong output because it takes the index of new set.. So it should be plus 1 actually.. Sets1= [[4, 5, 6], [2, 3, 4], [1, 5]] Also the second part of the condition which goes for indexes 0 and m. Isn't included yet.. Edit: I fixed the plus 1 part by writing i+1 and I tried the second part of the condition by adding these if statements: Sets1=[] for j in range(3): Sets1.append([i+1 for i, xp in enumerate(K[1:-1]) if B[xp,j]==1 and B[xp+1,j]==1]) if B[0,j]==1: Sets1[j].append(0) if B[(x-1),j]==1: Sets1[j].append(x-1) Which does work since it gives the following output: Sets1= [[5, 6, 7, 8], [3, 4, 5], [2, 6]] So now i just need to add +1 to the elements of the list for the first part of the condition (before the if statements)... I would really appreciate the help!
downvote count: 0
has answer: http://stackoverflow.com/a/51105565
favorite count: 0
has answer: http://stackoverflow.com/a/51105404
tagged with: python
has title: Get indices from array where element in row satisfies condition
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51105404
tagged with: list
upvote count: 2
accepted answer: http://stackoverflow.com/a/51105565
type: Question
tagged with: numpy

http://stackoverflow.com/a/51095966
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89187172
has body: Since you have already fit the model with the desired variables in mt_model1, you can directly call for F-statistic by, print(mt_model1.fvalue) This can be also used when you have multiple predictors in your model.
has comment: http://stackoverflow.com/comment/89185461
upvote count: 1
answers question: http://stackoverflow.com/q/51093906
has comment: http://stackoverflow.com/comment/89201537
downvote count: 0

http://stackoverflow.com/q/51073045
type: Question
has comment: http://stackoverflow.com/comment/117399463
possible better answer: http://stackoverflow.com/a/51073094
has answer: http://stackoverflow.com/a/68669876
tagged with: srt
has body: I have a video transcript SRT file with lines in conventional SRT format. Here's an example: 1 00:00:00,710 --&gt; 00:00:03,220 Lorem ipsum dolor sit amet consectetur, adipisicing elit. 2 00:00:03,220 --&gt; 00:00:05,970 Dignissimos et quod laboriosam iure magni expedita 3 00:00:05,970 --&gt; 00:00:09,130 nisi, quis quaerat. Rem, facere! I'm trying to use python to read and then parse through this file, remove (or skip) the lines that include the digit strings (e.g., SKIP '1' &amp; '00:00:00,710 --> 00:00:03,220') and then format the remaining lines of text so that they are joined and presented in readable format. Here's an example of the output I'm trying to generate: Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dignissimos et quod laboriosam iure magni expedita nisi, quis quaerat. Rem, facere! Here's the code I've come up with so far: def main(): # Access folder in filesystem # After parsing content of file, move to next file # Declare variable empty list lineList = [] # read file line by line file = open( "/Sample-SRT-File.srt", "r") lines = file.readlines() file.close() # look for patterns and parse # Remove blank lines from file lines = [i for i in lines if i[:-1]] # Discount first and second line of each segment using a match pattern for line in lines: line = line.strip() if isinstance(line[0], int) != False: # store all text into a list lineList.append(line) # for every item in the list that ends with '', '.', '?', or '!', append a space at end for line in lineList: line = line + ' ' # Finish with list.join() to bring everything together text = ''.join(lineList) print(text) main() I'm pretty out of practice with my Python as is, but right now I'm wondering if the only way to effectively and reliably match the first and second lines of the segment for removal or skipping is to use a regular expression. Otherwise, this might be possible using the itertools library or some kind of function that would skip lines 1 &amp; 2 as well as any blank line. A…
downvote count: 0
has comment: http://stackoverflow.com/comment/89135993
has answer: http://stackoverflow.com/a/51073232
has comment: http://stackoverflow.com/comment/89135737
favorite count: 0
answer count: 5
tagged with: python
upvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12595051
has answer: http://stackoverflow.com/a/51073094
has title: parsing transcript .srt files into readable text
has answer: http://stackoverflow.com/a/51073461
accepted answer: http://stackoverflow.com/a/51073232
score: 6
has answer: http://stackoverflow.com/a/72942153

http://stackoverflow.com/comment/89135100
type: Comment
has text: follwing your example, I keep the list abc( with 6 elements) and created a new df with 9 rows , in which they have 6 rows that the number in column text =2. data = {'Text':['foo', 'bar', 'spam', 'eggs', 'ham', 'asdf','cvddd','vfhfhhfhf','cgddd','aa'], 'Number':[2, 2, 5, 2, 4,2, 3,2,4,2]} . I modify your code with enumerate(range(0, len(abc))) .In the result, the element 'c' and 'e' in list abc are removed and two last '2' in df are still not replaced by the element in abc So do you know how to fix this problem?Thank you very much
comment on: http://stackoverflow.com/a/51052016
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89112703
comment on: http://stackoverflow.com/a/51056151
score: 0
type: Comment
type: AnswerComment
has text: @MateenUlhaq thank you for comment, about memory you're right. For medium-sized lists i edit the answer. For big data not think both solution is good.

http://stackoverflow.com/a/51193462
has body: The following is an example of how to interpolate your values. The coord_ and ma_ arrays will be your imported data. The first thing the script does is build some more sensible data structures from your disparate 1 dimensional arrays. The part that you're actually looking for is the call to np.interp, documented here. import numpy as np import datetime import time # Numpy cannot interpolate between datetimes # This function converts a datetime to a timestamp def to_ts(dt): return time.mktime(dt.timetuple()) coord_dts = np.array([ datetime.datetime(2000, 1, 1, 12), datetime.datetime(2000, 1, 2, 12), datetime.datetime(2000, 1, 3, 12), datetime.datetime(2000, 1, 4, 12) ]) coord_xs = np.array([3, 5, 8, 13]) coord_ys = np.array([2, 3, 5, 7]) coord_zs = np.array([1, 3, 6, 10]) ma_dts = np.array([ datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2), datetime.datetime(2000, 1, 3), datetime.datetime(2000, 1, 4) ]) ma_vals = np.array([1, 2, 3, 4]) # Handling the data as separate arrays will be painful. # This builds an array of dictionaries with the form: # [ { 'time': timestamp, 'x': x coordinate, 'y': y coordinate, 'z': z coordinate }, ... ] coords = np.array([ { 'time': to_ts(coord_dts[idx]), 'x': coord_xs[idx], 'y': coord_ys[idx], 'z': coord_zs[idx] } for idx, _ in enumerate(coord_dts) ]) # Build array of timestamps from ma datetimes ma_ts = [ to_ts(dt) for dt in ma_dts ] for coord in coords: print("ma interpolated value", np.interp(coord['time'], ma_ts, ma_vals)) print("at coordinates:", coord['x'], coord['y'], coord['z'])
accepted answer of: http://stackoverflow.com/q/51129215
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51129215
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51148293
has body: I have the following code (Python 2.7): import pandas as pd .... pd.DataFrame(response2.json())['results'].to_json('orders.json', orient='records') This saves a orders.json file in my local project. I want the file to be written to my Bucket on Google Storage and not to my local machine. Is it possible to generate the file directly to the storage or must I create it locally and then upload it? I know it should be something like: from google.cloud import storage storage_client = storage.Client() bucket = storage_client.get_bucket("MyTestBucket") blob = bucket.blob("folderName/" + blob?!) blob.upload_from_filename("orders.json") # Or something with writing the DataFrame? Can someone help with that?
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51148976
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: google-cloud-storage
type: Question
has answer: http://stackoverflow.com/a/51148976
has title: How to create a Json file in google storage from DataFrame?

cflags
type: Tag
tags question: http://stackoverflow.com/q/51149227
tag name: cflags

http://stackoverflow.com/comment/89210881
score: 0
type: AnswerComment
has text: @YaleNewman - I suggest 2 solutions - replace NaN to some integer like `s["order_id"] = s["order_id"].fillan(0).astype(int)` or remove rows with NaNs like `s = s.dropna(subset=['order_id'])`. Use `astype(object)` is hack.
comment on: http://stackoverflow.com/a/51112008
type: Comment

http://stackoverflow.com/comment/89298767
has text: In your plot above, all the circles are red, all the squares are green and all the triangles are blue. Would it be possible to have a plot where both marker and shape are decided by the data, which would lead to some squares being green while other squares being red for example? My guess would be using the color argument of p.circle/square/triangle
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51146060

http://stackoverflow.com/a/51164627
downvote count: 0
has comment: http://stackoverflow.com/comment/89312638
score: 1
has comment: http://stackoverflow.com/comment/89312489
answers question: http://stackoverflow.com/q/51161506
has comment: http://stackoverflow.com/comment/89386924
upvote count: 1
has body: Solution1 (simpler code but slower and less flexible) total = [] total1 = [] for i in range(df.shape[0]): temp = df.iloc[i].tolist() if "R2" in temp: total.append(temp[temp.index("R2")+1]) else: total.append(0) if ("C1" in temp) &amp; ("C4" in temp): total1.append(temp[temp.index("C1")+1] + temp[temp.index("C4")+1]) else: total1.append(0) df["Total"] = total df["Total1"] = total1 Solution2 (faster than solution1 and easier to customize but possibly memory intensive) # columns to use cols = df.columns.tolist() zones = [x for x in cols if x.startswith('Zone')] vals = [x for x in cols if x.startswith('Value')] # you can customize here bucket1 = ['R2'] bucket2 = ['C1', 'C4'] thresh = 2 # "OR": 1, "AND": 2 original = df.copy() # bucket1 check for zone in zones: df.loc[~df[zone].isin(bucket1), cols[cols.index(zone)+1]] = 0 original['Total'] = df[vals].sum(axis=1) df = original.copy() # bucket2 check for zone in zones: df.loc[~df[zone].isin(bucket2), cols[cols.index(zone)+1]] = 0 df['Check_Bucket'] = df[zones].stack().reset_index().groupby('level_0')[0].apply(list) df['Check_Bucket'] = df['Check_Bucket'].apply(lambda x: len([y for y in x if y in bucket2])) df['Total1'] = df[vals].sum(axis=1) df.loc[df.Check_Bucket &lt; thresh, 'Total1'] = 0 df.drop('Check_Bucket', axis=1, inplace=True) When I expanded original dataframe to 100k rows, solution 1 took 11.4 s ± 82.1 ms per loop, while solution 2 took 3.53 s ± 29.8 ms per loop. The difference is because solution 2 does not for-looping over row direction.
type: Answer
has comment: http://stackoverflow.com/comment/89369196
has comment: http://stackoverflow.com/comment/89386312
has comment: http://stackoverflow.com/comment/89386990

http://stackoverflow.com/a/51016679
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51016397
score: 3
has body: These are two code snippets from google's tensorflow and facebook's pytorch. Tensorflow if (not input_saved_model_dir and not saver_lib.checkpoint_exists(input_checkpoint)): print("Input checkpoint '" + input_checkpoint + "' doesn't exist!") Pytorch ALL_TENSORTYPES = [torch.float, torch.double, torch.half] In both, they used the same line closing braces strategy. So, in my opinion, It is better to follow that.
upvote count: 3

http://stackoverflow.com/comment/89130241
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51051536
type: Comment
has text: `level_data = [[(0, 0, 0) for x in range(grid_width)] for y in range(grid_height)]`

http://stackoverflow.com/comment/89273153
has text: But `dict1` may not contain the changed element in `y`. Each dict in `x` contains 5 key/ value pairs out of the possible 26 in `y`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51144397
score: 0
type: Comment

http://stackoverflow.com/q/51034233
has comment: http://stackoverflow.com/comment/89060571
type: Question
score: 0
upvote count: 1
downvote count: 1
has body: I have 2 questions. I know that you can import excel files to Python, but when I try to it doesn't seem to work. How do I import an excel file to python? The excel file is very big, roughly 500 mbs. I would like to illustrate this but I can't seem to put in a data table in stacked overflow so please bear with me. Let's say I have a table with 3 columns, column A, B, and C. These are farm data, column A is each of the 4 seasons for the past 5 years (so 20 words/titles total, spring2018, summer2018, fall2018, winter2018, spring2017, summer2017, fall2017, winter2017...etc). Column B and C are wheat and canola yields, respectively. A couple of questions here. How do I apply formulas (eg. sum) to only "spring" in column A?(so if you can imagine excel, with column A filtered for only "spring", then applying a sum function to the results). I would like to calculate the total yields for each of the four categories. The other question I have is, after I calculate sum, how do I rank them? I want to know which season collectively for the past 5 years is the best for wheat/canola, then the 2nd best, 3rd best..etc. Bonus question: I would also like to take the sum of Column B and Column C and apply a 0.5 multiplier on it (to simulate results in a terrible year), how would I be able to do that?
has comment: http://stackoverflow.com/comment/89076683
has comment: http://stackoverflow.com/comment/89060586
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: How do you apply formulas for a subset of data in a table in python?
tagged with: python
has comment: http://stackoverflow.com/comment/89060629

http://stackoverflow.com/q/51083268
linked to: http://stackoverflow.com/q/12043973
type: UnansweredQuestion
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/89155055
has title: Modify values of an Excel file without changing the color formatting
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89156137
upvote count: 1
has comment: http://stackoverflow.com/comment/89170490
type: Question
has comment: http://stackoverflow.com/comment/89154936
has comment: http://stackoverflow.com/comment/89158803
has comment: http://stackoverflow.com/comment/89155120
downvote count: 0
tagged with: pyexcel
has body: In a Excel file, I want to replace all fields containing -0.01 by NR. In this file, all the boxes containing 0.01 are yellow. I want to keep this color formatting. But, when I replace the values as I want, all the colors are removed from the file. Here is my code # Clean the spreadsheet def cleanSpreadSheet(self): for sheet in self.data: dataSheet = self.data[sheet] for line in dataSheet: for index, entry in enumerate(line): if entry == -0.01: line[index] = 'NR' pyexcel_xlsx.save_data(self.nameFile, self.data)
favorite count: 0
has comment: http://stackoverflow.com/comment/89155247

http://stackoverflow.com/comment/89351817
has text: @exmatelote "I wrote a function to do the maths and then a for loop with an if statement." is exactly what is in my answer.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51077214

http://stackoverflow.com/comment/89095297
type: Comment
has text: The OP is clearly re-inventing classes in the initial request, and has never used them. I think much of the nuance in the last few comments is well beyond the OPs current understanding.
comment on: http://stackoverflow.com/a/51051934
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89083218
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51045519
has text: @newpyguy then show us the neural network you want to implement. The solution will depend on the data and the solution for the current data is don't do batches.

http://stackoverflow.com/q/51016711
has answer: http://stackoverflow.com/a/51016889
type: Question
score: -2
possible better answer: http://stackoverflow.com/a/51016889
answer count: 3
has title: Break one line python code to multiple lines
has comment: http://stackoverflow.com/comment/89026200
has answer: http://stackoverflow.com/a/51016964
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: How to break one line code into multiple descriptive line because i am unable to understand this one line code. data = formatted_data + "|" + '|'.join(["{}".format(a) for b, a in sorted(values.items()) if a and b not in ['SecureHash']]) Is this correct or not any one help me: for b, a in sorted(values.items()): if a and b not in ['SecureHash']: c = ["{}".format(a)] data = formatted_data + "|" + "|".join(c)
has comment: http://stackoverflow.com/comment/89025940
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51016854
accepted answer: http://stackoverflow.com/a/51016964
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/51083689
tagged with: python-3.x
linked to: http://stackoverflow.com/q/30561260
type: UnansweredQuestion
has body: I've written a script in python to get the content (which are in tabular format) of a site. When I execute my script, It does parse that content successfully. The only thing I can't modify is the language option. The content of that sites are in Arabic language. However, my intention is to parse that in such a way so that the output I'll get is in english. This is where I'm stuck. I tried with headers={"Accept-Language":"en-US,en;q=0.9"} according to this answer but it doesn't seem to work in this case. How can I change the language option to serve the purpose? This is my script: import requests from bs4 import BeautifulSoup URL = "http://www.awm.gov.jo/dotnet/default.aspx" req = requests.get(URL,headers={"Accept-Language":"en-US,en;q=0.9"}) soup = BeautifulSoup(req.text,"lxml") for items in soup.select("#GV_prices tr"): data = [item.get_text(strip=True) for item in items.select("th,td")] print(data) FYI, this was headers={"Accept-Language": "en-US,en;q=0.5"} my first try but It didn't work either.
has comment: http://stackoverflow.com/comment/89156748
tagged with: web-scraping
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89156744
has comment: http://stackoverflow.com/comment/89156377
score: -1
has comment: http://stackoverflow.com/comment/89226259
upvote count: 0
has answer: http://stackoverflow.com/a/51083857
answer count: 1
has comment: http://stackoverflow.com/comment/89156274
favorite count: 0
tagged with: beautifulsoup
has title: Unable to change the language to get desired output
tagged with: python

http://stackoverflow.com/q/51112011
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/894864
tagged with: python
has answer: http://stackoverflow.com/a/51112321
has body: I have a circular dependency, how can I fix this? LogClass ... import ErrorClass def log(self, error): # isinstance(error, ErrorClass) ErrorClass ... import LogClass log = LogClass()
downvote count: 2
has comment: http://stackoverflow.com/comment/89211294
type: Question
upvote count: 0
score: -2
has title: Circular dependency fix in Python
answer count: 1
has comment: http://stackoverflow.com/comment/89211204

http://stackoverflow.com/a/51060637
score: 3
has body: use pandas to read the csv-file into a dataframe import pandas as pd sourceinput = pd.read_csv('myfile.csv') outputlist = sourceinput['id'].loc[sourceinput['id'] == &lt;value_you_need&gt;].tolist()
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51060346
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51060346

http://stackoverflow.com/q/51069610
has comment: http://stackoverflow.com/comment/89129583
has body: In this question i will hardcode acceptable operators, these operators will be allowed in the code: acceptable_operators = ['x', '/' , '+', '-', '.'] Now i will give a string let's say : sentence = "this 78isa6+trap//+sentence78-+6" First step, after removing all non numbers and strings not in accepted_operators: 786+//+78-+6 We can see that it doesn't make much sense here same occurrences of multiplications more than once if ... or xxx should be reduced to only one, same with addition and division, however minus operator is different 2 minuses will result a + 3 minuses a minus and so on. In case of different operators next to each other: in case it's a +- regular math takes over. in other cases like having +/ or +x or -/ or -x the multiplication and division operators dominate and the +- are "deleted" however if we have x-5 we, for example, we don't delete the minus as it indicates 5 is negative. In case we have x/ the one to the right is "deleted" in this case / Final expected result: 786/+78-6
has answer: http://stackoverflow.com/a/51069977
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89129477
has comment: http://stackoverflow.com/comment/89129115
has comment: http://stackoverflow.com/comment/89129543
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89129542
downvote count: 2
has comment: http://stackoverflow.com/comment/89129195
accepted answer: http://stackoverflow.com/a/51069977
upvote count: 1
has comment: http://stackoverflow.com/comment/89129317
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51070503
score: -1
has answer: http://stackoverflow.com/a/51070503
has title: How can i keep only the given operators and numbers?

http://stackoverflow.com/q/51124241
has answer: http://stackoverflow.com/a/51125096
has title: Reload request data for telegrambot python
type: Question
has comment: http://stackoverflow.com/comment/89233946
score: 0
answer count: 1
has body: I'm creating telegrambot for price and I did it successfully but the problem is the price didn't update, each time I press start I got the same price while it updated on the API wep-page import requests import json import telebot import locale import time from datetime import datetime locale.setlocale( locale.LC_ALL, '' ) while True : try: # base URLs tickerURL = "https://api.coinmarketcap.com/v1/ticker/" # choice = "bitcoin" tickerURL += '/'+choice+'/' request = requests.get(tickerURL) data = request.json() ticker = data[0]['symbol'] price = data[0]['price_usd'] price_btc = data[0]['price_btc'] rank = data[0]['rank'] market_cap = data[0]['market_cap_usd'] change_24 = data[0]['24h_volume_usd'] price_a = ticker + ":\t\t$ " + price price_b = ticker + ":\t\tB " + price_btc bot_token = '&lt;telegram-token&gt;' bot = telebot.TeleBot(bot_token) @bot.message_handler(commands=['price', 'help']) def send_welcome(message): cont = price_a cont += '\n'+ price_b cont += '\nRank: '+ rank cont += '\nChange 24hr: '+ "{:,}".format(float(change_24)) cont += '\nMarket_cap: ' + "{:,}".format(float(market_cap)) bot.reply_to(message,cont) print('hey..') bot.polling() except Exception: time.sleep(10) So I want to add some code to update the price frequently
has comment: http://stackoverflow.com/comment/89233998
tagged with: telegram
type: UnansweredQuestion
tagged with: python
tagged with: cryptography

http://stackoverflow.com/comment/104715328
has text: @RahulChawla why it is expensive operation any references, special cases of reasoning for same.?
comment on: http://stackoverflow.com/q/51078195
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51060433
score: 0
has comment: http://stackoverflow.com/comment/89141589
has comment: http://stackoverflow.com/comment/89141145
type: Question
has answer: http://stackoverflow.com/a/54091687
answer count: 2
tagged with: javascript
has comment: http://stackoverflow.com/comment/89113469
tagged with: jquery
tagged with: flask
accepted answer: http://stackoverflow.com/a/51079772
possible better answer: http://stackoverflow.com/a/54091687
has body: I coded a jQuery with flask where on-click it should perform an SQL search and export the dataframe as excel, the script is: &lt;script type=text/javascript&gt; $(function () { $('a#export_to_excel').bind('click', function () { $.getJSON($SCRIPT_ROOT + ' /api/sanctionsSearch/download', { nm: $('input[name="nm"]').val(), searchtype: $('select[name="searchtype"]').val() }, function (data) { $("#download_results").text(data.result); }); return false; }); }); However there was not response on the browser, my python code is as below: from io import BytesIO,StringIO from flask import render_template, request, url_for, jsonify, redirect, request, Flask, send_file def index(): #get the dataframe ready and define as 'data', parameters obtained from form input in html name = request.args.get('nm','', type = str) type = request.args.get('searchtype','Entity',type = str) #function get_entity() to get the dataframe #I have checked and the dataframe is functioning properly data = get_entity(name,type) #check if the dataframe is empty if data.empty == True: print("its not working bruh...") word = "No results to export! Please try again!" return jsonify(result = word) #store the csv to BytesIO proxy = StringIO() data.to_csv(proxy) mem = BytesIO() mem.write(proxy.getvalue().encode('utf-8')) mem.seek(0) proxy.close() print("download starting....") #send file send_file(mem, as_attachment=True,attachment_filename='Exportresults.csv', mimetype='text/csv') word = "Download starting!" return jsonify(result = word) Can someone tell me what's wrong with my code? The "download starting..." was properly printed to the html but the download did not start at all.
has title: Flask send_file as attachment no response
has comment: http://stackoverflow.com/comment/89136792
tagged with: python
has answer: http://stackoverflow.com/a/51079772
type: AnsweredQuestion

http://stackoverflow.com/a/56449703
upvote count: 1
has body: I tried the proposed solution but it doesn't work for a lot of reasons, including metaclass conflicts with graphene.ObjectType so I created a solution that works pretty well: you would provide the subclassed ObjectType a list of your ORM models (in my case SQLAlchemy) and it auto creates the schema. The only thing left to do would be to add special handling if you needed to add extra filtering options for any of the fields. class SQLAlchemyAutoSchemaFactory(graphene.ObjectType): @staticmethod def set_fields_and_attrs(klazz, node_model, field_dict): _name = camel_to_snake(node_model.__name__) field_dict[f'all_{(s2p(_name))}'] = FilteredConnectionField(node_model) field_dict[_name] = node_model.Field() # log.info(f'interface:{node_model.__name__}') setattr(klazz, _name, node_model.Field()) setattr(klazz, "all_{}".format(s2p(_name)), FilteredConnectionField(node_model)) @classmethod def __init_subclass_with_meta__( cls, interfaces=(), models=(), excluded_models=(), default_resolver=None, _meta=None, **options ): if not _meta: _meta = ObjectTypeOptions(cls) fields = OrderedDict() for interface in interfaces: if issubclass(interface, SQLAlchemyInterface): SQLAlchemyAutoSchemaFactory.set_fields_and_attrs(cls, interface, fields) for model in excluded_models: if model in models: models = models[:models.index(model)] + models[models.index(model) + 1:] possible_types = () for model in models: model_name = model.__name__ _model_name = camel_to_snake(model.__name__) if hasattr(cls, _model_name): continue if hasattr(cls, "all_{}".format(s2p(_model_name))): continue for iface in interfaces: if issubclass(model, iface._meta.model): model_interface = (iface,) break else: model_interface = (CustomNode,) _node_class = type(model_name, (SQLAlchemyObjectType,), {"Meta": {"model": model, "interfaces": model_interface, "only_fields": []}}) fields["all_{}".format(s2p(_model_name))] = FilteredConnectionField(_node_class) setattr(cls, "all_{}".format(s2p(_model_name)), FilteredConnectionFie…
score: 1
answers question: http://stackoverflow.com/q/51042724
accepted answer of: http://stackoverflow.com/q/51042724
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51102219
type: Answer
score: 0
has body: So you have a dict of DataFrames let's call it data_dict and a list of Cycle Cycles. You say you don't know how to handle a dictionnary of dataframes but that is actually the easy part once you know how to handle one dataframe since you just have to loop over it. To solve your problem just use the isin method : res = {} for id, df in data_dict.items(): #loop over the dataframes in the dict res[id] = df[df.Cycle.isin(Cycles)] #this is a new dataframe where you have only the cycles in Cycles
answers question: http://stackoverflow.com/q/51101998

http://stackoverflow.com/comment/89201972
comment on: http://stackoverflow.com/q/51107205
has text: @Mufeed Yep, thanks!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51048031
has comment: http://stackoverflow.com/comment/89093584
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89093453
has comment: http://stackoverflow.com/comment/89090712
has answer: http://stackoverflow.com/a/51051336
has comment: http://stackoverflow.com/comment/89090397
has comment: http://stackoverflow.com/comment/89091234
has comment: http://stackoverflow.com/comment/89090950
has comment: http://stackoverflow.com/comment/89091017
type: Question
tagged with: search
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89092138
has title: How to search through both zipped and unzipped folders for a specific line
tagged with: python
has comment: http://stackoverflow.com/comment/89090010
has comment: http://stackoverflow.com/comment/89093737
tagged with: regex
has comment: http://stackoverflow.com/comment/89091098
has body: I'm trying to implement a Python script that takes a folder from the user (can be zipped or unzipped), and search through all the files in the folder to output the specific lines that my regular expression matches. My code below works for regular unzipped folders, but I can't figure out how to do the same with zipped folders that are inputted to function. Below are my code, thanks in advance! def myFunction(folder_name): path = folder_name for (path, subdirs, files) in os.walk(path): files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log') or f.endswith('-release') or f.endswith('.out') or f.endswith('messages') or f.endswith('.zip')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log") files.sort() # file is sorted list files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function # The following for loop searches all files with the selected format for filename in files: #print('start parsing... ' + str(datetime.datetime.now())) matched_line = [] try: with open(filename, 'r', encoding = 'utf-8') as f: f = f.readlines() except: with open(filename, 'r') as f: f = f.readlines() # print('Finished parsing... ' + str(datetime.datetime.now())) for line in f: #0strip out \x00 from read content, in case it's encoded differently line = line.replace('\x00', '') RE2 = r'^Version: \d.+\d.+\d.\w\d.+' RE3 = r'^.+version.(\d+.\d+.\d+.\d+)' pattern2 = re.compile('('+RE2+'|'+RE3+')', re.IGNORECASE) for match2 in pattern2.finditer(line): matched_line.append(line) print(line) #Calling the function to use it myFunction(r"SampleZippedFolder.zip") The try and except block of my code was my attempt to open the zipped folder and read it. I'm still not very clear with how to open the zipped folder or how it works. Please let me know how I can modify my code to make it work, much appreciated!

http://stackoverflow.com/comment/89193998
comment on: http://stackoverflow.com/a/51103136
type: Comment
has text: @DLMike you would probably want to write a loop. See [**`any`**](https://docs.python.org/3/library/functions.html#any) and [**`all`**](https://docs.python.org/3/library/functions.html#all)
score: 0
type: AnswerComment

http://stackoverflow.com/a/60982323
answers question: http://stackoverflow.com/q/51056935
type: Answer
has body: Another way to change the data type after reading the csv: df['col'].apply(tuple)
score: 0

http://stackoverflow.com/q/51056935
has answer: http://stackoverflow.com/a/60982323
has title: Why does pandas df.values convert tuple into strings
score: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: pandas
downvote count: 1
answer count: 3
has answer: http://stackoverflow.com/a/51057007
has answer: http://stackoverflow.com/a/51058039
has body: I have a csv with 4000 over data, in which each cells contains a tuple which holds a specific coordinated. I will like to convert it to a numpy array to work with. I use pandas to convert it into a DataFrame before calling df.values. However after calling df.values, the tuple becomes a string "(x,y)", instead. Is it possible to prevent this happening? Thank you. df = pd.read_csv(sample_data) array = df.values
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/52488258
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51014756
answers question: http://stackoverflow.com/q/51014756
type: Answer
downvote count: 0
score: 1
has body: In this page of the tcl/tk wiki are listed some problems related to Mac and the color of labels and buttons's backgrounds. For example: ... The Mac OS X background color should not be white, it should be #ececec. Since winfo rgb does not work properly on the mac colors, this makes it difficult to get the proper default color. ... etc. Saludos!,
upvote count: 1

http://stackoverflow.com/comment/89092864
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51030474
type: Comment
has text: (Without `del builtins._`, the `randn` return value gets deallocated between the creation of the `numpy.empty` return value and the stringification of the `numpy.empty` return value, because `sys.displayhook` sets `builtins._` to `None` before stringifying or printing anything.)

http://stackoverflow.com/a/51047679
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/51047378
type: Answer
has body: One nice way to do this might be to define a from_string classmethod on your ListNode class that will recursively build a linked list for you and return the head: class ListNode(object): def __init__(self, x): self.val = x self.next = None @classmethod def from_string(cls, s): if s: n = cls(s[0]) n.next = ListNode.from_string(s[1:]) return n n = ListNode.from_string('hello') print(n.next.next.next.next.val) &gt;&gt;&gt; 'o'
score: 1

http://stackoverflow.com/comment/89270207
comment on: http://stackoverflow.com/q/51142930
score: 1
has text: Long paths have to be enabled both at the system level and in the application's manifest. It's enabled for Python 3.6+ if you can upgrade. Otherwise you could modify the embedded manifest in "python.exe".
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89221768
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51116785
type: Comment
has text: You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder.

http://stackoverflow.com/q/51065560
type: Question
has comment: http://stackoverflow.com/comment/89121626
has comment: http://stackoverflow.com/comment/89122260
has answer: http://stackoverflow.com/a/51065975
has comment: http://stackoverflow.com/comment/89121063
score: 0
tagged with: pandas
has title: Removing date from an entire column of date&time data in python?
answer count: 1
tagged with: dataset
has body: I am working with large data sets from a water quality sensor that relays the date and time in the format: 25-Jun-2018 15:16:51 I would like to remove the date portion from the entire column of Date/Time data, however I am finding it hard to do so because I am extremely new to python. I was able to remove the date from a single piece of data using: df = pd.DataFrame({'time':['25-Jun-2018 15:17:49']}) df time 0 25-Jun-2018 15:17:49 df['time'] = pd.to_datetime(df['time']).dt.time df time 0 15:17:49 Can anybody help me do this to an entire column of data at once? The data looks like this. water_level_time = pd.DataFrame() water_level_time = df'Date / Time' water_level_time Date / Time 0 25-Jun-2018 15:16:51 1 25-Jun-2018 15:16:53 2 25-Jun-2018 15:16:55 3 25-Jun-2018 15:16:57 4 25-Jun-2018 15:16:59 5 25-Jun-2018 15:17:1 6 25-Jun-2018 15:17:3 7 25-Jun-2018 15:17:5 8 25-Jun-2018 15:17:7 9 25-Jun-2018 15:17:9 Any and all suggestions are appreciated. Thank you for your time.
tagged with: time
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89122314

http://stackoverflow.com/comment/89128861
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51068950
has text: the code is still giving optimal lambda as nan for all all polynomials for the errors
type: AnswerComment

http://stackoverflow.com/comment/89122668
has text: Yes that does work for the first section of code. And @tobesecret comment works for the append part. Currently getting an issue when trying to delete the row from the old Dataframe.
comment on: http://stackoverflow.com/a/51066187
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89235126
has text: Hey there, thanks for the response; I tried what you suggested and still had some issues - I updated my question with the output of `brew doctor`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51118020

http://stackoverflow.com/a/51160400
has comment: http://stackoverflow.com/comment/89304992
has comment: http://stackoverflow.com/comment/89304843
has body: No shallow copying, shortest, and with modification possibilities: from collections import UserDict class DictProxy(UserDict): def __init__(self, d): self.data = d def __getitem__(self, item): val = super().__getitem__(item) if item == 'a': val += 2 return val
score: 0
has comment: http://stackoverflow.com/comment/89305007
has comment: http://stackoverflow.com/comment/89305529
type: Answer
answers question: http://stackoverflow.com/q/51159611
has comment: http://stackoverflow.com/comment/89305056

http://stackoverflow.com/comment/89351137
score: 0
has text: I've figured out how to do it with some help from a friend. I wrote a function to do the maths and then a for loop with an if statement. There's a problem with the maths I am still working through but when I get that right i'll post what I did.
type: AnswerComment
comment on: http://stackoverflow.com/a/51077214
type: Comment

http://stackoverflow.com/comment/89263099
type: Comment
has text: I don't understand your comment.
comment on: http://stackoverflow.com/a/51139401
type: AnswerComment
score: 0

http://stackoverflow.com/a/51155617
has comment: http://stackoverflow.com/comment/89295353
has comment: http://stackoverflow.com/comment/89295135
score: 1
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89295086
has comment: http://stackoverflow.com/comment/89318803
downvote count: 1
has comment: http://stackoverflow.com/comment/89295392
answers question: http://stackoverflow.com/q/51154180
has comment: http://stackoverflow.com/comment/89295017
has comment: http://stackoverflow.com/comment/89295115
has comment: http://stackoverflow.com/comment/89295345
has body: I suspect that the problem concerns the way you are defining your target vector. try replacing this: target = 'num' with this: target = ['num'] hope this helps

http://stackoverflow.com/comment/89244063
type: Comment
has text: do you want to change no. in wikiEdit ?
score: 0
comment on: http://stackoverflow.com/q/51129628
type: QuestionComment

http://stackoverflow.com/comment/115941827
score: 0
has text: I think you better make it manually to reset the password
type: Comment
comment on: http://stackoverflow.com/a/51172955
type: AnswerComment

http://stackoverflow.com/comment/89310229
type: Comment
comment on: http://stackoverflow.com/a/51146914
has text: This works with order (thanks for that) but there a way to also get similar strings? like if their csv file has the column "FirstName" it would still appropriate the fields "first_name"?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51101217
has answer: http://stackoverflow.com/a/51102392
has comment: http://stackoverflow.com/comment/89192076
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89199000
has comment: http://stackoverflow.com/comment/89197636
accepted answer: http://stackoverflow.com/a/51102392
has title: Implementing k nearest neighbours from distance matrix?
tagged with: pandas
has body: I am trying to do the following: Given a dataFrame of distance, I want to identify the k-nearest neighbours for each element. Example: A B C D A 0 1 3 2 B 5 0 2 2 C 3 2 0 1 D 2 3 4 0 If k=2, it should return: A: B D B: C D C: D B D: A B Distances are not necessarily symmetric. I am thinking there must be something somewhere that does this in an efficient way using Pandas DataFrames. But I cannot find anything? Homemade code is also very welcome! :) Thank you!
answer count: 1
has comment: http://stackoverflow.com/comment/89199738
tagged with: python
has comment: http://stackoverflow.com/comment/89199538
type: AnsweredQuestion

http://stackoverflow.com/comment/89126970
comment on: http://stackoverflow.com/a/51068419
has text: That's correct. But that doesn't tell you anything. Put in some more prints and run it again. Then you will learn something.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89224703
comment on: http://stackoverflow.com/q/51119445
type: Comment
has text: You can hit the `up` arrow key if you want to edit your older functions without having to copy/paste. See [How do I access the command history from IDLE?](https://stackoverflow.com/questions/3132265/how-do-i-access-the-command-history-from-idle)
score: 0
type: QuestionComment

http://stackoverflow.com/q/51039943
tagged with: f-string
accepted answer: http://stackoverflow.com/a/51040363
type: Question
has comment: http://stackoverflow.com/comment/89071417
has comment: http://stackoverflow.com/comment/89071231
has title: way to create fstring inside a fstring
has answer: http://stackoverflow.com/a/51040363
score: 0
has comment: http://stackoverflow.com/comment/89071553
has comment: http://stackoverflow.com/comment/89072479
answer count: 1
tagged with: string
tagged with: python
has comment: http://stackoverflow.com/comment/89072142
type: AnsweredQuestion
has body: is it possible to create a fstring inside a fstring? what i am trying now is to create a dynamic function using eval. my code is something like this func_string = '' for scenario in ['scene1', 'scene2']: for aa in ['int', 'ext']: func_string += f''' def function_{scenario}_{aa}(part): print(f"this is {part}") ''' eval(func_string) function_scene1_int('part1') running this script will return: this is part1

http://stackoverflow.com/comment/89144479
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51063665
has text: Oh, thank you. Read that and understood. Will take care from ahead.
score: 0

http://stackoverflow.com/comment/89207585
comment on: http://stackoverflow.com/q/51110235
score: 1
has text: Excuse me? I don't think I did anything that went against the guidelines. I already suggested a solution that did not work, and I am looking for an alternative.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51049897
score: 3
has answer: http://stackoverflow.com/a/70438841
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89091880
downvote count: 0
tagged with: dataframe
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89092919
favorite count: 0
tagged with: python-3.x
tagged with: dask
type: UnansweredQuestion
has title: Dask Apply of Python Function
has body: I have a df: id log 0 24 2*C316*first_field_name17*second_field_name16*third_field_name2*N311*field value1*Y5*hello2*O30*0*0* 1 25 2*C316*first_field_name17*second_field_name16*third_field_name2*N311*field value1*Y5*hello2*O30*0*0* I have a function that parses the string: dfs = [] def parse_log(id, log): split = log.split('*') number_of_fields = int(split[1][1:int(split[0][0])]) i=2 string_length = int(split[1][int(split[0][0]):]) field_names_list = [] while i &lt; number_of_fields + 2: field_name = split[i][0:string_length] field_names_list.append(field_name) string_length = int(split[i][string_length:]) i+=1 i = 3 + number_of_fields string_length = int(split[2 + number_of_fields][string_length:]) new_values_list = [] while i &lt; 3+number_of_fields*2: field_name = split[i][0:string_length] new_values_list.append(field_name) string_length = int(split[i][string_length:]) i+=1 i = 4 + number_of_fields*2 string_length = int(split[3 + number_of_fields*2][string_length:]) old_values_list = [] while i &lt;= 3 + number_of_fields*3: old_value = split[i][0:string_length] old_values_list.append(old_value) if i == 3 + number_of_fields*3: string_length = 0 else: string_length = int(split[i][string_length:]) i+=1 df = pd.DataFrame( {'id':id, 'field': field_names_list, 'old_value': old_values_list, 'new_value': new_values_list }) dfs.append(df) This function works with a normal pandas apply: data.apply(lambda x: parse_audit_log(x['id'], x['log']), axis=1) Then I attempt to apply with dask instead (data in this case is a dask dataframe read from SQL): out = data.map_partitions(lambda df : df.apply(lambda x : parse_audit_log(x.id,x.log),axis=1), meta=('result', int)).compute(get=get) This results in the error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-12-2468010e0124&gt; in &lt;module&gt;() ----&gt; 1 out = data.map_partitions(lambda df : df.apply(lambda x : parse_audit_log(x.ROW_…
tagged with: python

http://stackoverflow.com/comment/89130854
comment on: http://stackoverflow.com/q/51070495
score: 0
type: Comment
type: QuestionComment
has text: What about an array of buttons?

http://stackoverflow.com/a/70483364
score: 0
has body: Running the code depends on the console you want to use. Since the question asks for a Ubuntu solution I'd suggest gnome-terminal. gnome-terminal -e "python3 %path%" Here's a screenshot and sample code for clarity. The last line input() prevents the window from closing so the user can view the output. I've tried this solution with Ubuntu 20.04.
type: Answer
answers question: http://stackoverflow.com/q/51053609

http://stackoverflow.com/a/51160160
score: 1
accepted answer of: http://stackoverflow.com/q/51159993
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51159993
type: Answer
has body: You can do ori=df.copy() pd.concat([ori.set_index('Group',append=True).swaplevel(0,1),out], 1).reset_index()
downvote count: 0

http://stackoverflow.com/a/51080964
score: 1
has comment: http://stackoverflow.com/comment/89171593
upvote count: 1
has comment: http://stackoverflow.com/comment/89154578
has body: In this case numexpr module may be faster. This module avoids intermediate buffering and thus is faster for certain operations: i = np.random.rand(100000) j = np.random.rand(100000) %timeit np.sqrt(i**2 + j**2) # 1.34 ms import numexpr as ne %timeit ne.evaluate('sqrt(i**2+j**2)') #370 us
downvote count: 0
answers question: http://stackoverflow.com/q/51077418
has comment: http://stackoverflow.com/comment/89154895
type: Answer
has comment: http://stackoverflow.com/comment/89155189

http://stackoverflow.com/comment/89129343
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51069716
has text: yeah maybe multiple versions of python installed.

http://stackoverflow.com/a/51072114
type: AcceptedAnswer
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/51072094
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/89134196
accepted answer of: http://stackoverflow.com/q/51072094
has body: If you want to know if anything in the list is a list: any(isinstance(a, list) for a in list1) If you want to know if all the things in the list are lists: all(isinstance(a, list) for a in list1) This takes advantage of passing a generator expression to all().

http://stackoverflow.com/a/51045259
downvote count: 0
has comment: http://stackoverflow.com/comment/89085470
has comment: http://stackoverflow.com/comment/89085496
has comment: http://stackoverflow.com/comment/89085661
type: Answer
answers question: http://stackoverflow.com/q/51045207
has comment: http://stackoverflow.com/comment/89081977
has body: Use select_dtypes for only object columns (obviously strings) with applymap and in: df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [None, u'bball', u'cnut', u'fball'], 'id2': [u'uball', u'mball', u'pnut', u'zball']}) print (df) vals ids id2 0 1 None uball 1 2 bball mball 2 3 cnut pnut 3 4 fball zball mask = df.select_dtypes(include=[object]).applymap(lambda x: 'ball' in x if pd.notnull(x) else False) #if always non NaNs, no Nones #mask = df.select_dtypes(include=[object]).applymap(lambda x: 'ball' in x) print (mask) ids id2 0 False True 1 True True 2 False False 3 True True Another solution is use apply with contains: mask = df.select_dtypes(include=[object]).apply(lambda x: x.str.contains('ball', na=False)) #if always non NaNs, no Nones #mask = df.select_dtypes(include=[object]).apply(lambda x: x.str.contains('ball')) print (mask) ids id2 0 False True 1 True True 2 False False 3 True True Then for filtering use DataFrame.any for check at least one True per rows or DataFrame.all for check all values per rows: df1 = df[mask.any(axis=1)] print (df1) vals ids id2 0 1 None uball 1 2 bball mball 3 4 fball zball df2 = df[mask.all(axis=1)] print (df2) vals ids id2 1 2 bball mball 3 4 fball zball
has comment: http://stackoverflow.com/comment/89085719
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89085426
has comment: http://stackoverflow.com/comment/89085357
has comment: http://stackoverflow.com/comment/89084542

http://stackoverflow.com/comment/89250351
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51132454
score: 0
has text: What about `[20, 20, 40]`?

http://stackoverflow.com/a/51062588
answers question: http://stackoverflow.com/q/51062136
score: 0
has body: The problem with the second case is when you get to the fourth iteration and your script executes i = arr.index(10). You expect this to return 3, but list.index() finds the first instance of 10 in the list, which is in position 1. In this case, you don't actually want to iterate over the elements of the list, but over their indices. Try this: def find_even_index(arr): for i in range(len(arr)): if sum(arr[:i]) == sum(arr[i+1:]): return i
type: Answer

http://stackoverflow.com/a/51131780
downvote count: 0
upvote count: 2
has body: Assuming you are using Python3.5 or newer: In [1]: d = {'NodeId_Name': 'lvgwatchit01t', 'LocationId_Name': 'loc_gru,loc_virtual_vie', 'Name': 'aixbuildhost'} In [2]: k = 'LocationId_Name' In [3]: vals = d[k].split(',') In [4]: In [5]: dicts = [{**d, k:v} for v in vals] In [6]: dicts Out[6]: [{'LocationId_Name': 'loc_gru', 'Name': 'aixbuildhost', 'NodeId_Name': 'lvgwatchit01t'}, {'LocationId_Name': 'loc_virtual_vie', 'Name': 'aixbuildhost', 'NodeId_Name': 'lvgwatchit01t'}]
answers question: http://stackoverflow.com/q/51131660
type: Answer
has comment: http://stackoverflow.com/comment/89248344
score: 2

http://stackoverflow.com/comment/89254650
comment on: http://stackoverflow.com/q/51134752
has text: @Glitch_Doctor thank you for your answer, it works.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51109956
has title: creating catch-all url() entry using regex
linked to: http://stackoverflow.com/q/40826295
has body: So had zero issues with my Django and React URL routing in dev, but now that I am trying to move to production, running into all kinds of issues. Yes, I suck when it come to regex. It looks like a cat walked on a keyboard. Definitely something I need to sit down and commit to learning. In dev, my catch-all was just the following which worked perfectly: url(r'', TemplateView.as_view(template_name='index.html')), In production, I got Uncaught SyntaxError: Unexpected token &lt;. This, as it was explained to me, had to do with JS being caught in the url instead of index.html and that the JS needed to "pass through". I was told to try: url(r'^$', TemplateView.as_view(template_name='index.html')), This worked. The web application loaded and I was able to navigate. Another problem came up, however, when it came to verification emails links. I am running into issues with Page not found (404) which, again, wasn't an issue in my dev setup. The email links look like the following: https://test.example.com/auth/security_questions/f=ru&amp;i=101083&amp;k=6d7cd2e9903232a5ac28c956b5eded86c8cb047254a325de1a5777b9cca6e537 What I get back is this: Page not found (404) Requested URL: http://test.example.com/auth/security_questions/f%3Dru&amp;i%3D101083&amp;k%3D6d7cd2e9903232a5ac28c956b5eded86c8cb047254a325de1a5777b9cca6e537/ My react routes are the following: &lt;App&gt; &lt;Switch&gt; &lt;Route exact path='/auth/security_questions/f=:f&amp;i=:id&amp;k=:key' component={SecurityQuestions} /&gt; &lt;Route exact path='/auth/*' component={Auth} /&gt; &lt;Route exact path='/' component={Auth} /&gt; &lt;/Switch&gt; &lt;/App&gt; This should render /auth/security_questions/... route. My urls.py is the following: urlpatterns = [ # API authentication entry point url(r'^api/auth/', include('authentication.urls', namespace='signin')), # Any requets that come through serve the index.html # url(r'^$', TemplateView.as_view(template_name='index.html')), ] + static(settings.STATIC_URL, document_root=s…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89207679
has comment: http://stackoverflow.com/comment/89207765
has comment: http://stackoverflow.com/comment/89207825
type: Question
upvote count: 4
tagged with: reactjs
linked to: http://stackoverflow.com/q/51140145
has comment: http://stackoverflow.com/comment/89207116
has comment: http://stackoverflow.com/comment/89207089
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89207863
has answer: http://stackoverflow.com/a/51141819
score: 4
favorite count: 0
linked to: http://stackoverflow.com/q/31248126
linked to: http://stackoverflow.com/q/28264061
tagged with: python
tagged with: regex
tagged with: react-router-dom
accepted answer: http://stackoverflow.com/a/51141819
tagged with: django

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/51034459
type: Tag

http://stackoverflow.com/q/51045492
has title: pySerial and Arduino communication
accepted answer: http://stackoverflow.com/a/51045860
has body: So far, I was exploring Python with Arduino using pySerial. I made some projects where pySerial reads something from the serial port. import serial arduinoSerialData = serial.Serial('com11',9600) #Create Serial port object called arduinoSerialData while (1==1): if (arduinoSerialData.inWaiting()&gt;0): myData = arduinoSerialData.readline() print (myData) int trigPin=13; //Sensor Trig pin connected to Arduino pin 13 int echoPin=11; //Sensor Echo pin connected to Arduino pin 11 float pingTime; //time for ping to travel from sensor to target and return float targetDistance; //Distance to Target in inches float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees. void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(trigPin, LOW); //Set trigger pin low delayMicroseconds(2000); //Let signal settle digitalWrite(trigPin, HIGH); //Set trigPin high delayMicroseconds(15); //Delay in high state digitalWrite(trigPin, LOW); //ping has now been sent delayMicroseconds(10); //Delay in low state pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second) pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour) targetDistance= speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance. targetDistance= targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile) Serial.println(targetDistance); delay(100); //delay tenth of a second to slow things down a little. } For now, my code looks something like this. How can I make use of my ultrasonic sensor in Python and…
tagged with: python
type: AnsweredQuestion
tagged with: arduino
type: Question
has answer: http://stackoverflow.com/a/51045860
score: 0
tagged with: pyserial
answer count: 1

http://stackoverflow.com/comment/89311867
type: QuestionComment
has text: I would suggest installing Anaconda, which I believe comes with scikit and other data science tools
comment on: http://stackoverflow.com/q/51164281
score: 0
type: Comment

http://stackoverflow.com/comment/89112243
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51060952
has text: Can you provide a sample of your input dataframe: something like `df.head()` or `df.head().to_dict()`?
score: 0

http://stackoverflow.com/q/51097526
has comment: http://stackoverflow.com/comment/89182736
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51103457
has comment: http://stackoverflow.com/comment/89182710
type: Question
has body: I would like to make a list or matrix that has a known number of rows(3), but for each row the number of elements will be different. So it could look something like this: [[4, 6, 8], [1, 2, 3, 4], [0, 2, 3, 4, 8]] Each row will have a known maximum of elements(8). So far I have tried the following: Sets1=np.zeros((3,8)) for j in range(3): Sets1[0,:]=[i for i, x in enumerate(K[:-1]) if B[x,j]==1 or B[x+1,j]==1] I want this because I want to have a list for each j in range(3) over which I can do a for loop and add constraints to my ILP. Any help will be greatly appreciated!
tagged with: list
tagged with: numpy
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89182682
answer count: 1
tagged with: arraylist
has title: Making a 2 dimensional list/matrix with different number of columns for each row
score: 0
tagged with: python

http://stackoverflow.com/comment/89129724
type: Comment
has text: https://docs.python.org/3/tutorial/ If you want to learn some more advanced syntax.
comment on: http://stackoverflow.com/a/51069520
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89062358
has text: You will need to show code and error messages for anyone to have any hope of helping you. I'm not familiar with botle but flask can be run in debug mode, perhaps a similar thing is possible in bottle, which may give more clues about what is happening.
score: 0
comment on: http://stackoverflow.com/q/51034693
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89216061
type: Comment
type: QuestionComment
score: 1
has text: Video upload is not yet implemented with tweepy : https://github.com/tweepy/tweepy/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+upload . And "update_with_media" is deprecated. Sorry but I suggest to use another library.
comment on: http://stackoverflow.com/q/51106363

http://stackoverflow.com/q/51086772
possible better answer: http://stackoverflow.com/a/51087125
has answer: http://stackoverflow.com/a/51087109
score: 1
has answer: http://stackoverflow.com/a/51087125
accepted answer: http://stackoverflow.com/a/51087069
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/89162108
type: Question
downvote count: 0
has body: For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input. YourName = '' while YourName != "Sunny": print("Please type in your name") YourName = input() print(YourName + " is correct") Thanks in advance, best Sentino
has title: Python: How to demand a string as input rather than a specific value
has comment: http://stackoverflow.com/comment/89163682
tagged with: while-loop
answer count: 3
tagged with: string
has answer: http://stackoverflow.com/a/51087069
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/89162056
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89419261
has text: Thanks, I think the best thing I learned here is not to necessarily rely on inheritance when you don't have to. I was able to make the same functionality by creating an instance of a GraphicsWindow within my plotting class, then this bypassed all of the other issues. I was able to get the class running by switching the order of GraphicsWindow and my custom class, but further complications started happening that I didn't understand.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51165348

http://stackoverflow.com/a/51057632
type: Answer
score: 1
upvote count: 1
has body: except KeyError: pytest.fail('ERROR: There are no clients using {}: {}\nExpected: {}\nEndpoint: {}'.format(device_spec, key, expected_value, endpoint), pytrace=False) raise SystemExit(1) SystemExit(1) is the main reason of loop break, which is causing the force termination of program. simply by removing it from code will work fine.
has comment: http://stackoverflow.com/comment/89108102
has comment: http://stackoverflow.com/comment/89113680
answers question: http://stackoverflow.com/q/51057447
downvote count: 0

http://stackoverflow.com/q/51150492
upvote count: 4
answer count: 2
downvote count: 0
tagged with: keyboard
possible better answer: http://stackoverflow.com/a/63799615
favorite count: 0
has title: Pyinstaller & Keyboard
has answer: http://stackoverflow.com/a/63799615
has answer: http://stackoverflow.com/a/68445006
tagged with: pyinstaller
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/68445006
has body: I'm stuck on a problem. I'm exporting code to .exe with pyinstaller. Code includes tkinter, PIL and keyboard modules. Software runs perfectly on my PC with Python, whereas on the one without Python it crashes whenever I use something linked to keyboard. Therefore, I concluded that keyboard module wasn't included properly when "converting" to .exe. I've tried including it with adding --hidden-import=keyboard in the script, but it also doesn't seem to work. Have You got any idea, how to possibly solve this and include that module into output?
score: 4

http://stackoverflow.com/a/51101524
type: Answer
has body: This is the most terrible idea ever, really. First of course because it makes code harder to read and reason about. Wait, 'folder3', where does this come from ???. Also because if two packages define a submodule with the same name, which one you'll get when importing depends on the order in your PYTHONPATH. And once you rearranged your PYTHONPATH so you get "moduleX" from "packageX" and not from "packageY", then somemone add a "moduleY" under "packageX" which shadows the "moduleY" from "packageY". And then you are screwed... But that's only the less annoying part... If you have one module using from folder1.folder2.folder3 import foo and another using from folder3 import foo, you end up with two distinct module objects (two instances of your module) in sys.modules - and all the objects defined in those modules are also duplicated (two instances, different id), and now you have a program that starts behaving in the most erratic way whenever there's some identity testing involved. And since exception handling relies on identity, if foo is an exception, depending on which instance of the module raised it and which one is trying to catch it the test will either succeed or fail with no discernable pattern. Good luck debugging this...
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51094709
has comment: http://stackoverflow.com/comment/89197314

http://stackoverflow.com/q/51144471
tagged with: indexing
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51146731
type: Question
tagged with: subplot
answer count: 1
has title: How do I index or plot datetimes after resampling so they display on a bar plot axis correctly?
downvote count: 0
has body: I want to display my third plot x-axis data in the datetime like my other two plots (see linked figure). I have used similar approaches to each graph, but resampled the third dataset to plot precipitation in a bar graph for every hour in my time period. When I originally attempted to format the date for the third plot as I did in the previous two, the x-axis labels either disappeared or the data doesn't plot correctly. In the link below, the data is displayed the way I intended. Three subplots of rainfall My timeseries data appears like this, where I'm only concerned about 'Reading' and 'Value': Reading,Receive,Value,Unit,Quality 2018-04-07 13:09:28,2018-04-07 13:09:35,0.00,in,A 2018-04-07 06:01:25,2018-04-07 06:01:35,0.04,in,A 2018-04-07 04:38:15,2018-04-07 04:38:35,0.04,in,A Here is how I achieved the correct scheme in the second plot: import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.patches as patches import matplotlib.dates as mdates import datetime as dt #read data from csv data2 = pd.read_csv('Arroyo_Corte_Madera_del_Presidio_38021_Precipitation_Accumulation_0.txt', usecols=['Reading','Value'], parse_dates=['Reading']) #set date as index data2.set_index('Reading',inplace=True) #plot data ax2 = plt.subplot(3, 1, 2) data2.plot(ax=ax2) #set ticks every 12 hours ax2.xaxis.set_major_locator(mdates.HourLocator(byhour=range(0,24,12))) plt.xticks(rotation=0, ha='center') #format date ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d\n%H:%M:%S')) ax2.legend().set_visible(False) ax2.set_title('Accumulated Rainfall\nApril 5-7, 2018') ax2.set_xlabel('') ax2.set_ylabel('Inches Since Oct 1 2017') ax2.set_ylim(17.5, 22) arrow_date2 = mdates.datestr2num('04/07/2018 04:30:00') start_date2 = mdates.datestr2num('04/07/2018 03:00:00') end_date2 = mdates.datestr2num('04/07/2018 06:00:00') text_date2 = mdates.datestr2num('04/07/2018 03:00:00') ax2.axvspan(start_date2, end_date2, 0.86, 0.97, colo…
favorite count: 0
has answer: http://stackoverflow.com/a/51146731
tagged with: datetime
tagged with: resampling
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/38294137

http://stackoverflow.com/q/51064038
has comment: http://stackoverflow.com/comment/89120798
favorite count: 0
has comment: http://stackoverflow.com/comment/89118206
has comment: http://stackoverflow.com/comment/89118141
tagged with: python
type: AnsweredQuestion
downvote count: 2
has title: Python3 index of char on String when not found
has answer: http://stackoverflow.com/a/51064113
has body: As said in the official documentation, in Python when calling the function index on a String index raises ValueError when x is not found in s I know we can test the existence of a char in a String simply like this 'c' in String, but it makes the syntax kind of akward. Is there any known implementation of the function index that would return a -1 or such an error code instead of raising an Error
type: Question
score: -2
linked to: http://stackoverflow.com/q/22190064
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/51064251
answer count: 2
has answer: http://stackoverflow.com/a/51064251
duplicate of: http://stackoverflow.com/q/22190064
upvote count: 0
accepted answer: http://stackoverflow.com/a/51064113

http://stackoverflow.com/q/51014376
type: UnansweredQuestion
tagged with: percentile
has answer: http://stackoverflow.com/a/65063266
tagged with: pandas
has comment: http://stackoverflow.com/comment/102898622
downvote count: 0
score: 17
favorite count: 0
has comment: http://stackoverflow.com/comment/112976556
type: Question
answer count: 2
tagged with: python
has title: Pandas Dataframe groupby describe 8x ~slower than computing separatly
has comment: http://stackoverflow.com/comment/110641652
tagged with: describe
has comment: http://stackoverflow.com/comment/112888817
has body: The following code summarizes numeric data using two different approaches. The first approach uses the Dataframe().describe() and passes some specific extra percentiles. The second approach separately computes the summary stats (mean, std, N), stacks it, computes the same quantiles, then appends the two and sorts by the index so the result is essentially the same as the first approach. There are some minor naming differences that we can clean up afterword's and since the summarized data is small, that is very fast. Turns out that using the describe function was about 8x slower in this example. I am looking for reasons why and perhaps suggestions on any other approaches that may speed this up even more (filters, groups, values) are all passed in from UI to a tornado service - so speed is important, as the user is waiting for results, and the data can be even larger that this example. import pandas as pd import numpy as np from datetime import datetime def make_data (n): ts = datetime.now().timestamp() + abs(np.random.normal(60, 30, n)).cumsum() df = pd.DataFrame({ 'c1': np.random.choice(list('ABCDEFGH'), n), 'c2': np.random.choice(list('ABCDEFGH'), n), 'c3': np.random.choice(list('ABCDEFGH'), n), 't1': np.random.randint(1, 20, n), 't2': pd.to_datetime(ts, unit='s'), 'x1': np.random.randn(n), 'x2': np.random.randn(n), 'x3': np.random.randn(n) }) return df def summarize_numeric_1 (df, mask, groups, values, quantiles): dfg = df[mask].groupby(groups)[values] return dfg.describe(percentiles = quantiles).stack() def summarize_numeric_2 (df, filt, groups, values, quantiles): dfg = df[mask].groupby(groups)[values] dfg_stats = dfg.agg([np.mean, np.std, len]).stack() dfg_quantiles = dfg.quantile(all_quantiles) return dfg_stats.append(dfg_quantiles).sort_index() %time df = make_data(1000000) groups = ['c1', 'c2', 't1'] mask = df['c3'].eq('H') &amp; df['c1'].eq('A') values = ['x1', 'x3'] base_quantiles = [0, .5, 1] extd_quantiles = [0.25, 0.75, 0.9] all_quantiles = base_quantile…
linked to: http://stackoverflow.com/q/63314312
has answer: http://stackoverflow.com/a/64970104
upvote count: 17
has comment: http://stackoverflow.com/comment/113016493
has comment: http://stackoverflow.com/comment/112821738
tagged with: quantile

http://stackoverflow.com/comment/89250757
type: Comment
has text: Oh you are totally correct, I just mindblowed myself. It is UTC time and BST is UTC + 1 basically. So you are absolutely correct when you meant that it is time for *UTC*. So yes. Converting from UTC to BST would be my question. :)
comment on: http://stackoverflow.com/q/51132916
score: 0
type: QuestionComment

http://stackoverflow.com/q/51031137
tagged with: bokeh
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/97758409
has body: I'd like my glyphs to change to an alpha value of 1 when hovered over. However, if I set hover_fill_alpha=1, the color for the glyphs changes to the default blue color on hover. I'm using a ColumnDataSource to determine the fill_color for the glyphs, but unfortunately when I set hover_fill_color to the very same column it turns out to be the wrong color. The proportion of hover colors overall seems to be correct, but the glyphs are being assigned the wrong hover_fill_color. So my question is how do I either set hover_fill_alpha=1 without changing hover_fill_color, or if that is inevitable then how do I set hover_fill_color to be the same as fill_color? hover = HoverTool( tooltips = [ ("val", "@values"), ("(x,y)", "($x{int}, $y{int})") ] ) plot = figure(tools=[hover, "pan, wheel_zoom, save"], active_scroll="wheel_zoom", sizing_mode="scale_both") plot.patches('xs', 'ys', source=source, view=cdsview, line_alpha=1, fill_alpha=.5, line_color="black", fill_color="fill_colors", hover_fill_alpha=1, hover_fill_color="fill_colors", hover_line_color="black") I'm using Bokeh 0.13.0, but it happens in previous versions as well. edit: I think that this might be a bug when using a view. If I remove the view, the hover_fill_color seems correct. I really need the view to work though.
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/97760654
has title: bokeh hover alpha and color
tagged with: python
score: 3
answer count: 0
upvote count: 3

http://stackoverflow.com/a/51021936
score: 0
answers question: http://stackoverflow.com/q/51021749
has comment: http://stackoverflow.com/comment/89036582
type: Answer
has body: ArithmeticSequence is not a new-style class. Check this You have 2 options: Add self to check_index. In the class, you will use it as self.check_index(key). You will need to instantiate an ArithmeticSequence class object. Add @staticmethod before check_index. You will use it as ArithmeticSequence.check_index(key)
has comment: http://stackoverflow.com/comment/89064461

http://stackoverflow.com/comment/89094555
comment on: http://stackoverflow.com/q/51051176
has text: @SimbarasheTimothyMotsi thanks but the first portion of your response wasn't the issue.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51070285
has title: Python: How do I save data even when a long running batch process crashes?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89130638
type: Question
accepted answer: http://stackoverflow.com/a/51070349
tagged with: batch-processing
answer count: 1
has answer: http://stackoverflow.com/a/51070349
score: 0
has body: I have a long running python batch process that is processing data from a REST API. In case the program crashes or terminates for some reason I want to save info about the position of my last processing so I can restart and resume. I do not want to loose that info (store it on disk and not only in RAM). How can I handle this if possible with a lightweight solution maybe without a database? Thanks Philip

http://stackoverflow.com/a/51109763
answers question: http://stackoverflow.com/q/51042841
accepted answer of: http://stackoverflow.com/q/51042841
has body: Since there's always going to be at least one TaxTotal element, I would create a new csv row for each one and go back up the tree for the preceding values. Here's an example using lxml. I added a function to make it easier to handle empty values, but any additional formatting of values I'll leave up to you. Python 3.6 from lxml import etree import csv def get_value(target_tree, xpath, namespaces): try: return target_tree.xpath(xpath, namespaces=namespaces)[0].text except IndexError: return "" tree = etree.parse("input.xml") ns = {"cac": "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", "cbc": "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", "i2": "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"} with open("output.csv", "w") as csvfile: csvwriter = csv.writer(csvfile, delimiter=";", lineterminator="\n", quoting=csv.QUOTE_MINIMAL) # Header csvwriter.writerow(["ID", "/InvoiceLine/ID", "/InvoiceLine/InvoicedQuantity", "/InvoiceLine/LineExtensionAmount", "/InvoiceLine/TaxTotal/TaxAmount", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxableAmount", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxAmount", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxCategory/ID", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxCategory/Percent", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxCategory/TaxScheme/ID", "/InvoiceLine/TaxTotal/TaxSubtotal/TaxCategory/TaxScheme/Name"]) for tax_total in tree.xpath("//cac:TaxTotal", namespaces=ns): csvwriter.writerow([get_value(tax_total, "/i2:Invoice/cbc:ID", ns), get_value(tax_total, "../cbc:ID", ns), get_value(tax_total, "../cbc:InvoicedQuantity", ns), get_value(tax_total, "../cbc:LineExtensionAmount", ns), get_value(tax_total, "cbc:TaxAmount", ns), get_value(tax_total, "cac:TaxSubtotal/cbc:TaxableAmount", ns), get_value(tax_total, "cac:TaxSubtotal/cbc:TaxAmount", ns), get_value(tax_total, "cac:TaxSubtotal/cac:TaxCategory/cbc:ID", ns), get_value(tax_total, "cac:TaxSubtotal/cac:TaxCategory/cbc:Percent", ns), get_value(tax_total, "cac:…
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89248977
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89098540
comment on: http://stackoverflow.com/a/51053362
type: AnswerComment
has text: I didn't post the question, and the person did not state the requirements very clearly. But I believe they want to call the sequence "unique" if it doesn't contain any duplicate values. Your version only checks whether the *last* number entered is a duplicate.
score: 0
type: Comment

http://stackoverflow.com/q/51067088
type: Question
has title: Removing accented words from stop words algorithm with NLTK
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to develop a simple algorithm in Python to remove stop words from a text, but I'm having problems with words that have accents. I'm using the following code: import io from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from unicodedata import normalize import sys reload(sys) sys.setdefaultencoding('utf8') stop_words = set(stopwords.words('portuguese')) file1 = open("C:\Users\Desktop\Test.txt") print("File open") line = file1.read() words = line.split() #convert the words to lower case words = [word.lower() for word in words] print("Running!") for r in words: if r not in stop_words: appendFile = open('finalText.txt','a') appendFile.writelines(" "+r) appendFile.close() print("Finished!") When running the code with the following test file: E É Á A O Ó U Ú I have this output: É Á Ó Ú It doesn't seem to recognize accentuated words, and using "setdefaultencoding" for utf-8 does not work, does anyone knows of a solution I can use to solve this problem?
tagged with: python
accepted answer: http://stackoverflow.com/a/51078244
upvote count: 1
has answer: http://stackoverflow.com/a/51078244
type: AnsweredQuestion
tagged with: nltk
score: 1

http://stackoverflow.com/comment/89273430
comment on: http://stackoverflow.com/a/51132983
type: AnswerComment
has text: Thanks for your reply, I changed according your advice, but it still doesn't work
type: Comment
score: 0

http://stackoverflow.com/comment/89072200
type: QuestionComment
has text: can you share some more working code? what have you tried and what is not working for you
comment on: http://stackoverflow.com/q/51040401
score: 0
type: Comment

http://stackoverflow.com/comment/89167242
has text: thank you BenG-TW! Isn't there a way to get the seasons without specifying the year?
comment on: http://stackoverflow.com/a/51072629
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89183450
type: AnswerComment
comment on: http://stackoverflow.com/a/51097544
type: Comment
has text: Thank you, mate appreciate it :)
score: 0

http://stackoverflow.com/comment/89069582
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51037568
score: 0
has text: I have backups, I will restore it and see what happen @DanielRoseman

http://stackoverflow.com/comment/89203736
type: QuestionComment
score: 1
has text: What does `where pip` display? Does the output make sense? (If there is a directory in the `where` output that reflects Python 3.6, you'll want to remove that from your `%PATH%`).
comment on: http://stackoverflow.com/q/51108226
type: Comment

http://stackoverflow.com/comment/89162070
type: Comment
has text: text_entry = canvas.Entry(root, textvariable=myvar) button1 = canvas.Button(root, text="Back to Home", command=mywarWritten) button1.pack() text_entry.pack()
comment on: http://stackoverflow.com/q/51086108
score: 0
type: QuestionComment

http://stackoverflow.com/q/51027493
tagged with: ctypes
accepted answer: http://stackoverflow.com/a/51033625
has body: Can ctypes wrap functions that return objects (not pointers/references) of a C++ class with a destructor? The example below segfaults when calling lib.init_point_by_value: foo.cpp: #include &lt;iostream&gt; extern "C" { using namespace std; struct Point { int x; int y; ~Point(); }; Point::~Point() { cout &lt;&lt; "Point destructor called" &lt;&lt; endl; } Point init_point_by_value(int x, int y) { cout &lt;&lt; "init_point_by_value called" &lt;&lt; endl; Point p; p.x = x; p.y = y; return p; } Point&amp; init_point_by_ref(int x, int y) { cout &lt;&lt; "init_point_by_ref called" &lt;&lt; endl; Point* p = new Point; p-&gt;x = x; p-&gt;y = y; return *p; } void cleanup_point(Point* point) { cout &lt;&lt; "cleanup_point called" &lt;&lt; endl; if (point) { delete point; } } } foo.py: import ctypes class Point(ctypes.Structure): _fields_ = [ ('x', ctypes.c_int), ('y', ctypes.c_int), ] def setup_lib(lib_path): lib = ctypes.cdll.LoadLibrary(lib_path) lib.cleanup_point.argtypes = [ctypes.POINTER(Point)] lib.init_point_by_value.argtypes = [ctypes.c_int, ctypes.c_int] lib.init_point_by_value.restype = ctypes.POINTER(Point) lib.init_point_by_ref.argtypes = [ctypes.c_int, ctypes.c_int] lib.init_point_by_ref.restype = ctypes.POINTER(Point) return lib lib = setup_lib('./foolib.so') p1 = lib.init_point_by_ref(3, 4) lib.cleanup_point(p1) # seg faults p2 = lib.init_point_by_value(5, 6) lib.cleanup_point(p2) Compile and run it with: g++ -c -fPIC foo.cpp -o foo.o &amp;&amp; g++ foo.o -shared -o foolib.so &amp;&amp; python foo.py Output: init_point_by_ref called cleanup_point called Point destructor called init_point_by_value called Segmentation fault (core dumped)
tagged with: return-by-value
has comment: http://stackoverflow.com/comment/89047452
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89050238
has answer: http://stackoverflow.com/a/51033625
tagged with: python
tagged with: destructor
tagged with: c++
type: AnsweredQuestion
has title: ctypes wrapper for function returning by value objects of a C++ class with destructor
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/89293569
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51155142
score: 1
has text: Ahh yes! That solved it! It actually was `ticket_reference`. I just took `order__order_reference` from my OrderListView and forgot to change it. Thank you!

http://stackoverflow.com/a/51125484
has body: You can use mapping template to pass requestId to lambda function https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference
downvote count: 1
has comment: http://stackoverflow.com/comment/89239198
upvote count: 0
has comment: http://stackoverflow.com/comment/89497089
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/114863783
answers question: http://stackoverflow.com/q/51105990

http://stackoverflow.com/comment/89208820
type: AnswerComment
has text: If you can reproduce secondary or tertiary or n-iary requests, then that would give you a great starting point. I would recommend focusing on the differences in the headers and attempting to reproduce the reloaded website so that you can reverse engineer the changes made to the cookies or headers. Although I'm sure you are already doing that, so I do apologize for giving a non- solution. You can always dig through their js as well, assuming it's not obfuscated.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51110680

http://stackoverflow.com/comment/89095143
comment on: http://stackoverflow.com/a/51051865
score: 0
type: AnswerComment
has text: @Xeberdee Then what's the new error message? Before you had the error message of `subprocess.CalledProcessError: Command '['C:/GUI/My', 'app/ffprobe.exe',...` so it was clearly not parsing the command with the white space correctly.
type: Comment

http://stackoverflow.com/a/76846233
answers question: http://stackoverflow.com/q/51012658
has body: The same as @Vivek Kumar's answer, just updated to use scikeras instead of keras.wrappers.scikit_learn which is defunct. I've left the defunct bits in, just commented out, and with the replacement scikeras line directly below, there are a few differences. from keras.models import Sequential from keras.layers import Dense # from keras.wrappers.scikit_learn import KerasClassifier from scikeras.wrappers import KerasClassifier from sklearn.datasets import make_classification def model(): model = Sequential() model.add(Dense(10, input_dim=20, activation='relu')) model.add(Dense(2, activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # estimator = KerasClassifier(build_fn=model, epochs=100, batch_size=5) estimator = KerasClassifier(model=model, epochs=100, batch_size=5, verbose=0) X, y = make_classification() estimator.fit(X, y) # This is what you need # estimator.model.summary() estimator.model_.summary()
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89281921
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51132249
has text: thanks sir for replying,after this correction,the code is working fine but it is not giving any output...any suggestions
score: 0

http://stackoverflow.com/q/51045402
has answer: http://stackoverflow.com/a/51047936
answer count: 1
has title: How can I return a dictionary of multiple features, from a tf.data.Dataset, created from generator?
tagged with: tensorflow-datasets
has comment: http://stackoverflow.com/comment/89086072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89086768
tagged with: python
has body: I have an example dataset like below: feature_1 feature_2 label 4 5 1 4 3 1 4 6 2 ... I have created a tf.feature_column.embedding_column for each feature (feature_1 and feature_2), so I have to return from my train_input_fn a dictionary of features, where the keys have the same name with the features. My input function is given below: def train_input_fn(features, labels, output_types, output_shapes, batch_size, feature_names): """ Provides the data pipeline for the training process. :param features: (numpy.array) A numpy array that holds the training features. :param labels: (numpy.array) A numpy array that holds the target variable. :param output_types: (tuple(tensorflow.DType)) A tuple containing the data type of each component yielded. :param output_shapes: (tuple(tensorflow.TensorShape)) A tuple containing the shape of each component yielded. :param batch_size: (int) The size of every batch. :return: (dict, int) A dictionary of key -&gt; value for every feature and the target label. """ def gen(): for f, l in zip(features, labels): yield f, l ds = tf.data.Dataset.from_generator(gen, output_types, output_shapes) # If we do repeat without any argument we actually create and infinite loop. # That is preferred, we can now control the iterations via epochs. ds = ds.repeat().batch(batch_size) feature, label = ds.make_one_shot_iterator().get_next() return {'feature': feature}, label How can I return something like: {'feature_1': x_1, 'feature_2': x_2}
tagged with: tensorflow
type: Question
tagged with: tensorflow-estimator
score: 0

http://stackoverflow.com/q/51030163
has answer: http://stackoverflow.com/a/51047666
tagged with: unsigned-integer
has title: uint8 little endian array to uint16 big endian
tagged with: endianness
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: python
score: 2
has body: In Python2.7, from an USB bulk transfer I get an image frame from a camera: frame = dev.read(0x81, 0x2B6B0, 1000) I know that one frame is 342x260 = 88920 pixels little endian, because that I read 2x88920 = 177840 (0x2B6B0) from the bulk transfer. How can I convert the content of the frame array that is typecode=B into an uint16 big endian array?
upvote count: 2
tagged with: unsigned-char
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/51114150
has body: you can use tf.TextLineReader which has option to skip headers reader = tf.TextLineReader(skip_header_lines=1)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51113982

http://stackoverflow.com/a/51052910
has body: Oversimplifying slightly, your code: with x as 1: y = 1 … translates to something like this: try: 1 = x.__enter__() y = 1 finally: 1.__exit__() Writing 1 = x.__enter__() is obviously going to raise a SyntaxError: can't assign to literal, because it doesn't mean anything to assign a new value to the literal constant 1. Doing the same thing in a with statement raises the same exception. (In old versions of Python (I think just 2.5?), the error message wasn't quite as useful, and it just said SyntaxError: invalid syntax, but the problem is the same.) Depending on what was in x, getting past the SyntaxError may well just raise a new exception, AttributeError: __enter__. Only context managers can be used in a with statement. Roughly, these are things that know how to clean up after themselves, and where it's important to get them to clean up at the end of some block of code no matter what. Files are the prototypical example: they call self.close() when you exit the block, which makes sure you don't get OS errors from having hundreds of open files lying around, or fail to flush the last write, or other such problems. For more information on with, see PEP 343, the proposal that originally added with to Python 2.5, or Understanding Python's "with" statement (from effbot). So, the question here is: what were you trying to do? If you just want to assign the value 1 to the name x, you already know how to do that, because you did it with y in the very next line: just x = 1. If you were trying to do something different… well, there probably is a way to do it, but with may well be nowhere near the right answer.
answers question: http://stackoverflow.com/q/51052807
score: 5
has comment: http://stackoverflow.com/comment/89097022
upvote count: 5
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89096887

http://stackoverflow.com/comment/89090410
score: 0
type: QuestionComment
has text: So what is the issue in your existing code?
type: Comment
comment on: http://stackoverflow.com/q/51048725

http://stackoverflow.com/a/51110281
has comment: http://stackoverflow.com/comment/89210061
has body: You can do: &gt;&gt;&gt; li=[[1,2,3],[],[2,-2],[3,2,1]] &gt;&gt;&gt; {frozenset(e) for e in li} {frozenset({1, 2, 3}), frozenset({2, -2}), frozenset()} &gt;&gt;&gt; [list(x) for x in {frozenset(e) for e in li}] [[1, 2, 3], [2, -2], []] The key is to use frozenset since a set is not hashable. Note the order may change with this method. If you want to maintain the same order, you can do: &gt;&gt;&gt; seen=set() &gt;&gt;&gt; [e for e in li if frozenset(e) not in seen and not seen.add(frozenset(e))] [[1, 2, 3], [], [2, -2]] If there is a possibility of repeated elements within the sublists, you can sort the sublists and use a representation of that: li=[[1,2,3],[],[2,-2],[3,2,1],[1,1,2,2,3],[1,2,1,2,3]] seen=set() nli=[] for e in li: re=repr(sorted(e)) if re not in seen: seen.add(re) nli.append(e) &gt;&gt;&gt; nli [[1, 2, 3], [], [2, -2], [1, 1, 2, 2, 3]] (Note: You can use tuple instead or repr if desired. Either produces a hashable immutable result)
has comment: http://stackoverflow.com/comment/89210082
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51110251
answers question: http://stackoverflow.com/q/51110251
has comment: http://stackoverflow.com/comment/89209763
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/89207743
downvote count: 0
has comment: http://stackoverflow.com/comment/89210037
score: 5

http://stackoverflow.com/comment/89268862
score: 0
type: AnswerComment
has text: The solution itself isn't much different from mine, but yeah this was the point `.total_seconds()`
comment on: http://stackoverflow.com/a/51127059
type: Comment

http://stackoverflow.com/q/51119918
type: AnsweredQuestion
score: 3
has body: I'm working with Sympy expressions that have units. Here's a trivial example: from sympy.physics.units import newton, meter atmosphere = 101325. * newton / (meter **2) In the above example, is there a concise way to get the units, i.e. newton / (meter **2) from the variable atmosphere?
type: Question
linked to: http://stackoverflow.com/q/45414404
possible better answer: http://stackoverflow.com/a/52336567
tagged with: sympy
has title: How to concisely get the units of a Sympy expression
upvote count: 3
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51138039
accepted answer: http://stackoverflow.com/a/51138039
favorite count: 0
has comment: http://stackoverflow.com/comment/89233696
has answer: http://stackoverflow.com/a/52336567
tagged with: python

http://stackoverflow.com/comment/89274228
type: Comment
has text: Good point, I'll edit my post to mention this.
comment on: http://stackoverflow.com/a/51144976
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89299478
has text: Sure, I'll upload it to my git.
comment on: http://stackoverflow.com/q/51157949
type: Comment
type: QuestionComment
score: 0

zipkin
type: Tag
tags question: http://stackoverflow.com/q/51138208
tag name: zipkin

http://stackoverflow.com/comment/89183081
type: Comment
comment on: http://stackoverflow.com/q/51090462
type: QuestionComment
has text: @ScottSkiles it displays the same thing. I have just noticed it uses the dates 01-1-1900. Even though the date is never provided.
score: 0

http://stackoverflow.com/q/51076598
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89244110
tagged with: python
tagged with: c++
tagged with: boost
has answer: http://stackoverflow.com/a/51105499
type: Question
has comment: http://stackoverflow.com/comment/89144565
score: 0
answer count: 1
has body: I have a class exported to python, in pure python, I can easily extend the dir function by this: def __dir__(self): attr = list(self.__attributesMap().keys()) return attr + dir(type(self)) so I added a dir function to my c++ class, but the question is how to get value of dir(type(self)) in c++ with boost.python?
tagged with: boost-python
has title: using boost.python, how to extend a class's __dir__ function?

http://stackoverflow.com/comment/89416085
has text: Does `chcp 65001` help?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51160183

igraph
tags question: http://stackoverflow.com/q/51157949
tags question: http://stackoverflow.com/q/51052465
type: Tag
tag name: igraph
tags question: http://stackoverflow.com/q/51102350
tags question: http://stackoverflow.com/q/51104928
tags question: http://stackoverflow.com/q/51074411
tags question: http://stackoverflow.com/q/51012429

http://stackoverflow.com/q/51140048
answer count: 2
has comment: http://stackoverflow.com/comment/89264243
has comment: http://stackoverflow.com/comment/89266690
downvote count: 0
has answer: http://stackoverflow.com/a/51141645
has title: How to get just one item from ForeignKey Model in django?
score: 1
possible better answer: http://stackoverflow.com/a/51140092
favorite count: 0
has answer: http://stackoverflow.com/a/51140092
accepted answer: http://stackoverflow.com/a/51141645
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89266868
has comment: http://stackoverflow.com/comment/89266945
type: AnsweredQuestion
has body: I have below two models in my app, class Question(models.Model): question_text = models.CharField(max_length=200) question_author = models.ForeignKey(User, on_delete=models.CASCADE) q_pub_date = models.DateTimeField('Date Question Published') def __str__(self): return self.question_text class Answer(models.Model): answer_text = models.CharField(max_length=5000) answer_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ans_auth') question = models.ForeignKey(Question, on_delete=models.CASCADE) a_pub_date = models.DateTimeField('Date Answer Published') def __str__(self): return self.answer_text I want to show latest questions on home page in a list. Each item in list will show question text and one answer out of many posted for that particular question. I am able to show question text but I am not able to find a way to get the answer item for every question item in my view below, def home(request): latest_question = Question.objects.order_by('-q_pub_date')[:15]
tagged with: django-views
has comment: http://stackoverflow.com/comment/89267115
tagged with: django-models
has comment: http://stackoverflow.com/comment/89266736
type: Question

http://stackoverflow.com/q/51092894
has comment: http://stackoverflow.com/comment/89174117
has comment: http://stackoverflow.com/comment/89174122
type: Question
type: AnsweredQuestion
tagged with: stock-data
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/89174182
accepted answer: http://stackoverflow.com/a/51093339
has title: (Python/MySQL/JSON) Not enough arguments for format string
has body: Can anybody help me figure out what I'm doing stupidly? I'm attempting to propagate an SQL table with financial data from a json file. I get the error in the title, but I can't seem to figure out where it's coming from. import json import MySQLdb open_time = 0 openp = 0 high = 0 low = 0 closep = 0 volume = 0 close_time = 0 quoteassetvol = 0 trades = 0 ignore1 = 0 ignore2 = 0 ignore3 = 0 con = MySQLdb.connect(host='localhost',user='root',db='binance_adabtc',passwd='abcde') cur = con.cursor() symbols = ["(JSON_EXTRACT('json_obj','$[i][open_time]'), (JSON_EXTRACT('json_obj','$[i][openp]'), (JSON_EXTRACT('json_obj','$[i][high]'), (JSON_EXTRACT('json_obj','$[i][low]'), (JSON_EXTRACT('json_obj','$[i][closep]'),(JSON_EXTRACT('json_obj','$[i][volume]'), (JSON_EXTRACT('json_obj','$[i][close_time]'), (JSON_EXTRACT('json_obj','$[i][quoteassetvol]'), (JSON_EXTRACT('json_obj','$[i][trades]'),(JSON_EXTRACT('json_obj','$[i][ignore1]'), (JSON_EXTRACT('json_obj','$[i][ignore2]'), (JSON_EXTRACT('json_obj','$[i][ignore3]'))"] json_file = open("C:\Users\Mike\Desktop\Binance\Binance_ADABTC_5m_1512086400000-1529971200000.json","r") json_obj = json.load(json_file) json_file.close() column_str = "(open_time, openp, high, low, closep, volume, close_time, quoteassetvol, trades, ignore1, ignore2, ignore3)" insert_str = ("%s, "*12)[:-2] final_str = "INSERT INTO Binance_ADABTC_5m_1512086400000_1529971200000 (%s) VALUES (%s)" % (column_str, insert_str) for i in range (0,178848): cur.execute(final_str,symbols) con.commit() #cnx.commit() con.close() The data from the file looks like this: [[1512086400000, "0.00001204", "0.00001209", "0.00001161", "0.00001183", "771721.00000000", 1512086699999, "9.10638040", 126, "359700.00000000", "4.22792312", "52516956.22676400"], [1512086700000, "0.00001189", "0.00001194", "0.00001183", "0.00001189", "119120.00000000", 1512086999999, "1.41575664", 44, "49016.00000000", "0.58377518", "52659721.84287900"], [1512087000000, "0.00001191", "0.00001196", "0.00001183",…
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/89174653
has comment: http://stackoverflow.com/comment/89174213
has comment: http://stackoverflow.com/comment/89174184
tagged with: http://stackoverflow.com/tag/json
tagged with: mysql
tagged with: formatting
has comment: http://stackoverflow.com/comment/89174557
downvote count: 1
has comment: http://stackoverflow.com/comment/89174433
upvote count: 0
has comment: http://stackoverflow.com/comment/89174522
has answer: http://stackoverflow.com/a/51093339

http://stackoverflow.com/a/51082355
score: 6
type: Answer
upvote count: 6
has body: Using collections.Counter with operator.itemgetter: from collections import Counter from operator import itemgetter res = Counter(map(itemgetter(0, 2), z)) print(res) Counter({(1, 2015): 4, (1, 2016): 5, (2, 2015): 4, (3, 2015): 5, (4, 2015): 4, (5, 2015): 5, (6, 2015): 4, (7, 2015): 4, (8, 2015): 5, (9, 2015): 4, (10, 2015): 4, (11, 2015): 5, (12, 2015): 4})
downvote count: 0
answers question: http://stackoverflow.com/q/51082247

http://stackoverflow.com/comment/89021720
type: QuestionComment
comment on: http://stackoverflow.com/q/51014386
type: Comment
has text: Ubuntu 16.04, yes i'm calling the export command and running flask run
score: 0

http://stackoverflow.com/comment/89166903
type: Comment
has text: Ok now I get it. What are you using to freeze your program? pyinstaller?
comment on: http://stackoverflow.com/q/51088946
score: 0
type: QuestionComment

http://stackoverflow.com/a/51075606
answers question: http://stackoverflow.com/q/51074577
score: 0
type: Answer
has body: A better approach to do the same is to download and use AWS CLI and run the command aws configure to save your access_key_id , secret_access_key and default region in your local machine and then run this python script given below : import boto3 s3 = boto3.resource('s3') bucket=s3.Bucket('bucket_name') for obj in bucket.objects.filter(Prefix='Event/'): print(obj.key)

http://stackoverflow.com/q/51117082
possible better answer: http://stackoverflow.com/a/51117281
tagged with: python
has answer: http://stackoverflow.com/a/51123881
has answer: http://stackoverflow.com/a/51117281
type: AnsweredQuestion
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/51123881
has body: scrapy shell 'https://itunes.apple.com/us/album/no-tears-left-to-cry/1374085537?i=1374087460&amp;v0=WWW-NAUS-ITSTOP100-SONGS&amp;l=en&amp;ign-mpt=uo%3D4' I wanted to get album "no tears left to cry - Single" from here, Itunes chart _ music preview page "no tears left to cry - Single / Ariana Grande" the album name's xpath is this : //*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1 and i tried to response.xpath('//*[@id="ember653"]/section[1]/div/div[2]/div[1]/div[2]/header/h1') but result was [] how can I get album informations from this wepsite?
score: 0
has title: scrapy shell xpath returns empty list from itunes.apple.com
answer count: 2
linked to: http://stackoverflow.com/q/50884181
tagged with: xpath

http://stackoverflow.com/a/63304306
answers question: http://stackoverflow.com/q/51136741
type: Answer
has body: First make sure your ingress controller in running, to check that kubectl get pods -n ingress-nginx if you dont find any pods running you need to deploy the kubernetes ingress you can do that by kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/provider/cloud/deploy.yaml. If you have installed ingress controller correctly, then just apply the yaml below, you need to have selector in your deployment so that the deployment can manage the replicas, apart from that you dont need to expose a node port as you are going to access your app through load balancer. apiVersion: v1 kind: Service metadata: name: test-app labels: app: test-app spec: type: LoadBalancer ports: - name: http port: 80 protocol: TCP targetPort: 8080 selector: app: test-app --- apiVersion: apps/v1 kind: Deployment metadata: labels: app: test-app name: test-app spec: selector: matchLabels: app: test-app replicas: 1 template: metadata: labels: app: test-app spec: containers: - name: test-app image: arycloud/flask-svc imagePullPolicy: Always ports: - containerPort: 8080 --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: test-ingress annotations: kubernetes.io/ingress.class: "nginx" spec: rules: - http: paths: - path: / backend: serviceName: frontend servicePort: 80
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/89282145
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51149055
has text: This has nothing to do with "variable variables". This man just want to print the name of the variable.

http://stackoverflow.com/comment/89121414
has text: Good spot. How exactly do I pull up a readable copy of cv_results_?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51065629

http://stackoverflow.com/a/51179555
score: 15
type: Answer
upvote count: 15
answers question: http://stackoverflow.com/q/51073532
downvote count: 0
has body: A pure python solution could be using the on_form_prefill callback function that admin provides, and it's only run in the edit view. You wouldn't need form_widget_args in that case. You could have something like this to edit the form dynamically, making that field read only: class MyView(ModelView): def on_form_prefill(self, form, id): form.title.render_kw = {'readonly': True}

http://stackoverflow.com/comment/89314954
has text: Just putting it out there, it could be that it is running from `/Users/jbennett8/anaconda3/bin/snips-nlu`, try using a full path to the files and see if that works?
comment on: http://stackoverflow.com/q/51165856
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51112711
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/51112855
answer count: 1
has title: Protect image path in Flask API
type: UnansweredQuestion
tagged with: python
type: Question
has body: Im making a web application using flask api. When a user is created, a folder is created for them on the file system. They use this for uploading their own images. When uploding the image path is stored in the db. My problem is that this image path should only be allowed for that specific user. The paths gets returned by the api, but If known everyone can request the image src. How can i restrict that to the owner only?

http://stackoverflow.com/comment/89304789
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51160386
has text: @Kevin, i tried with torch.Tensor(2,3) too. i mentioned that in the question too.

http://stackoverflow.com/comment/89089090
type: QuestionComment
has text: What is the point of doing ` a = b` here? Why are you doing that, after you create both a and b? If you didn't do this, you would have the output you want. But with it, I can't understand what you are trying to do
score: 0
comment on: http://stackoverflow.com/q/51048839
type: Comment

http://stackoverflow.com/comment/89228799
comment on: http://stackoverflow.com/q/51121661
has text: Possible duplicate of [Django Filters - or?](https://stackoverflow.com/questions/739776/django-filters-or)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51144098
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89272687
has comment: http://stackoverflow.com/comment/89272431
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51144274
downvote count: 3
has title: Wondering if it's possible to program something that can deal with the massive number of possible combinations in a deck of 52 cards
type: Question
score: -1
has comment: http://stackoverflow.com/comment/89272531
has body: They say there are 8.06e+67 different combinations that can be made from a deck of 52 cards, a number that's really too big for a human mind to comprehend, and (I'm assuming) too big for any computer to handle as well. But my question is, if you establish a hierarchy of cards in some code, e.g. from A-2-3-4-5-6-7-8-9-10-J-Q-K, and then D,H,S,C for the suits, is it possible to write something that will tell you, for example, what the combination #45,000,000,000,000,000,000,000 is without having to run through all of them to get there? Or, if you could feed in a specific combination of 52 cards, is there a way to quickly find out what its number would be without having to run through all of them?
answer count: 2
has comment: http://stackoverflow.com/comment/89272693
has answer: http://stackoverflow.com/a/51144274
has comment: http://stackoverflow.com/comment/89272591
possible better answer: http://stackoverflow.com/a/51144349
favorite count: 0
has answer: http://stackoverflow.com/a/51144349

http://stackoverflow.com/comment/89273910
has text: Use `d = {"m":1,"d":5,"y":2000}` `print("/".join(map(str, list(d.values()))))`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51144717

http://stackoverflow.com/comment/89318396
type: Comment
type: QuestionComment
has text: Then as suggested by others, please provide full objects view used(after removing sensitive data). As concatenation what you gave here if rendered in Python 3.6.5 gave no such error even if port is initialized as an int value
comment on: http://stackoverflow.com/q/51167397
score: 0

http://stackoverflow.com/comment/89082457
score: 0
type: Comment
has text: Yes I have edited it and mentioned the same @VincenzoLavorini
type: QuestionComment
comment on: http://stackoverflow.com/q/51045038

http://stackoverflow.com/comment/89100702
type: Comment
comment on: http://stackoverflow.com/a/51054849
score: 0
has text: May I ask the difference of data type or data structure is judged by their complexity? Or there is normally not much difference?
type: AnswerComment

http://stackoverflow.com/a/51166457
accepted answer of: http://stackoverflow.com/q/51166000
type: Answer
answers question: http://stackoverflow.com/q/51166000
score: 0
has body: I tried reproducing your results with a random (discrete) signal like so: import numpy as np import pyw x = np.random.randint(0,100,500) y = pywt.wavedec(x, 'db12', level=2) (e,f) = pywt.dwt(x, 'db12') I noticed two things: For a 1D signal, wavedec returns more than two coefficient arrays, as also mentioned in the docs. Similarly, the dwt function does not know the keyword level=, but works just fine with the command specified above. Hope that helps
type: AcceptedAnswer

http://stackoverflow.com/q/51140575
upvote count: 2
has answer: http://stackoverflow.com/a/51140636
type: Question
accepted answer: http://stackoverflow.com/a/51140636
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a large csv file where I have filtered out the rows I want and created smaller more manageable data frames (called 'CL'). Each row has a Contract Month and Contract Year both in Int64 (I believe). I want to create a column combining the two in a date format (e.g., MM-YYYY) and having difficulty. I have tried both extracting the columns to pandas series and converting to string series.to_string as well as the individual columns with CL['CONTRACT MONTH']= CL['CONTRACT MONTH'].astype(str) The latter method gives me a message "... 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" A little over my head with this (just learning Python) and was hoping for some help.
tagged with: string
favorite count: 0
tagged with: series
has comment: http://stackoverflow.com/comment/89265949
tagged with: python
type: AnsweredQuestion
score: 2
has title: concatenating Columns within a dataframe

http://stackoverflow.com/q/51075601
accepted answer: http://stackoverflow.com/a/51075737
possible better answer: http://stackoverflow.com/a/51093272
score: 0
has answer: http://stackoverflow.com/a/51093272
linked to: http://stackoverflow.com/q/19158339
tagged with: python
has body: I was trying to solve a homework question that involves processing an order based on a list of tuples which contain the name of item, quantity, and price per item. The total is calculated by taking the 1st and 2nd indices of each tuple in the list after the item is removed and then summing the products for each tuple in the list remaining. I have to do these things within the process_order() function, but I keep on running into issues when I'm trying to remove one tuple from the list because the while loop keeps running and deletes all the elements always making the total equal to 0. The starting code is like this: total = 0 def process_order(x_list): x = [("oranges", 4, 3.22),("gummy bears",1,1.99),("sour bites", 3, 2.33), ("antacid", 1, 5.33)] while(len(x)&gt;0): process_order(x) print("total price: ", total)
type: AnsweredQuestion
type: Question
has title: Deleting an element from a list of tuples and then calculating a total price based on elements within each tuple
answer count: 2
has answer: http://stackoverflow.com/a/51075737

http://stackoverflow.com/q/51098026
has title: Import error while running py.test
has comment: http://stackoverflow.com/comment/89235821
tagged with: python
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/89234284
accepted answer: http://stackoverflow.com/a/51103675
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89234600
has body: When I tried to run pytest I get an error, this is my project structure: slots_tracker/ README.md development.txt requirements.txt tasks.py venv/ slots_tracker/ __init__.py conf.py db.py expense.py server.py swagger.yml test_api.py This is my test file: from expense import create from conf import PayMethods def test_create_new_expense(): response = create(dict(amount=200, desc='Random stuff', pay_method=PayMethods.Visa.value)) # We got a success code assert response[1] == 201 when I run pytest with: pytest I get this error: ModuleNotFoundError: No module named 'expense' If I run pytest with: python -m pytest I don't get any error, also I can run my app with and don't get any import error: python server.py I also noties that if I remove the __init__.py file I can run pytest with only: pytest any iade on I can fix this? removing the __init__.py doesn't look like the 'right' solution becuase I'm building a package so it should have an __init__.py file. I'm running on a Mac with Python 3.6.5 in a virtual env.
downvote count: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/89189414
has answer: http://stackoverflow.com/a/51103675
type: Question
upvote count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/89220430
answer count: 1
has comment: http://stackoverflow.com/comment/89230262
favorite count: 0
tagged with: importerror

http://stackoverflow.com/comment/89284110
type: QuestionComment
comment on: http://stackoverflow.com/q/51148505
has text: anyway i didn't get my answer
score: 0
type: Comment

http://stackoverflow.com/comment/89279676
has text: After running this script, I got the following error: `selenium.common.exceptions.WebDriverException: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 127 ` I am pretty sure that libfontconfig is downloaded. So there is no problem of libraries. Then what is the error? Is there anything I am missing in terms of downloads?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51124325
type: Comment

http://stackoverflow.com/comment/89199646
type: QuestionComment
has text: Consider storing your data in a list, not a string.
score: 0
comment on: http://stackoverflow.com/q/51106304
type: Comment

http://stackoverflow.com/comment/89185588
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51098303
has text: @Hielke Walinga Can you share the sample data?

http://stackoverflow.com/comment/89107327
type: QuestionComment
comment on: http://stackoverflow.com/q/51057280
has text: found sulotion, used eval()
score: 0
type: Comment

http://stackoverflow.com/comment/89254139
comment on: http://stackoverflow.com/q/51134981
has text: When i run your sequence of commands i get text ... all on one line `0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89274141
has text: The best duplicate questions are about tkinter rather than PyQt. I also found one that's about the exact same issue in the `defaultdict` constructor, for variety, but nothing specifically about PyQt. So please take a look and make sure you understand the answers even though the `TypeError` you get looks a bit different; if not, I'm sure we can find something Qt-specific (even if the explanation isn't as good).
type: Comment
comment on: http://stackoverflow.com/q/51144903
type: QuestionComment
score: 0

http://stackoverflow.com/q/51132161
downvote count: 0
accepted answer: http://stackoverflow.com/a/51132185
has title: Count most frequent group with Nan values
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51132375
tagged with: python
has answer: http://stackoverflow.com/a/51132375
favorite count: 0
type: Question
upvote count: 2
answer count: 3
has body: basically I would like to count number of the most frequent item grouped by 2 variables. I use this code: dfgrouped = data[COLUMNS.copy()].groupby(['Var1','Var2']).agg(lambda x: stats.mode(x)[1]) This code works, but does not work on columns that have Nan values, since NaN values are float and others are str. So this error is shown: '&lt;' not supported between instances of 'float' and 'str' I would like to omit NaN values and count mode for the rest. So str(x) is not a solution. And scipy.stats.mode(x, nan_policy='omit') does not work neither with an error: TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Could you please give me an advice how to deal with that. Thanks
has answer: http://stackoverflow.com/a/51132372
tagged with: dataframe
tagged with: scipy
has answer: http://stackoverflow.com/a/51132185
score: 2

http://stackoverflow.com/a/51166038
has comment: http://stackoverflow.com/comment/89316663
has comment: http://stackoverflow.com/comment/89316424
has comment: http://stackoverflow.com/comment/89317264
has comment: http://stackoverflow.com/comment/89316680
has comment: http://stackoverflow.com/comment/89316729
downvote count: 0
has comment: http://stackoverflow.com/comment/89316828
has comment: http://stackoverflow.com/comment/89316436
score: 2
has comment: http://stackoverflow.com/comment/89316641
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89317227
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51165854
type: Answer
answers question: http://stackoverflow.com/q/51165854
has body: I think need if MultiIndex also in index first check notna of all values, then check at least one per first level of MultiIndex in columns by DataFrameGroupBy.any and last count Trues by sum: print (df.index) MultiIndex(levels=[[101, 102], [28, 30]], labels=[[0, 1], [1, 0]]) df = df.notna().groupby(axis=1, level=0).any().sum(axis=1) #oldier pandas versions #df = df.notnull().groupby(axis=1, level=0).any().sum(axis=1) If there is no MultiIndex in index add drop for remove info level: print (df.index) RangeIndex(start=0, stop=2, step=1) s = df.drop('info', level=0, axis=1).notnull().groupby(axis=1, level=0).any().sum(axis=1) print (s) 0 2 1 3 dtype: int64 And if need create column by position use insert: df.insert(2, ('info','count'), s) print (df) info '2002' '2003' '2004' 'PID' 'Age' count 't1' 't2' 't1' 't2' 't1' 't2' 0 101 30 2 NaN 2 2 1.0 NaN NaN 1 102 28 3 2.0 5 1 NaN 10.0 100.0

http://stackoverflow.com/a/51061094
type: Answer
accepted answer of: http://stackoverflow.com/q/51058479
has body: After you create the plot, you can set the axes to be log scale, using matplotlib's ax.set_xscale('log') and ax.set_yscale('log'). In this case, we need to get the axis from the JointGrid created by jointplot. If you catch the JointGrid returned as g, then the joint axis is g.ax_joint. For example: g = sns.jointplot(x="predictions", y="targets", data = calibration_data, kind="reg", logx=True, ) g.ax_joint.set_xscale('log') g.ax_joint.set_yscale('log')
score: 19
upvote count: 19
has comment: http://stackoverflow.com/comment/89115195
answers question: http://stackoverflow.com/q/51058479
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89263075
comment on: http://stackoverflow.com/a/51139316
type: AnswerComment
has text: Thank you for your answer, we are really insterested in testing the new features, are there any information on how long it will take till Anaconda has released the required packages?
type: Comment
score: 1

http://stackoverflow.com/comment/89261913
type: QuestionComment
has text: What have you researched, tried, iterated through, etc. prior to asking this question? If you suspect it is a token issue, what have you done to confirm or deny that assertion?
comment on: http://stackoverflow.com/q/51138791
score: 0
type: Comment

http://stackoverflow.com/a/58917859
has body: In my case it was missing bootstrap files from static/admin|css|js
answers question: http://stackoverflow.com/q/51053578
type: Answer
downvote count: 1
upvote count: 0
score: -1

http://stackoverflow.com/q/51021292
has answer: http://stackoverflow.com/a/51022882
has answer: http://stackoverflow.com/a/51021440
upvote count: 2
tagged with: range
has answer: http://stackoverflow.com/a/51021456
tagged with: python
score: 2
has body: In the code below I try to see if the next item of the given list is opposite to the previous one (i.e "North" &amp; "South" or "East" &amp; "West"). Of course, this will raise an IndexError once we reach the last item of the list. However, I have carefully delimited the for-loop so it stops before reaching the last index. def dirReduc(arr): for i in range(len(arr)-1): if arr[i] == "NORTH" and arr[i+1] == "SOUTH": arr.remove("NORTH"), arr.remove("SOUTH") elif arr[i] == "SOUTH" and arr[i+1] == "NORTH": arr.remove("SOUTH"), arr.remove("NORTH") elif arr[i] == "WEST" and arr[i+1] == "EAST": arr.remove("WEST"), arr.remove("EAST") elif arr[i] == "EAST" and arr[i+1] == "WEST": arr.remove("EAST"), arr.remove("WEST") return arr Could anyone please explain to my why this still raises IndexError: list out of range? Here is a sample input: ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"].
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51021400
has title: Python list index out of range, even after delimiting the indexes
type: Question
has comment: http://stackoverflow.com/comment/89035323
possible better answer: http://stackoverflow.com/a/51021415
tagged with: index-error
tagged with: arrays
has answer: http://stackoverflow.com/a/51021415
answer count: 6
has answer: http://stackoverflow.com/a/51034739
downvote count: 0
has answer: http://stackoverflow.com/a/51021400
favorite count: 0

http://stackoverflow.com/q/51082504
tagged with: module
has comment: http://stackoverflow.com/comment/89153657
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51082582
downvote count: 0
has answer: http://stackoverflow.com/a/51082709
answer count: 2
has comment: http://stackoverflow.com/comment/89153570
favorite count: 0
has title: OpenCV install on Python 3.6: ModuleNotFoundError
has body: I am getting the following error when using import cv2: ModuleNotFoundError: No module named 'cv2' My version of Python is 3.6 64 bit. I have downloaded the whl file to install it via pip manually, and have also installed it with pip install opencv-python however I still get ModuleNotFoundError. pip outputs Requirement already satisfied: opencv-python in c:\...\python36\site-packages Help would be much appreciated.
has comment: http://stackoverflow.com/comment/89153726
type: UnansweredQuestion
tagged with: pip
tagged with: python

http://stackoverflow.com/q/51037475
has comment: http://stackoverflow.com/comment/89069939
downvote count: 0
linked to: http://stackoverflow.com/q/51040834
answer count: 1
has comment: http://stackoverflow.com/comment/89074306
score: 1
has body: I am working on Ubuntu 16.04. I downloaded spaCy using conda and am working on jupyter notebook. I tried python -m spacy download en which gives the following error: /home/nikita/anaconda3/bin/python: No module named spacy.main; 'spacy' is a package and cannot be directly executed So I tried python -m spacy.en.download which gives these errors: Traceback (most recent call last): File "/home/nikita/anaconda3/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 964, in send self.connect() File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 1392, in connect super().connect() File "/home/nikita/anaconda3/lib/python3.6/http/client.py", line 936, in connect(self.host,self.port), self.timeout, self.source_address) File "/home/nikita/anaconda3/lib/python3.6/socket.py", line 724, in create_connection raise err File "/home/nikita/anaconda3/lib/python3.6/socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/nikita/anaconda3/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/home/nikita/anaconda3/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/nikita/anaconda3/lib/python3.6/site-…
favorite count: 0
has comment: http://stackoverflow.com/comment/89072391
has comment: http://stackoverflow.com/comment/89067627
has title: spaCy language module not downloading
has answer: http://stackoverflow.com/a/51041767
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/89071477
tagged with: spacy
type: Question
accepted answer: http://stackoverflow.com/a/51041767

http://stackoverflow.com/q/51062412
favorite count: 0
has comment: http://stackoverflow.com/comment/89115467
has comment: http://stackoverflow.com/comment/89115486
has title: np.random.seed need to be called every time
linked to: http://stackoverflow.com/q/21494489
has body: Following two version code should have given the same output. Looks like np.random.seed need to be called every time. Is it correct? Is there any way to set seed once so that same random number generated everytime np.random.seed(0) for _ in range(10): print(np.random.randint(low=1, high=100)) Output: 45 48 65 68 68 10 84 22 37 88 for _ in range(10): np.random.seed(0) print(np.random.randint(low=1, high=100)) Output: 45 45 45 45 45 45 45 45 45 45
tagged with: python
has answer: http://stackoverflow.com/a/51062532
has comment: http://stackoverflow.com/comment/89115112
has comment: http://stackoverflow.com/comment/89114546
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/89114682
has comment: http://stackoverflow.com/comment/89114559
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51062532
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89115012
has comment: http://stackoverflow.com/comment/89114736
answer count: 1
score: 1

http://stackoverflow.com/comment/89189635
type: Comment
has text: What is expected output? New column filled by `3` ? Or Series with `1` because only one value `6` in `MAX_Value` ?
score: 0
comment on: http://stackoverflow.com/q/51100921
type: QuestionComment

http://stackoverflow.com/a/51117023
score: 3
answers question: http://stackoverflow.com/q/51116967
downvote count: 0
type: Answer
has body: Here in you code bar is the reference to some list located in memory. When you use bar = [], the variable bar becomes associated with a new (empty) list. When you use bar.clear(), you modify current list. Speaking generally, this means that lists in Python are passed by reference and not by value. You can read more about it here.
upvote count: 3

http://stackoverflow.com/q/51017294
score: 1
tagged with: web-applications
upvote count: 1
accepted answer: http://stackoverflow.com/a/51037906
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/59813510
type: Question
has title: Reading timestamps from a txt.file and plotting them on X- axis with matplotlib (Web-server)
answer count: 2
has answer: http://stackoverflow.com/a/59813510
downvote count: 0
tagged with: web
has answer: http://stackoverflow.com/a/51037906
favorite count: 0
tagged with: python
has body: I have created a web application with Python and Pyramid that fetches the latest email from gmail, saves the data to a file and then plots the data with matplotlib and converts it into a html string with mpld3. I currently have the data in following form in my emails: 17 25 18 25 19 25 20 26 I have no issues plotting this data. However, I would like to plot the data in the same form, but with timestamps, like this: 25-06-2018 9:11 25 25-06-2018 9:12 25 25-06-2018 9:13 25 ... I've tried converting the data to datetime format, but with no success. Here is my code: from pyramid.config import Configurator from pyramid.response import Response import email import getpass import imaplib import os import re import numpy as np import matplotlib.pyplot as plt, mpld3 def imaptest(request): m = imaplib.IMAP4_SSL('imap.gmail.com') m.login('email@gmail.com', 'password') m.list() m.select('inbox') result, data = m.uid('search', None, 'UNSEEN') i = len(data[0].split()) #space separate string for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = m.uid('fetch', latest_email_uid, '(RFC822)') raw_email = email_data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) save_string = str('C:\Email\mail1' + str(x) + '.txt') myfile = open(save_string, 'a') myfile.write(str(body)) myfile.close else: continue with open('C:\Email\mail10.txt') as f: lines = f.readlines() x = [int(line.split()[0]) for line in lines] y = [int(line.split()[1]) for line in lines] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title('Test Graph') ax1.set_xlabel('Time') ax1.set_ylabel('Temperature') plt.plot(x,y) # Print as HTML return Response( mpld3.show() ) config = Configurator() config.add_route('imaptest', '/imaptest') config.add_route('landingpage', '/landingpage') config.add_view(landingpage, route_name='lan…

http://stackoverflow.com/q/51036156
tagged with: python-2.7
answer count: 2
has body: I get s when trying to parse a web page by readability(Python 2.7 on Windows 10, Sublime Text 2/cmd) &gt;&gt;&gt; import requests &gt;&gt;&gt; from readability import Document &gt;&gt;&gt; &gt;&gt;&gt; response = requests.get('http://www.gamersky.com/news/201806/1064930.shtml') &gt;&gt;&gt; doc = Document(response.text.encode("utf-8")) &gt;&gt;&gt; print doc.title() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'gbk' codec can't encode character u'\xe3' in position 0: illegal multibyte sequence &gt;&gt;&gt; print doc.title().encode("utf-8") lots of messy codes &gt;&gt;&gt; print doc.title().encode("utf-16") lots of messy codes &gt;&gt;&gt; print doc.title().encode("gbk") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'gbk' codec can't encode character u'\xe3' in position 0: illegal multibyte sequence I found I can never print out doc.title(), so I looked into doc.title() by running s = repr(doc.title()) print type(doc.title()) print s The result is very strange &lt;type 'unicode'&gt; u'\xe3\x80\x8a\xe5\xa5\x87\xe5\xbc\x82\xe4\xba\xba\xe7\x94\x9f\xe3\x80\x8b\xe5\x9b\xa2\xe9\x98\x9f\xe6\x96\xb0\xe4\xbd\x9c\xe3\x80\x8a\xe8\xb6 \xe8\x83\xbd\xe9\x98\x9f\xe9\x95\xbf\xe3\x80\x8b\xe5 \x8d\xe8\xb4\xb9\xe4\xb8\x8b\xe8\xbd\xbd \xe5\xb0\x8f\xe7\x94\xb7\xe5\xad\xa9\xe7\x9a\x84\xe8\x8b\xb1\xe9\x9b\x84\xe6\xa2\xa6\xe6\x83\xb3 _ \xe6\xb8\xb8\xe6\xb0\x91\xe6\x98\x9f\xe7\xa9\xba GamerSky.com' It seem that s is actually encoded in multibytes, because when I run print '\xe3\x80...' And it prints 《奇异人生》团队新作《? 能队长》? ?费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com Where the accurate title is 《奇异人生》团队新作《超能队长》免费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com Though there are some characters still missing, but the result convince me that the \xe3 should not be represented as a unicode form. After some searching, I found the following code helps, but there are still some missing characters. &gt;&gt;&gt; print s…
downvote count: 0
tagged with: unicode
favorite count: 0
accepted answer: http://stackoverflow.com/a/51036315
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/51036265
type: Question
has answer: http://stackoverflow.com/a/51036315
has answer: http://stackoverflow.com/a/51036265
has title: How can I decode this string which is represented as unicode?
tagged with: python-unicode

http://stackoverflow.com/a/51072757
upvote count: 2
type: AcceptedAnswer
has body: Using a for loop with list.append. To convert a list to an array is trivial, i.e. np.array(L). d = {"k": {"k1": 'v1',"k2": 'v2',"k3": 'v3'}} keys, values = [], [] for k1, v1 in d.items(): for k2, v2 in v1.items(): keys.append(k1+k2) values.append(v2[0][0]) print(keys, values, sep='\n') ['kk1', 'kk2', 'kk3'] ['v1', 'v2', 'v3']
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51067949
answers question: http://stackoverflow.com/q/51067949

azure
tags question: http://stackoverflow.com/q/51044013
tags question: http://stackoverflow.com/q/51143378
tags question: http://stackoverflow.com/q/51043010
tags question: http://stackoverflow.com/q/51118110
tags question: http://stackoverflow.com/q/51153543
tags question: http://stackoverflow.com/q/51145124
tags question: http://stackoverflow.com/q/51101459
type: Tag
tags question: http://stackoverflow.com/q/51088145
tags question: http://stackoverflow.com/q/51138004
tags question: http://stackoverflow.com/q/51138152
tags question: http://stackoverflow.com/q/51013775
tags question: http://stackoverflow.com/q/51133067
tags question: http://stackoverflow.com/q/51129758
tag name: azure
tags question: http://stackoverflow.com/q/51166611
tags question: http://stackoverflow.com/q/51068964
tags question: http://stackoverflow.com/q/51160000
tags question: http://stackoverflow.com/q/51141674

http://stackoverflow.com/q/51049117
has comment: http://stackoverflow.com/comment/89089663
answer count: 2
has body: I have a dictionary where each key corresponds to a list with the same number of values. I am treating each list as a "column". Using the values in each list, I am trying to write a linear approximation function. It works except when I run into the problem of a value repeating in a list. When I use indexof, it returns a y value that corresponds to the first occurrence of the x value passed in and not the actual y value that is at the same index in it's own list as the x value's index in it's respective list. Do I change my dictionary into a numpy matrix? Or is there a way to do this using a dictionary. def calc_target(x1, x2, type1, type2, X): """Uses linear approximation to return a calculated value for the passed in type using a target value. Keyword arguments: x1 -- first x value x2 -- second x value type1 -- type of value to be calculated type2 -- type of value passed in X -- target value """ y2 = float(data[type1][data[type2].index(str(x2))]) y1 = float(data[type1][data[type2].index(str(x1))]) print 'X:' print x1 print x2 print 'Y:' print y1 print y2 slope = (y2 - y1)/(x2 - x1) print slope return slope * (X - x1) + y1 For example, if my x values are 3 and the second 2 in the list corresponding to key 2, how can I make sure I'm getting 21 as the y value for 2 and not 24. Since if I use indexof, it will just return the corresponding value at the first instance of 2 which will be 24 and not 21.
has comment: http://stackoverflow.com/comment/89089418
score: 0
tagged with: matrix
has answer: http://stackoverflow.com/a/51049387
accepted answer: http://stackoverflow.com/a/51049387
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/51162094
has title: How can I access the elements of a "row" from a python dictionary without using numpy array
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51162094
type: Question

http://stackoverflow.com/comment/89036046
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51020497
has text: Same behavior...
score: 0

http://stackoverflow.com/comment/89162551
type: QuestionComment
has text: (Edit). Not quite. appending only worked with numpy.save, but that stores header information within the file (which I can't read with the software we have to use for analyzing the data). Size of the file is not the problem. But I cannot reopen and save the file anytime I append it. That would take way too long.
type: Comment
comment on: http://stackoverflow.com/q/51086704
score: 0

http://stackoverflow.com/a/78286274
downvote count: 1
has body: Set the host IP to 0.0.0.0 which means listen on all addresses. Next, add a line in the /etc/hosts file pointing to your public IP address and assign it to your domain e.g. &lt;your's public IP address www.exapmle.com&gt;. After you have opened the hosts file, also add your local IP address and the hostname of server machine e.g. &lt;192.168.1.21 ServerHostname&gt;. This will save you time in the future.
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/51045911
type: Answer

http://stackoverflow.com/comment/89240999
comment on: http://stackoverflow.com/a/51127231
score: 0
type: AnswerComment
type: Comment
has text: Nicely translated to Pandas! :-)

http://stackoverflow.com/a/51032558
has comment: http://stackoverflow.com/comment/89090463
has comment: http://stackoverflow.com/comment/89089879
upvote count: 2
has comment: http://stackoverflow.com/comment/89089548
has comment: http://stackoverflow.com/comment/89088247
has comment: http://stackoverflow.com/comment/89089514
has comment: http://stackoverflow.com/comment/89096133
has comment: http://stackoverflow.com/comment/89091629
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89092345
has comment: http://stackoverflow.com/comment/89086861
type: Answer
accepted answer of: http://stackoverflow.com/q/51031691
has comment: http://stackoverflow.com/comment/89089715
score: 2
has comment: http://stackoverflow.com/comment/89078832
downvote count: 0
answers question: http://stackoverflow.com/q/51031691
has body: I might be wrong with syntaxes ... but this should give you a general idea. Also, you can optimize it further by vectorization. I have simply put your loss function as it is. N is the batch size. def f(C, I, U, N): loss = 0 for i in range(N): sum_ = 0 for k in range(N): sum_ += I[i,k] * tf.exp(d(u[i]-u[k]) loss += C[i]*tf.log(sum) return loss loss = f(C,I,U, batch_size)

http://stackoverflow.com/comment/112976556
type: Comment
comment on: http://stackoverflow.com/q/51014376
has text: `count` is different than `len`, I believe. `len` will give you the total number of rows. `count` returns the number of non-null values,
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89157497
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51065493
has text: Thanks, I have given up the idea of clipboard altogether, and now I am using the stored images for retrieval. Acturally, I need all this stuff for OCR function. Almost succeeded in writing one in python.

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51112168
tags question: http://stackoverflow.com/q/51088698
tags question: http://stackoverflow.com/q/51111591
tags question: http://stackoverflow.com/q/51054082
type: Tag

http://stackoverflow.com/comment/89224631
score: 1
has text: I've seen this from the website. I want to extract decision rules themselves (like the first solution you gave, but not as an image). For eg: if I want to get to the green node on level 2 (from the top) which has petal length <= 4.95, then given the node id of that node, I wanted to get: petal_length <= 2.45 (False), petal_width <= 1.75 (True), petal_length <=4.95 (i.e the combinations of rules from root to that node). I want this as output of my program, not the graphviz image (since the decision tree I'm getting is very big and looking at the graphviz output won't help me in that case).
comment on: http://stackoverflow.com/a/51118570
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51043909
has body: I am trying to make a for loop that prints out every user in my database to my website page... the only problem is that the attribute "objects" refuses to register and I do not understand the problem... def index(request): all_users = UserInfo.objects.all() context = {'all_users':index} for user in all_users: url = '/index/' + str(user.id) + '/' # html = '&lt;a href="' + url + '"&gt;' + all_users + '&lt;/a&gt;&lt;br&gt;' return render(request, 'userData/allUsers.html', context) That is my code, and the error is "Unresolved attribute reference 'objects'". class UserInfo(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) name = "User:" + str(first_name) + " " + str(last_name) + "." SERVER_ROLE = ( ('creator', 'CREATOR'), ('admin', 'ADMIN'), ('moderator', 'MODERATOR'), ('normie', 'NORMIE'), ) role = models.CharField(max_length=10, choices=SERVER_ROLE, default='normie') This is the class that "UserInfo" relates to; if you need any more of my code I can add it to the question. Traceback (most recent call last): File "/Users/enzoromano/DiscordSite/DiscordBot/userData/views.py", line 3, in &lt;module&gt; from .models import UserInfo ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
has comment: http://stackoverflow.com/comment/89080182
has comment: http://stackoverflow.com/comment/89078900
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51044341
possible better answer: http://stackoverflow.com/a/51044400
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89079068
has comment: http://stackoverflow.com/comment/89079640
has comment: http://stackoverflow.com/comment/89079521
has comment: http://stackoverflow.com/comment/89079559
has comment: http://stackoverflow.com/comment/89079450
has title: Python objects.all command not registering?
type: Question
has comment: http://stackoverflow.com/comment/89079536
has comment: http://stackoverflow.com/comment/89079757
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51044341
has answer: http://stackoverflow.com/a/51044400

http://stackoverflow.com/comment/89100826
has text: Thank you very much for your response, I edited and inserted that lines but I get the same error but different array shape error in dataType ------ raise Exception('array shape must be (N,) or (N,2); got %s instead' % str(obj.shape)) Exception: array shape must be (N,) or (N,2); got (2L, 383924L) instead. Unfortunately maybe plotting in PyQtGraph is different in matplotlib? I'm really new to plotting and have to discover this for my project but I'm stuck.
type: AnswerComment
comment on: http://stackoverflow.com/a/51032990
score: 0
type: Comment

communication
tag name: communication
type: Tag
tags question: http://stackoverflow.com/q/51155345

time-series
tags question: http://stackoverflow.com/q/51022256
type: Tag
tags question: http://stackoverflow.com/q/51011727
tags question: http://stackoverflow.com/q/51154383
tags question: http://stackoverflow.com/q/51060216
tags question: http://stackoverflow.com/q/51139888
tags question: http://stackoverflow.com/q/51048895
tag name: time-series
tags question: http://stackoverflow.com/q/51063282
tags question: http://stackoverflow.com/q/51118345
tags question: http://stackoverflow.com/q/51094474
tags question: http://stackoverflow.com/q/51018536
tags question: http://stackoverflow.com/q/51104911
tags question: http://stackoverflow.com/q/51042474
tags question: http://stackoverflow.com/q/51027435

http://stackoverflow.com/a/51141752
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: You can create a group key df1.groupby(df1.b.diff().ne(1).cumsum()).a.diff() Out[361]: 0 NaN 1 110.0 2 140.0 3 NaN 4 230.0 Name: a, dtype: float64
answers question: http://stackoverflow.com/q/51141692

http://stackoverflow.com/q/51116774
has answer: http://stackoverflow.com/a/51116870
has body: Say I had a list: lis = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0] Would there be any way too take out the first 4 values of the list, make them : [4, 2, 2, 4] and the put them back in the list so the list now looks like [4, 2, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] and do all of this without making the list [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] at the start. Also if possible, can you make a loop to do this for all the 4 values available. So that the list now looks like: [4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4]
has answer: http://stackoverflow.com/a/51116807
tagged with: python
tagged with: python-3.x
score: 2
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/51117789
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5805892
type: Question
has answer: http://stackoverflow.com/a/51122878
has answer: http://stackoverflow.com/a/51226576
has answer: http://stackoverflow.com/a/51116835
has comment: http://stackoverflow.com/comment/89219780
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/51226480
has title: Changing specific index's in list
favorite count: 0

http://stackoverflow.com/q/51073780
score: 0
tagged with: api
answer count: 1
type: UnansweredQuestion
has title: How do I loop this function in python?
tagged with: python
has body: I am trying to extract hours of operations of a list of restaurants hitting Yelp API after I retrieved their respective business id: My original defined function was: def is_clocked(business_id): #import pdb; pdb.set_trace() try: clocked_ind = get_business(API_KEY, business_id) clocked_ind1 = clocked_ind['hours'] except: clocked_ind1 = 'None' return clocked_ind1 clocked_ind = is_clocked(b_id) print(clocked_ind) However, this function returned to me a long data instead of wide data format: bad_format: Querying https://api.yelp.com/v3/businesses/9GzjKeifGJ6KzWkaPftYHg ... [{'open': [{'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 0}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 1}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 2}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 3}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 4}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 5}, {'is_overnight': False, 'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR', 'is_open_now': True}] I want my final output to look like this in a csv: (input) day = [0, 1,2,3,4,5,6] start = [1100, 1100, 1100, 1100, 1100, 1100, 1100] end = [2200, 2200, 2200, 2200, 2200, 2200, 2100] day1 = [] for i in day: day1.append("start"+str(i)) for i in range(len(day1)): merge_HOO[day1[i]]=start[i] pd.DataFrame(merge_HOO, index=[0]) #Desired Output[115]: item day start end end0 ... start2 start3 start4 start5 start6 0 0 0 1100 2200 2200 ... 1100 1100 1100 1100 1100 But as you notice: I manually coded the input for once particular business. I want to create a loop such that it returns in csv my desired output for each business_id. I have also written the code below, but i feel there has to be a better way to make this loop. The below code needs to be a a function: day = day_open(b_id) start = day_start(b_id) end = day_end(b_id) day1 = [] for i in day: day1.append("start"+str(i)) dict1 = {} for …
has answer: http://stackoverflow.com/a/51079189
type: Question

http://stackoverflow.com/comment/89295606
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51154825
has text: Which Python, Conda, gcc and read_eagle (commit hash) versions? I can build the 4a73486 version fine with Python 3.7 and no Conda (both gcc 8.1 and clang 9.1); it may be a Conda issue.

http://stackoverflow.com/comment/89233064
type: AnswerComment
score: 0
type: Comment
has text: Ah! age_one = data[(data['age']==1)&(~data.duplicated())]
comment on: http://stackoverflow.com/a/51123453

ascii
tags question: http://stackoverflow.com/q/51089194
type: Tag
tag name: ascii
tags question: http://stackoverflow.com/q/51066682
tags question: http://stackoverflow.com/q/51090971
tags question: http://stackoverflow.com/q/51063696

http://stackoverflow.com/comment/128432063
type: Comment
has text: @AndreaRicchi Which OS and which Python version?
comment on: http://stackoverflow.com/a/71285627
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89186081
has text: @R.A.B.B.I.T The 5th column... DataType
score: 0
comment on: http://stackoverflow.com/q/51099197
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51139890
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89265414
has comment: http://stackoverflow.com/comment/89265097
score: 0
has comment: http://stackoverflow.com/comment/89323459
has comment: http://stackoverflow.com/comment/89264878
has comment: http://stackoverflow.com/comment/105984877
has comment: http://stackoverflow.com/comment/89264803
has comment: http://stackoverflow.com/comment/89265139
type: Answer
has body: As you can see, in your views you have a form class to your view form = LoginForm(), but in your template you're not rendering this form and you won't be able to validate it and the line if form.is_valid(): will always return False. You have two options, render the form class or change: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') username = username.lower() password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if user.is_staff: return redirect('sweet:vendor_index') else: return redirect('sweet:index') else: errors = "Invalid Username or Password" to: username = request.POST.get('username') username = username.lower() password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) if user.is_staff: return redirect('sweet:vendor_index') else: return redirect('sweet:index') Probably the LoginForm class take another parameters and cannot be validated
accepted answer of: http://stackoverflow.com/q/51138447
has comment: http://stackoverflow.com/comment/89265516
answers question: http://stackoverflow.com/q/51138447
has comment: http://stackoverflow.com/comment/89265219
has comment: http://stackoverflow.com/comment/89265439
has comment: http://stackoverflow.com/comment/89266753

http://stackoverflow.com/comment/89303119
type: Comment
type: QuestionComment
has text: Do you want the user to be able to zoom in on it while it's being created? One option would be to just show the overview without allowing them to zoom in. In this case it would just be a single image that you're replacing, and it can skip the DZI and OpenSeadragon until it's actually finished.
comment on: http://stackoverflow.com/q/51039788
score: 0

http://stackoverflow.com/a/51016163
accepted answer of: http://stackoverflow.com/q/51015240
has comment: http://stackoverflow.com/comment/89055984
type: Answer
score: 2
upvote count: 2
has body: First of all, you have to define the number of item in the list then you can input them. Then, you have to store them in an array and do the sorting process manually. I've done the sorting process without defining a function. If you want to use a function, just pass the array and return the sorted array. #include &lt;stdio.h&gt; int main() { int n, c, d, position, swap; printf("Enter number of elements\n"); scanf("%d", &amp;n); int array[n]; printf("Enter %d integers\n", n); for ( c = 0 ; c &lt; n ; c++ ) scanf("%d", &amp;array[c]); for ( c = 0 ; c &lt; ( n - 1 ) ; c++ ) { position = c; for ( d = c + 1 ; d &lt; n ; d++ ) { if ( array[position] &gt; array[d] ) position = d; } if ( position != c ) { swap = array[c]; array[c] = array[position]; array[position] = swap; } } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c &lt; n ; c++ ) printf("%d\n", array[c]); return 0; }
answers question: http://stackoverflow.com/q/51015240
type: AcceptedAnswer
downvote count: 0

datadog
tags question: http://stackoverflow.com/q/51033962
type: Tag
tag name: datadog

flask
tags question: http://stackoverflow.com/q/51111046
tags question: http://stackoverflow.com/q/51063327
tags question: http://stackoverflow.com/q/51024276
tags question: http://stackoverflow.com/q/51024025
tags question: http://stackoverflow.com/q/51119495
tags question: http://stackoverflow.com/q/51079338
tags question: http://stackoverflow.com/q/51045716
tags question: http://stackoverflow.com/q/51052953
tags question: http://stackoverflow.com/q/51054835
tags question: http://stackoverflow.com/q/51077280
tags question: http://stackoverflow.com/q/51045911
tags question: http://stackoverflow.com/q/51142702
tags question: http://stackoverflow.com/q/51034048
tags question: http://stackoverflow.com/q/51148947
tags question: http://stackoverflow.com/q/51071068
tags question: http://stackoverflow.com/q/51165460
tags question: http://stackoverflow.com/q/51160893
tags question: http://stackoverflow.com/q/51166149
tags question: http://stackoverflow.com/q/51027487
tags question: http://stackoverflow.com/q/51107877
tags question: http://stackoverflow.com/q/51011855
tags question: http://stackoverflow.com/q/51062531
tags question: http://stackoverflow.com/q/51059107
tags question: http://stackoverflow.com/q/51057226
tags question: http://stackoverflow.com/q/51031002
tags question: http://stackoverflow.com/q/51057966
tags question: http://stackoverflow.com/q/51025893
tags question: http://stackoverflow.com/q/51093873
tags question: http://stackoverflow.com/q/51127344
tags question: http://stackoverflow.com/q/51104830
tags question: http://stackoverflow.com/q/51130561
tags question: http://stackoverflow.com/q/51048471
tags question: http://stackoverflow.com/q/51015108
tags question: http://stackoverflow.com/q/51060433
tags question: http://stackoverflow.com/q/51092035
tags question: http://stackoverflow.com/q/51039214
tags question: http://stackoverflow.com/q/51027440
tags question: http://stackoverflow.com/q/51028096
tags question: http://stackoverflow.com/q/51014847
tags question: http://stackoverflow.com/q/51113799
tags question: http://stackoverflow.com/q/51028859
tags question: http://stackoverflow.com/q/51014182
tags question: http://stackoverflow.com/q/51085037
tags question: http://stackoverflow.com/q/51046786
tags question: http://stackoverflow.com/q/51160046
tags question: http://stackoverflow.com/q/51135498
tags question: http://stackoverflow.com/q/51163702
tags question: http://stackoverflow.com/q/51028360
tags question: http://stackoverflow.com/q/51075096
tags question: http://stackoverflow.com/q/51081604
tags question: http://stackoverflow.com/q/51159165
tags question: http://stackoverflow.com/q/51016103
tags question: http://stackoverflow.com/q/51027375
tags question: http://stackoverflow.com/q/51063249
tags question: http://stackoverflow.com/q/51065521
tags question: http://stackoverflow.com/q/51023265
tags question: http://stackoverflow.com/q/51013113
tags question: http://stackoverflow.com/q/51066705
tags question: http://stackoverflow.com/q/51159132
tags question: http://stackoverflow.com/q/51020809
tags question: http://stackoverflow.com/q/51025540
tags question: http://stackoverflow.com/q/51087988
type: Tag
tags question: http://stackoverflow.com/q/51042138
tags question: http://stackoverflow.com/q/51067121
tags question: http://stackoverflow.com/q/51136621
tags question: http://stackoverflow.com/q/51089257
tags question: http://stackoverflow.com/q/51159303
tags question: http://stackoverflow.com/q/51059906
tags question: http://stackoverflow.com/q/51097072
tags question: http://stackoverflow.com/q/51165668
tags question: http://stackoverflow.com/q/51141989
tags question: http://stackoverflow.com/q/51033646
tags question: http://stackoverflow.com/q/51041562
tags question: http://stackoverflow.com/q/51064261
tags question: http://stackoverflow.com/q/51017310
tags question: http://stackoverflow.com/q/51138208
tags question: http://stackoverflow.com/q/51156994
tags question: http://stackoverflow.com/q/51088557
tags question: http://stackoverflow.com/q/51024719

http://stackoverflow.com/comment/89371819
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51181602
has text: Try the Slack conversation system, you get access at http://robotframework.org/#support . Then you can ask for help at #ride channel.
type: AnswerComment

http://stackoverflow.com/a/51092161
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/51092139
answers question: http://stackoverflow.com/q/51092139
type: AcceptedAnswer
downvote count: 0
has body: You can use an if statement in the template. {% if user_settings.room2 %} /{{ user_settings.room2 }} {% endif %}

http://stackoverflow.com/q/51079183
score: 2
type: AnsweredQuestion
tagged with: anaconda
linked to: http://stackoverflow.com/q/38540395
type: Question
has answer: http://stackoverflow.com/a/51079358
answer count: 1
downvote count: 0
has title: Python Overwrite Last Line Without Appending
favorite count: 0
has comment: http://stackoverflow.com/comment/89147225
tagged with: spyder
tagged with: python
accepted answer: http://stackoverflow.com/a/51079358
has body: Similar questions have been answered for example here or here. Building upon the answers provided I am trying to overwrite the last output line in a Spyder console using interval = 1 for i in range(0,10): print(i, end = "\r") time.sleep(interval) which gives me the following, unexpected output: 0123456789 If i reduce the sleep interval to something short interval = 0.01, then I get the output I would expect 9 How can the timing of these consecutive print statements influence what is being printed? And more importantly how do I get my pretty output? This happens only when I use Spyder (3.2.6) and does not occur in a regular Python console.
upvote count: 2
linked to: http://stackoverflow.com/q/5419389

http://stackoverflow.com/q/51024921
tagged with: ibm-cloud
tagged with: db2
tagged with: command-line-interface
has answer: http://stackoverflow.com/a/51025211
answer count: 1
downvote count: 0
has body: I am trying to execute a prepared statement to a db2 on IBM Cloud. I only want to run the query if a data_array is populated which I have controlled that it is. This is my code: conn = ibm_db.connect(dsn, "", "") ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF) ins_sql = "insert into MY_TABLE (ID, NAME) values (?, ?)" ins_stm = ibm_db.prepare(conn, ins_sql) if data_array: for data in data_array: ibm_db.bind_param(ins_stm, 1, data['ID']) ibm_db.bind_param(ins_stm, 2, data['NAME']) ibm_db.execute(ins_stm) ibm_db.commit(conn) When I run it I get the following error in the ibm_db.execute(ins_stm)-line. Exception: Binding Error 3: [IBM][CLI Driver] CLI0102E Invalid conversion. SQLSTATE=07006 SQLCODE=-99999 What am I doing wrong here?
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has title: Binding error on executing prepared statement IBM_DB in python
upvote count: 1
has comment: http://stackoverflow.com/comment/89042711
type: Question
has comment: http://stackoverflow.com/comment/89043988

http://stackoverflow.com/a/51102609
has comment: http://stackoverflow.com/comment/89192838
has comment: http://stackoverflow.com/comment/89192903
score: 4
has comment: http://stackoverflow.com/comment/89192822
upvote count: 4
has comment: http://stackoverflow.com/comment/89192862
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51102581
has body: Convert integer column to boolean: print (type(df.loc[0, 'like'])) &lt;class 'numpy.int64'&gt; df['liked'] = df['like'].astype(bool) Or assign comparison with 1: df['liked'] = df['like'] == 1 If 1 is string compare by string '1': print (type(df.loc[0, 'like'])) &lt;class 'str'&gt; df['liked'] = df['like'] == '1' print (df) classification like liked 0 flower 1 True 1 flower 0 False 2 flower 0 False 3 adventure 1 True 4 adventure 1 True
answers question: http://stackoverflow.com/q/51102581
type: Answer

http://stackoverflow.com/comment/89270469
comment on: http://stackoverflow.com/a/51127799
type: AnswerComment
has text: That's OK though right? The point of this was to show how to slice a dataframe with a datetime index. Does that bit work for you?
score: 0
type: Comment

http://stackoverflow.com/q/51018026
has title: How can I update Python version when working on JGRASP on mac os?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51036825
tagged with: macos
has body: When I installed the new version of python 3.6.5, JGRASP was using the previous version, how can I use the new version on JGRASP?
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: jgrasp

pycharm
tags question: http://stackoverflow.com/q/51020750
tags question: http://stackoverflow.com/q/51071452
tags question: http://stackoverflow.com/q/51114330
tags question: http://stackoverflow.com/q/51113982
tags question: http://stackoverflow.com/q/51128298
tags question: http://stackoverflow.com/q/51054322
tags question: http://stackoverflow.com/q/51034459
tags question: http://stackoverflow.com/q/51147604
tags question: http://stackoverflow.com/q/51158946
tags question: http://stackoverflow.com/q/51111216
tags question: http://stackoverflow.com/q/51164281
tag name: pycharm
tags question: http://stackoverflow.com/q/51136788
tags question: http://stackoverflow.com/q/51148206
tags question: http://stackoverflow.com/q/51081102
tags question: http://stackoverflow.com/q/51055295
tags question: http://stackoverflow.com/q/51072974
tags question: http://stackoverflow.com/q/51022700
tags question: http://stackoverflow.com/q/51081216
tags question: http://stackoverflow.com/q/51114826
tags question: http://stackoverflow.com/q/51032676
tags question: http://stackoverflow.com/q/51030316
tags question: http://stackoverflow.com/q/51130546
tags question: http://stackoverflow.com/q/51030131
tags question: http://stackoverflow.com/q/51057226
tags question: http://stackoverflow.com/q/51121515
tags question: http://stackoverflow.com/q/51116241
tags question: http://stackoverflow.com/q/51126056
tags question: http://stackoverflow.com/q/51160464
tags question: http://stackoverflow.com/q/51070965
tags question: http://stackoverflow.com/q/51031757
type: Tag
tags question: http://stackoverflow.com/q/51124878
tags question: http://stackoverflow.com/q/51084768
tags question: http://stackoverflow.com/q/51063105
tags question: http://stackoverflow.com/q/51066880
tags question: http://stackoverflow.com/q/51132230
tags question: http://stackoverflow.com/q/51097615

http://stackoverflow.com/comment/89064599
score: 1
type: AnswerComment
has text: Puis, you can do the same to : print (len(list2[0][0][0])) ... etc. To see 2nd one is 9 and rest are 1 while 1st one will give an error cuz its a integer and len function isn't defined for it.
comment on: http://stackoverflow.com/a/51036447
type: Comment

http://stackoverflow.com/comment/89171126
comment on: http://stackoverflow.com/q/51091217
has text: That cannot possibly work. The XML handling is unaware that the data came from a file and so it cannot "write back" the changed value at the exact same position in the file. Even if it could: it is physically impossible to replace a text in a file with a shorter or longer text *without rewriting the entire file*. (The very only exceptions being "exactly the same length text" and "the data is at the very end".)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89315015
type: QuestionComment
type: Comment
has text: window 10 64 bit But i have installed 32 bit Python version and wxpython 2.8.12.1 It from Robotframework-ride installed using pip command.
comment on: http://stackoverflow.com/q/51146964
score: 0

http://stackoverflow.com/q/51055568
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89102037
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89101824
duplicate of: http://stackoverflow.com/q/5067604
answer count: 0
has body: In order to check my functions/methods I would like to know how to write python code to do: def function1: print('Exec of function', __function_name__) def function2: print('Exec of function', __function_name__) def function3: print('Exec of function', __function_name__) function1() function2() function3()
type: Question
linked to: http://stackoverflow.com/q/5067604
score: 0
has comment: http://stackoverflow.com/comment/89101739
has title: How to print method/function name using Python 3.6 system variable

django-views
tags question: http://stackoverflow.com/q/51082873
tags question: http://stackoverflow.com/q/51140048
tags question: http://stackoverflow.com/q/51106329
tags question: http://stackoverflow.com/q/51071911
tags question: http://stackoverflow.com/q/51066703
tags question: http://stackoverflow.com/q/51089217
tags question: http://stackoverflow.com/q/51115442
tags question: http://stackoverflow.com/q/51074314
tags question: http://stackoverflow.com/q/51163571
tag name: django-views
type: Tag
tags question: http://stackoverflow.com/q/51120313
tags question: http://stackoverflow.com/q/51144485
tags question: http://stackoverflow.com/q/51040840
tags question: http://stackoverflow.com/q/51127563
tags question: http://stackoverflow.com/q/51081730
tags question: http://stackoverflow.com/q/51075396
tags question: http://stackoverflow.com/q/51070139

http://stackoverflow.com/q/51063040
type: Question
has answer: http://stackoverflow.com/a/51064565
has comment: http://stackoverflow.com/comment/89118144
upvote count: 2
answer count: 1
has body: Ive been trying to figure out how I can use the date of the match to see how many days ago did the away team play and the home team play. By creating a Rest column for each I am trying to establish times played between there last appearance. I am assuming a list would have to be created but I cant quite grasp how that would work. Script: import csv import requests import datetime from pprint import pprint for i in range(20001,21271): req = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?site=en_nhl&amp;gamePk=20180' + str(i) + '&amp;leaderGameTypes=R&amp;expand=schedule.broadcasts.all,schedule.radioBroadcasts,schedule.teams,schedule.ticket,schedule.game.content.media.epg') data = req.json() for item in data['dates']: date = item['date'] games = item['games'] for game in games: gamePk = game['gamePk'] season = game['season'] teams = game['teams'] home = teams['home'] home_tm = home['team']['abbreviation'] away = teams['away'] away_tm = away['team']['abbreviation'] print(date, gamePk, away_tm, home_tm)
favorite count: 0
tagged with: python-3.x
has title: Using Date to create a time since last appearance column
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51064565
downvote count: 0

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/51044221
tags question: http://stackoverflow.com/q/51163887
type: Tag

http://stackoverflow.com/q/51031397
favorite count: 0
upvote count: 3
possible better answer: http://stackoverflow.com/a/51031710
tagged with: python
has body: We are trying to return a list of titles for the Django API, in which the title can have a few keywords. So for instance, if we use the __icontains method to search for "money" and "world" (api.com/?keyworld=money&amp;keyword=world) this will return all records that contain money, world or both. The related SQL statement is: select * from news where news_source = 1 or news_source = 2 and news_title like '%money%' or news_title like '%world%' We are trying to use this code to allow the user to have multiple keywords for the __icontains as well as multiple sources, so the end goal is: api.com/?keyworld=money&amp;keyword=world&amp;source=1&amp;source=2 Our code: def get_queryset(self): queryset = News.objects.all() title = self.request.query_params.getlist('title') source = self.request.query_params.getlist('source') if title: queryset = queryset.filter(news_title__icontains=title, news_source__in=source) return queryset The issue is that this is only returning the second keyword if a second keyword is used, and not other keywords prior to what is typed in &amp;keyword=.
tagged with: python-3.x
tagged with: django
has comment: http://stackoverflow.com/comment/89055419
type: AnsweredQuestion
score: 3
downvote count: 0
has title: icontains and getlist django python
has answer: http://stackoverflow.com/a/51031710
has answer: http://stackoverflow.com/a/51046643
accepted answer: http://stackoverflow.com/a/51046643
type: Question
answer count: 2
tagged with: django-rest-framework

http://stackoverflow.com/comment/89048893
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51027813
has text: @user32185 what should I change it to?

http://stackoverflow.com/comment/89173635
type: Comment
comment on: http://stackoverflow.com/a/51092475
has text: It would depend on what you are trying to match
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89165322
type: Comment
comment on: http://stackoverflow.com/q/51088376
score: 0
has text: Look for async callback with python, so when your creating and flush finish only then you call from_file https://hackernoon.com/asynchronous-python-45df84b82434
type: QuestionComment

http://stackoverflow.com/comment/89302069
type: AnswerComment
comment on: http://stackoverflow.com/a/51156447
score: 0
type: Comment
has text: Can you please provide a speed up test?

http://stackoverflow.com/comment/89017619
comment on: http://stackoverflow.com/q/51012131
has text: Is this also possible if x and y are gurobi vars?
score: 0
type: Comment
type: QuestionComment

time
tags question: http://stackoverflow.com/q/51065560
tags question: http://stackoverflow.com/q/51164619
tags question: http://stackoverflow.com/q/51084078
tags question: http://stackoverflow.com/q/51029343
tags question: http://stackoverflow.com/q/51072902
tags question: http://stackoverflow.com/q/51144283
tags question: http://stackoverflow.com/q/51094339
tag name: time
tags question: http://stackoverflow.com/q/51101386
tags question: http://stackoverflow.com/q/51130648
type: Tag
tags question: http://stackoverflow.com/q/51109346
tags question: http://stackoverflow.com/q/51132916
tags question: http://stackoverflow.com/q/51076577

http://stackoverflow.com/comment/89204557
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51108206
has text: Thanks for the response, I actually wanted to add some attributes to the dataframe that specifically interact with the methods, I've updated the question

http://stackoverflow.com/comment/89089514
type: Comment
has text: @ztyh I think there is some misunderstanding on my part and I am here to help. U is (m,3), I am assuming 3 is batch size, usually batch size is written first so let it be (3,m). But I was assuming the function `d` is a distance function and hence scalar? no? The loss has to be scalar to be able to optimize, otherwise argmin (or argmax) won't make sense.
comment on: http://stackoverflow.com/a/51032558
type: AnswerComment
score: 0

http://stackoverflow.com/a/51156376
has comment: http://stackoverflow.com/comment/89296286
has comment: http://stackoverflow.com/comment/89296884
answers question: http://stackoverflow.com/q/51156095
type: Answer
has comment: http://stackoverflow.com/comment/89296422
has comment: http://stackoverflow.com/comment/89297903
has body: Assuming the values are, indeed, valid JSON, it might be faster to build a single JSON object to decode. I think it should be safe to just join the values into a single string. &gt;&gt;&gt; new_json = b'[%s]' % (b','.join(source_data.values(),) &gt;&gt;&gt; new_json b'[{"age":33,"gender":"Male"},{"age":20,"gender":"Female"}]' &gt;&gt;&gt; json.loads(new_json) [{'age': 33, 'gender': 'Male'}, {'age': 20, 'gender': 'Female'}] This replaces the overhead of calling json.loads 2000+ times with the lesser overhead of a single call to b','.join and a single string-formatting operation.
has comment: http://stackoverflow.com/comment/89296784
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51156095

http://stackoverflow.com/q/51045347
score: 0
has answer: http://stackoverflow.com/a/51055203
tagged with: python
tagged with: spacy
tagged with: rasa-core
has comment: http://stackoverflow.com/comment/89082921
type: AnsweredQuestion
tagged with: rasa-nlu
type: Question
accepted answer: http://stackoverflow.com/a/51055203
answer count: 1
has title: Installation of SpacCy Language Model in python not working
has body: I'm following the Rasa Core "Building a simple Bot" tutorial. (https://core.rasa.com/tutorial_basics.html) It requires the installation of the SpaCy Language model: python -m spacy download en_core_web_md However, I get "AttributeError: module 'thinc.linalg' has no attribute 'Mat'" Have you any idea what is causing this?

http://stackoverflow.com/q/51050013
tagged with: ubuntu-14.04
has comment: http://stackoverflow.com/comment/89093863
has title: Show matplotlib plots in Ubuntu (Windows subsystem for Linux) - Python 3
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: windows-subsystem-for-linux
linked to: http://stackoverflow.com/q/43397162
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/111485306
type: Question
has body: I have followed the answer in the question linked below to the letter, and it works beautifully in Python 2, but I need this to work with Python 3 also. I can't seem to get matplotlib to play nicely in Python 3. 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) And here is the output I get: OMP: Error #100: Fatal system error detected. OMP: System error #22: Invalid argument [1] 5245 abort (core dumped) python Show matplotlib plots in Ubuntu (Windows subsystem for Linux)
tagged with: matplotlib

http://stackoverflow.com/a/51062525
answers question: http://stackoverflow.com/q/51058476
has body: The layer after nn.relu is usually linear. Doing some scaling before or after a ReLu won't change anything (if L is linear, L(relu(x))=relu(L(x)) for all x), so having one scaling after the bartch normalization and one in the next layer is redundant. So you can skip the scaling after batch norm followed by a ReLu if you have another linear layer after the ReLu, which is usually the case.
type: Answer
score: 0

http://stackoverflow.com/q/51028233
has comment: http://stackoverflow.com/comment/89049233
favorite count: 0
tagged with: featuretools
tagged with: python
possible better answer: http://stackoverflow.com/a/51044947
upvote count: 4
has answer: http://stackoverflow.com/a/51044947
type: AnsweredQuestion
downvote count: 0
has body: I have this 3 dataframes: df_train cortado:____________________ SK_ID_CURR TARGET NAME_CONTRACT_TYPE_Cash loans \ 0 100002 1 1 1 100003 0 1 2 100004 0 0 3 100006 0 1 4 100007 0 1 NAME_CONTRACT_TYPE_Revolving loans CODE_GENDER_F CODE_GENDER_M 0 0 0 1 1 0 1 0 2 1 0 1 3 0 1 0 4 0 0 1 df_bureau cortado:____________________ SK_ID_CURR SK_ID_BUREAU CREDIT_ACTIVE_Active 0 100002 5714464 1 1 100002 5714465 1 2 215354 5714466 1 3 215354 5714467 1 4 215354 5714468 1 bureau_balance cortado 3:____________________ SK_ID_BUREAU MONTHS_BALANCE STATUS_C 0 5715448 0 1 1 5715448 -1 1 2 5715448 -2 1 3 5715448 -3 1 4 5715448 -4 1 And this is the script I am trying to run to feature synthesis: entities = { "train" : (df_train, "SK_ID_CURR"), "bureau" : (df_bureau, "SK_ID_BUREAU"), "bureau_balance" : (df_bureau_balance,"MONTHS_BALANCE", "STATUS", "SK_ID_BUREAU") , } relationships = [ ("bureau", "SK_ID_BUREAU", "bureau_balance", "SK_ID_BUREAU"), ("train", "SK_ID_CURR", "bureau", "SK_ID_CURR") ] feature_matrix_customers, features_defs = ft.dfs(entities=entities, relationships=relationships, target_entity="train" ) But, whever I introduce the column "STATUS", this error happens: TypeError: 'str' object does not support item assignment If I don't put the column "STATUS", it is ok with few rows of the dataframe. When the number of rows increases (and only putting STATUS as key would solve it), this other error happens: AssertionError: Index is not unique on dataframe (Entity bureau_balance) Thanks in advance!!
type: Question
accepted answer: http://stackoverflow.com/a/51028768
has title: Creating Entity Set in Featuretools error TypeError: 'str' object does not support item assignment
score: 4
answer count: 2
has answer: http://stackoverflow.com/a/51028768

http://stackoverflow.com/a/51090025
has comment: http://stackoverflow.com/comment/89170929
has comment: http://stackoverflow.com/comment/89170065
score: 0
answers question: http://stackoverflow.com/q/51089841
has comment: http://stackoverflow.com/comment/89169468
has comment: http://stackoverflow.com/comment/89169044
has comment: http://stackoverflow.com/comment/89170219
type: Answer
has body: infomap is a python pip software package. You need to install it via pip, which is a python package manager. Try pip install infomap. If it gives you an error about pip not being found, you need to install it with something like sudo apt-get install python-pip, but I think it's a part of the build-essential package you already installed.
has comment: http://stackoverflow.com/comment/89169637
has comment: http://stackoverflow.com/comment/89170291

http://stackoverflow.com/comment/89187423
score: 0
comment on: http://stackoverflow.com/q/51099894
type: Comment
type: QuestionComment
has text: @neverwalkaloner I know, but this sentence is generated from exception message. Is it possible to override this message when exception with this field happens?

http://stackoverflow.com/q/51095585
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51100284
has comment: http://stackoverflow.com/comment/89186130
tagged with: python
has title: Efficient way to find mode in a large 2D matrix in python(Scipy)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89187151
score: 1
has body: I am using stats.mode() from scipy to calculate mode in a 800*500 matrix. And the execution time is like: `Time taken to execute 0.4359015187888584 Time taken to execute 0.42199154405135975 Time taken to execute 0.4250416821138656 Time taken to execute 0.4100701556064723 Time taken to execute 0.4371956395342953` But I need it under: Excution time 0.09193338154885265 Is there any method to make it efficient?
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/89178909
accepted answer: http://stackoverflow.com/a/51100284
upvote count: 1
has comment: http://stackoverflow.com/comment/89179185

http://stackoverflow.com/a/51017376
answers question: http://stackoverflow.com/q/51017204
upvote count: 2
score: 0
downvote count: 2
has body: So if we want to count number of elements in a list without actually just calling len this could be done like this. li = [1, 2, 3, 4, 5, "string1", "string2"] print("Test of List") i = 0 try: while True: li[i] i += 1 except IndexError: print('Length of the list:', i) This is much slower, terribly obtuse and generally bad, but it works. I'd use len(li)
type: Answer

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/51039018
type: Tag

http://stackoverflow.com/comment/89032014
comment on: http://stackoverflow.com/q/51019609
has text: Yep, you can create a view with `df = df.loc[<boolean array>, [columns names]]`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51083714
has comment: http://stackoverflow.com/comment/89158257
has body: I believe you are on Unix system like Linux for example, where default strategy to create a subprocess is forking. Subprocess inherits the execution state and memory state of it's parent, including imported Python modules. You are correct when you say that mymodule is not imported for the second time. You actually want to wrap the code in mymodule with a function: import random def get_random(): return random.randint(0, 1000) and then call it from your mp_test.C.f() method: def f(self): print self.c, id(self.mm), id(self.mm.get_random()), self.mm.get_random()
score: 0
answers question: http://stackoverflow.com/q/51083210
type: Answer

http://stackoverflow.com/comment/89181209
type: Comment
comment on: http://stackoverflow.com/q/51093660
score: 1
has text: If you are using scapy to dissect the packet, you may also want to use it to directly receive the packets. You could replace the entire loop by `sniff(prn=handle)` where handle would accept the already-dissected packet as an argument
type: QuestionComment

http://stackoverflow.com/comment/89143185
has text: Could I remove MULTI if the transaction is not required? I replaced MULTI with UNWATCH in test, it seems it works, are there any risks?
comment on: http://stackoverflow.com/a/51061341
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89042426
type: Comment
type: QuestionComment
has text: I guess you could use `try ... except` with [this](https://github.com/7sDream/torrent_parser) library's parse function.
comment on: http://stackoverflow.com/q/51024950
score: 0

http://stackoverflow.com/a/51403649
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51132230
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51132230
has body: Answering to my own question: Turns out there's a compatibility setting in Pycharm for Pyside: Set it to PySide and debugger runs.

http://stackoverflow.com/q/51123442
favorite count: 0
has title: Geting multiple return value from PyObject in C#
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51124267
downvote count: 1
has body: I wrote the following code to execute python script using Python.Runtime. It succeed if my python method has a single return value. How can I get multiple return values from PyObject if my python method actually return multiple values? using (Py.GIL()) { dynamic test = Py.Import("test"); PyObject ob2 = test.test_method(); string str2 = ob2.ToString(); MessageBox.Show(str2); } my test.py is like this: def test_method(): x = 1 y = "name" return x,y If my test_method() only return x, or only return y, my code has no problem. However, if I want to separately get the value of x and y in my C# code. What should i do?
tagged with: c#
score: -1
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/89521331
type: Comment
comment on: http://stackoverflow.com/a/51169674
score: 0
type: AnswerComment
has text: @queenofthecapes I updated my answer to your latest code

http://stackoverflow.com/comment/89297950
type: Comment
type: QuestionComment
score: 2
has text: Please don't show pictures of code. Take the time to properly cut, paste, and format the information.
comment on: http://stackoverflow.com/q/51157219

http://stackoverflow.com/q/51154939
tagged with: tuples
downvote count: 3
has title: How can i create a list of dictionaries in python
tagged with: python
has comment: http://stackoverflow.com/comment/89293135
tagged with: dictionary
has answer: http://stackoverflow.com/a/51155153
answer count: 4
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/51155582
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/51155482
has body: I have a dictionary and tuple of friendship. I need to create a list of dictionaries that each key the person and the values are his friends users=[{"id":0,"name":"hero"},{"id":1,"name":"Dunn"},{"id":2,"name":"Sue"},{"id":3,"name":"Chie"},{"id":4,"name":"Thor"}, {"id": 5, "name": "Clive"},{"id":6,"name":"Hicks"},{"id":7,"name":"Devin"},{"id":8,"name":"Kate"},{"id":9,"name":"kelin"}] friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)] friend={} friends=[] for i in users: for j,k in friendships: if i['id']==j: friend[i['name']]=k friends.append(friend)
type: Question
tagged with: list
has comment: http://stackoverflow.com/comment/89293357
has comment: http://stackoverflow.com/comment/89293471
has answer: http://stackoverflow.com/a/51155298
has comment: http://stackoverflow.com/comment/89293390
favorite count: 0

http://stackoverflow.com/comment/89318301
type: Comment
score: 0
has text: Hi @jazz, I have double checked it!
type: QuestionComment
comment on: http://stackoverflow.com/q/51167397

http://stackoverflow.com/comment/89159713
comment on: http://stackoverflow.com/a/51085122
has text: :) hahaha indeed
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89230585
type: QuestionComment
has text: Do you think `df["Duration"] = df["Time_Difference"].cumsum()` ?
type: Comment
comment on: http://stackoverflow.com/q/51122702
score: 0

http://stackoverflow.com/comment/89169357
type: AnswerComment
type: Comment
has text: @Null-Hypothesis 1_1 and 1_2 is QuestionID_AnswerID combination?
comment on: http://stackoverflow.com/a/51090477
score: 1

http://stackoverflow.com/q/51061653
tagged with: subprocess
has body: This is my main function. If I receive new offer, I need to check the payment. I have HandleNewOffer() function on that. But the problem with this code happens if there are 2(or more) offers at the same time. One of the buyers will have to wait until the closing of the transaction. So is this possible to generate new process with HandleNewOffer() function and kill it when it`s done to make several transactions at the same time? Thank you in advance. def handler(): try: conn = k.call('GET', '/api/').json() #connect response = conn.call('GET', '/api/notifications/').json() notifications = response['data'] for notification in notifications: if notification['contact']: HandleNewOffer(notification) # need to dynamically start new process if notification except Exception as err: error= ('Error') Send(error)
has title: How can I dynamically create new process in python?
tagged with: process
tagged with: multiprocessing
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51064404
has comment: http://stackoverflow.com/comment/89113188
answer count: 1
score: 0
tagged with: python
tagged with: asynchronous
accepted answer: http://stackoverflow.com/a/51064404

http://stackoverflow.com/q/51157157
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51157302
type: Question
has body: I have a pandas dataframe with some data in blocks. The separating information is the timestamp of when the data was received. How can I put an empty line between each block of data? Ultimately, the idea is that this data will be fed to a live blotter via temporary csv and the data blocks need to be separated for ease of reading/replying. The data in my frame is without a breakline - but I need to separate it like the below example when output in CSV: Ticker Coupon Size Received UCGIM 5.375 1,000,000 03/07/2018 10:03 INEGRP 2.125 800,000 03/07/2018 10:03 LINGR 1.75 650,000 03/07/2018 10:03 BYLAN 0.75 500,000 03/07/2018 10:03 CMZB 0.875 500,000 03/07/2018 10:03 CXGD 5.75 500,000 03/07/2018 10:03 AAFFP 0 500,000 03/07/2018 10:03 UPCB 3.875 5,000,000 03/07/2018 10:01 UPCB 3.625 5,000,000 03/07/2018 10:01 BMW 0.5 1,000,000 03/07/2018 10:02 ACAFP 1.375 6,100,000 03/07/2018 10:02 ACACB 1.375 2,000,000 03/07/2018 10:02 BPLN 4.154 1,000,000 03/07/2018 10:02 TOTAL 1.875 2,000,000 03/07/2018 10:02 ISPIM 3.928 1,700,000 03/07/2018 10:02 BMW 0.875 1,350,000 03/07/2018 10:02 HTZ 5.5 1,150,000 03/07/2018 10:02 BAMIIM 1.75 1,100,000 03/07/2018 10:02 ENELIM 1.966 1,100,000 03/07/2018 10:02 SRGIM 1.5 1,000,000 03/07/2018 10:02 NDASS 3.5 1,000,000 03/07/2018 10:02 ESM 1.85 8,900,000 03/07/2018 09:46 ISPIM 1.125 5,200,000 03/07/2018 09:46 CARPP 1 4,100,000 03/07/2018 09:46 Thanks
has comment: http://stackoverflow.com/comment/89297785
has comment: http://stackoverflow.com/comment/89297884
has title: Python - Output empty line between group of rows in a dataframe
tagged with: dataframe
score: 0

http://stackoverflow.com/a/51054593
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51054490
has body: Yes, your understanding of both argument and parameter are correct. So if you look at question 10, the data is passed into the function 'min'. that is why it is an argument. As for question 8, data is a parameter of the function 'f'. When you want to call function 'f' in your program, you will need to provide an argument for the function. Example code: def hello(name): # name is a parameter return name myName = 'jack' hello(myName) # myName is an argument for function 'hello'
accepted answer of: http://stackoverflow.com/q/51054490
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/89282189
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51148860
has text: That's the weirdness of the issue. Asking my collegues and reproducing the mistake only "worked" once, as it usually worked out fine without any mistake
score: 0

http://stackoverflow.com/comment/89141237
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51076150
has text: @AbdulRehman try to add slash to urlpattern: `'deployments/<int:pk>/'`.

http://stackoverflow.com/comment/89133605
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51071212
type: Comment
has text: @DominicPrice: numerals & lowercase letters (28 + 10=38 chars)

http://stackoverflow.com/a/51137580
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51137118
accepted answer of: http://stackoverflow.com/q/51137118
type: Answer
has body: The magic bytes 0x1f8b at the start of the response indicate zlib compression. Servers will often compress the data for transport, and browsers automatically uncompress them. Here, you'll have to do the second step yourself: import urllib from urllib.request import urlopen import xml.etree.ElementTree as ET from io import BytesIO import gzip response = urllib.request.urlopen("http://regnskaber.virk.dk/32673592/eGJybHN0b3JlOi8vWC1GNzY5MUY0Ny0yMDE0MDMyOV8xMzQxNThfMT\ c5L3hicmw.xml") print (response.getcode()) data = response.read() compdata = BytesIO(data) text = [] for unit in gzip.GzipFile(fileobj=compdata): text.append(unit) text = b"".join(text) tree = ET.fromstring(text) print(tree) Output: 200 &lt;Element '{http://www.xbrl.org/2003/instance}xbrl' at 0x104d09098&gt;
score: 4

http://stackoverflow.com/q/51161990
upvote count: 1
tagged with: coremltools
tagged with: tensorflow
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89308366
tagged with: coreml
has title: coremltools exporting model with wrong input dimensions?
downvote count: 0
tagged with: keras
favorite count: 0
has body: I exported my model via coremltools: coreml_model = coremltools.converters.keras.convert(model) coreml_model.save('my_model.mlmodel') Then when I import it into iOS I get this: It looks to me like the input dimension isn't correct. I think it should be 30 double values and 1 binary output, so probably a MultiArray (Double 30) for the input? Well, I tried it anyway: let model = PredictionModel() guard let random_test_input = try? MLMultiArray(shape: [30], dataType: .double) else { return } let d = [28.946907457340416, 23.651251205295942, 20.848493236981295, 2.9486505022627476, 19.76246988067936, 13.44847786346712, 19.84888646187787, 9.577035016581378, 20.277092056011174, 4.428205956020074, 26.57346212148054, 13.3277424887711, 10.922006581604867, 23.47004848915737, 4.120362794693939, 24.86682912094741, 4.565591023296161, 16.85564118150741, 8.300754854155517, 10.43274595744203, 6.135850806878693, 7.737464090946267, 0.6374431422342641, 2.7510065670854624, 25.327854311852775, 18.685750099316806, 8.455681186509617, 25.651466411041778, 7.055552151358634, 0.33626649072226567] for (index, element) in d.enumerated() { random_test_input[index] = NSNumber(value: element) } do{ let output = try model.prediction(input1: random_test_input) print(output) }catch{ print(error) return } And I get an error: Input feature input1 was presented as a vector of length 30, but the model expects an input of length 1. Here's my export code: batch_size = 50 epochs = 10 test_size = 500 input_dim = 30 data = np.load(data_filename) x, y = data['x'], data['y'] # x.shape = (3114, 30) 3114 training samples with 30 data points per sample # y is a category matrix [0, 1, 0, 0] means that there's a one. [0, 0, 0, 1] means there is a 4. # y.shape = (3114, 2); In our case we only have 0's and 1's, so [1, 0] or [0, 1] # Shuffle them p = np.random.permutation(x.shape[0]) x, y = x[p], y[p] x_train, x_test = x[:2000], x[2000:] y_train, y_test = y[:2000], y[2000:] x_train, x_test = np.expand_dims(x_train, axis=…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89376483
answer count: 0

http://stackoverflow.com/q/51160137
score: 1
type: Question
has body: I am supposed to compress this directory called "log" which contains various logs(almost 50 logs) from different devices. This is the code so far I have tried... import tarfile import os import glob def value(): tar = tarfile.open("Archive.tgz","w:gz") path = '/var/log' cwd = os.getcwd() for name in glob.glob(path): tar.add(name, arcname = "log") tar.close() if os.path.isfile('./Archive.tgz'): print "Compressed Successfully !" else: print "File not Found!" value() I keep getting this error though: File "tar2.py", line 18, in &lt;module&gt; value() File "tar2.py", line 11, in value tar.add(name, arcname = "log") File "../../../../../../../src/dist/python/Lib/tarfile.py", line 2002, in add File "../../../../../../../src/dist/python/Lib/tarfile.py", line 1994, in add IOError: [Errno 13] Permission denied: '/var/log/cscript.log' I read a lot about this error online and tried using chmod as well. But nothing works. Please help me out!
has comment: http://stackoverflow.com/comment/89304014
upvote count: 1
answer count: 1
has title: Python: Compressing all the contents of a log file to a tgz format
has comment: http://stackoverflow.com/comment/89305038
favorite count: 0
has answer: http://stackoverflow.com/a/51160333
accepted answer: http://stackoverflow.com/a/51160333
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51034252
has comment: http://stackoverflow.com/comment/90515387
has comment: http://stackoverflow.com/comment/90694871
has comment: http://stackoverflow.com/comment/90449727
tagged with: web-scraping
tagged with: python
has body: I am using Selenium/Python to try and fill out a form and than fill out the recaptcha. I found python-anticaptcha and bought $10 in credits, and everything is working, the captcha comes up, but than nothing happens. I tried to look for answers for a few hours/consulted their api and examples, but could not find anything. Ultimately, the captcha should work and then the website would generate a table which I am trying to web-scrape This is what it ends up looking like, but nothing happens and after a minute or so it usually quits, this is the code from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup from python_anticaptcha import AnticaptchaClient, NoCaptchaTaskProxylessTask import re import pandas as pd import os import time import requests url = "https://claimittexas.org/app/claim-search" driver = webdriver.Safari() driver.implicitly_wait(30) driver.get(url) wait = WebDriverWait(driver, 30) result = driver.find_element_by_xpath('//*[@id="lastName"]') driver.execute_script("arguments[0].value='Al';",result) time.sleep(2) result.submit() api_key = #MYAPIKEY site_key = '6LeQLyEUAAAAAKTwLC-xVC0wGDFIqPg1q3Ofam5M' # grab from site time.sleep(2) client = AnticaptchaClient(api_key) task = NoCaptchaTaskProxylessTask(url, site_key) job = client.createTask(task) job.join() token = job.get_solution_response() requests.post(url, data={'g-recaptcha-response': token}).text
has answer: http://stackoverflow.com/a/51794399
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90517788
has title: Integrating anticaptcha with selenium
tagged with: selenium
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89093798
accepted answer: http://stackoverflow.com/a/51794399
has comment: http://stackoverflow.com/comment/90683874
has comment: http://stackoverflow.com/comment/130178188
tagged with: recaptcha
favorite count: 0
has comment: http://stackoverflow.com/comment/89093820
upvote count: 2

http://stackoverflow.com/q/51129944
score: 0
has comment: http://stackoverflow.com/comment/89316399
tagged with: pandas
has comment: http://stackoverflow.com/comment/89244973
has title: npzeros + itertuples alternative
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89314140
answer count: 0
has comment: http://stackoverflow.com/comment/89244924
has body: I have a dataframe like this : user_id anime_id user_rating 0 1 20 7.808497 1 3 20 8.000000 2 5 20 6.000000 3 6 20 7.808497 4 10 20 7.808497 it looks like basic dataframe for playing with recommender system. i had ~ 7millions rows, I reduced a bit the dataframe like that : df = df[df["user_id"] &lt; 2000] let's print n_users, n_items, i had 1999 users of course, and ~6000items I have 2 problems. if i want to built my training dataset like that : ratings = np.zeros((n_users, n_items)) for row in df.itertuples(): ratings[row[1]-1, row[2]-1] = row[3] with ratings = np.zeros((n_users, n_items)) i got an enormous matrix that result to memory error. i come with 2nd problem if i filter a few sample, this line don't return memory error but i have an IndexError like that : IndexError: index 950 is out of bounds for axis 0 with size 949
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89245002

http://stackoverflow.com/q/51146270
tagged with: python
has answer: http://stackoverflow.com/a/51146373
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51146438
possible better answer: http://stackoverflow.com/a/51146373
type: Question
accepted answer: http://stackoverflow.com/a/51146438
answer count: 2
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/5900578
favorite count: 0
has body: I have a JSON file that I took the keys from to use as rows for my data frame, next I took all the values from all the keys and put them into a flattened list. I want to use that list of values as the columns. However there's eight values and 5 keys JSON: { "student1": [ "view_grades", "view_classes" ], "student2": [ "view_grades", "view_classes" ], "teacher": [ "view_grades", "change_grades", "add_grades", "delete_grades", "view_classes" ], "principle": [ "view_grades", "view_classes", "change_classes", "add_classes", "delete_classes" ] } convert.py def json_to_csv(): with open('C:/Users/Elitebook/Documents/GitHub/permissions.json') as json_file: #convert to python dict py_dict = json.load(json_file) #first get a list of all the values(permissions) from the dict, flatten the list and return only unique values permissions = sorted(set([key for value in py_dict.itervalues() for key in value])) #create a dataframe from the python dictionary pd.DataFrame.from_dict(py_dict, orient='index', columns=permissions) I'm getting the AssertionError: 8 columns passed, passed data had 5 columns error, I want to have it so I can have the 8 columns and 5 rows. Then I can put what I want in the value fields for the dataframe
has title: Make a pandas dataframe with unequal rows and columns
tagged with: pandas

http://stackoverflow.com/q/51084165
accepted answer: http://stackoverflow.com/a/51084309
tagged with: loops
downvote count: 1
type: Question
has body: New to Python. Working in the following environment. Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] I'm getting an "invalid syntax" error on the following line of code: if(j % 10000) == 0 Pretty sure this is something simple. Just not familiar enough to know what I'm doing wrong. Any help would be appreciated. Thanks.
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89156752
has answer: http://stackoverflow.com/a/51084309
favorite count: 0
has title: Python - Looping Statement Syntax
tagged with: python
has comment: http://stackoverflow.com/comment/89157216
score: -1
type: AnsweredQuestion
tagged with: syntax

http://stackoverflow.com/comment/90080965
comment on: http://stackoverflow.com/q/51150468
has text: Looks like it's necessary to provide an **input_shape** parameter to LSTM layer, i did it and now it working. Thanks to @Mitiku for advice.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51107699
has answer: http://stackoverflow.com/a/51108251
tagged with: http://stackoverflow.com/tag/json
tagged with: mysql
type: Question
tagged with: financial
has comment: http://stackoverflow.com/comment/89202996
tagged with: database
has comment: http://stackoverflow.com/comment/89202491
accepted answer: http://stackoverflow.com/a/51108251
score: 0
has comment: http://stackoverflow.com/comment/89203414
answer count: 1
has comment: http://stackoverflow.com/comment/89203154
has body: I have a JSON file with raw financial data, including OHLC, volume, trades, etc. All of the data except the OHLC will correctly transfer to the MySQL database I setup. The OHLC data only as zeros after the transfer to the database. The raw json data looks like this: [[1512086400000, "0.00001204", "0.00001209", "0.00001161", "0.00001183", "771721.00000000", 1512086699999, "9.10638040", 126, "359700.00000000", "4.22792312", "52516956.22676400"], [1512086700000, "0.00001189", "0.00001194", "0.00001183", "0.00001189", "119120.00000000", 1512086999999, "1.41575664", 44, "49016.00000000", "0.58377518", "52659721.84287900"], [1512087000000, "0.00001191", "0.00001196", "0.00001183", [1512087600000, "0.00001187", "0.00001190", "0.00001171", "0.00001174", "312477.00000000", 1512087899999, "3.69618651", 63, "155121.00000000", "1.84118817", "53289721.44287900"], … … Where the first value is time, the next four values in quotation marks are the OHLC data, and the next value in quotations is volume. I originally suspected the quotations prevented the transfer for some reason, though oddly volume is in quotes too and transfers to my database with no issue. I considered iterating over the file and copying it to another json file, taking out the quotation marks. I'm not sure however if the effort will pan out, so I want to see what the advice of those who might know better would be.
has title: (Python/JSON/MySQL) Advice on financial data in JSON that won't transfer to db
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89024862
has text: Incidentally, `resample` appears to more accurately visualize the data: Why did [so many say I should rather use `groupby`](https://stackoverflow.com/questions/50983386/how-do-i-sum-time-series-data-by-day-in-python-resample-sum-has-no-effect)?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51016188

http://stackoverflow.com/comment/89089012
score: 1
comment on: http://stackoverflow.com/q/51048950
type: Comment
type: QuestionComment
has text: You can't share GUI widgets between processes. Depending on your platform, it will either do nothing, freeze, raise exceptions, create two separate copies of the GUI, or, if you're really unlucky, unpredictably work sometimes but do one of the other things other times.

http://stackoverflow.com/comment/89164193
comment on: http://stackoverflow.com/a/51087366
score: 0
type: Comment
type: AnswerComment
has text: Although I was thinking in a general solution to the input and next parse it, I will adapt your proposal. Thanks.

http://stackoverflow.com/comment/89272338
type: QuestionComment
has text: What is your expected output from this data?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51143595

http://stackoverflow.com/q/51065457
has comment: http://stackoverflow.com/comment/89121326
answer count: 3
has answer: http://stackoverflow.com/a/51065599
has title: How to Import a SQL file to Python
tagged with: sqlite
favorite count: 0
has answer: http://stackoverflow.com/a/51065780
upvote count: 2
type: UnansweredQuestion
has body: I'm attempting to import an sq file that already has tables into python. However, it doesn't seem to import what I had hoped. The only things I've seen so far are how to creata a new sq file with a table, but I'm looking to just have an already completed sq file imported into python. So far, I've written this. # Python code to demonstrate SQL to fetch data. # importing the module import sqlite3 # connect withe the myTable database connection = sqlite3.connect("CEM3_Slice_20180622.sql") # cursor object crsr = connection.cursor() # execute the command to fetch all the data from the table emp crsr.execute("SELECT * FROM 'Trade Details'") # store all the fetched data in the ans variable ans= crsr.fetchall() # loop to print all the data for i in ans: print(i) However, it keeps claiming that the Trade Details table, which is a table inside the file I've connected it to, does not exist. Nowhere I've looked shows me how to do this with an already created file and table, so please don't just redirect me to an answer about that
tagged with: python
has comment: http://stackoverflow.com/comment/89120900
score: 2
has comment: http://stackoverflow.com/comment/89121187
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/70751187

http://stackoverflow.com/a/51180078
has body: The documentation shows that in PyQt, iterator objects support __iadd__ and __isub__. This allows you to use, e.g. it += 1 instead of ++it. Here's a small demo: # from PyQt5.QtWidgets import QApplication, QTextEdit from PyQt4.QtGui import QApplication, QTextEdit app = QApplication(['test']) edit = QTextEdit() edit.setText('onetwothree ') it = edit.document().firstBlock().begin() while not it.atEnd(): fragment = it.fragment() if fragment.isValid(): print(fragment.text()) it += 1 Output: one two three
accepted answer of: http://stackoverflow.com/q/51136174
score: 3
answers question: http://stackoverflow.com/q/51136174
has comment: http://stackoverflow.com/comment/128475243
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/128477280
type: Answer
upvote count: 3

http://stackoverflow.com/q/51123027
type: Question
has comment: http://stackoverflow.com/comment/89231154
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/51123840
score: 0
tagged with: background-image
answer count: 1
tagged with: sprite
has title: How do you isolate enemy sprites so that they disappear when going into a new room?
has body: I've tried few methods such as coding the enemies in the room1 class but nothing seems to work, it either doesn't spawn the intended sprite at all or the sprite spawns but doesn't disappear, when I go into other rooms (unless I collide with it). This is my code, any help at all would be much appreciated! Side note, I've also tried to apply a different background to each room but haven't had any luck either. What needs to be done to implement that? import pygame import random # Define colours BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) PURPLE = (255, 0, 255) # --- Classes class Wall(pygame.sprite.Sprite): def __init__(self, x, y, width, height, color): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Player(pygame.sprite.Sprite): change_x = 0 change_y = 0 def __init__(self, filename, x, y): super().__init__() self.image = pygame.image.load(filename).convert() self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x def changespeed(self, x, y): self.change_x += x self.change_y += y def move(self, walls): self.rect.x += self.change_x block_hit_list = pygame.sprite.spritecollide(self, walls, False) for block in block_hit_list: if self.change_x &gt; 0: self.rect.right = block.rect.left else: self.rect.left = block.rect.right self.rect.y += self.change_y block_hit_list = pygame.sprite.spritecollide(self, walls, False) for block in block_hit_list: if self.change_y &gt; 0: self.rect.bottom = block.rect.top else: self.rect.top = block.rect.bottom class Enemy(pygame.sprite.Sprite): def __init__(self, filename): super().__init__() self.image = pygame.image.load(filename).convert() self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() class ProjectileUp(pygame.sprite.Sprite): def __init__(self, filename): super().__init__() self.image = pygame.image.load(filename).c…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51123840
has comment: http://stackoverflow.com/comment/89233405

http://stackoverflow.com/q/51081439
possible better answer: http://stackoverflow.com/a/51081966
tagged with: machine-learning
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51082005
tagged with: conv-neural-network
downvote count: 0
has body: I am using on-line data augmentation of images I feed into my Convolutional Neural Network. I am using the Keras ImageDataGenerator for this. The images are augmented in each batch and then the model is trained on these images. I am comparing different models, but since the images are augmented on the fly, is this really fair, since each models is getting slightly different images?
tagged with: tensorflow
has title: Is the usage of on-line data augmentation a fair comparison between CNN models
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51082005
has answer: http://stackoverflow.com/a/51081966
tagged with: keras
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/90031025
type: Comment
type: QuestionComment
has text: out of curiosity: why not graphene-django? Just for the sake of exercise?
score: 1
comment on: http://stackoverflow.com/q/51042724

http://stackoverflow.com/comment/89242182
score: 0
has text: Ok, so something like `*/2 * * * * cd /home/user/public_html/projects/myproject/spiders scrapy run crawler` would be entirely sufficient without the shell script?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51128529

http://stackoverflow.com/comment/89027566
type: QuestionComment
score: 2
has text: You don't show the code for `analyze()`, but I would guess that it mutates its argument - ie it removes all the entries from `tokens` as it analyzes them, and if there are any left after it returns that must be a syntax error.
comment on: http://stackoverflow.com/q/51017508
type: Comment

http://stackoverflow.com/comment/89171466
comment on: http://stackoverflow.com/q/51091558
has text: @Abhishek That's an example, it's got 1. Pizza 2.Pizza but with Ham and Anchovy 3. 2 drinks, both tub 4. a 10% coupon I've put in prices, and I think I got how coupons work, but the rest is muddled, especially pizza, how would I be able to pull a price for an empty list?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89073993
type: Comment
has text: you mean remove the whole `Div(Field('status'), css_class='col-sm-6'),` ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51040596

http://stackoverflow.com/a/51110087
answers question: http://stackoverflow.com/q/51107992
has comment: http://stackoverflow.com/comment/89208074
upvote count: 4
downvote count: 0
score: 4
type: Answer
has body: In python, a single-item tuple (called a singleton) is written as (value,), so the (111) in your input should be written as (111,) instead; otherwise it would be considered an integer of 111. From tuple's documentation: A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. &gt;&gt;&gt; empty = () &gt;&gt;&gt; singleton = 'hello', # &lt;-- note trailing comma &gt;&gt;&gt; len(empty) 0 &gt;&gt;&gt; len(singleton) 1 &gt;&gt;&gt; singleton ('hello',)

http://stackoverflow.com/a/51088512
answers question: http://stackoverflow.com/q/51088481
has comment: http://stackoverflow.com/comment/89165784
has comment: http://stackoverflow.com/comment/89165589
type: Answer
has body: Use collections.Counter: import collections print collections.Counter(words) For your input you'd get: Counter({'bcdef': 2, 'bcde': 1, 'abcdefg': 1})
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89165912
downvote count: 0
has comment: http://stackoverflow.com/comment/89165691
has comment: http://stackoverflow.com/comment/89165673

http://stackoverflow.com/q/51067038
has comment: http://stackoverflow.com/comment/89124128
downvote count: 1
possible better answer: http://stackoverflow.com/a/52721613
tagged with: python
has title: Bring Python gui window to front?
tagged with: tkinter
tagged with: easygui
has answer: http://stackoverflow.com/a/51067707
accepted answer: http://stackoverflow.com/a/51067707
type: AnsweredQuestion
type: Question
has body: I'm trying to use one of Python's gui modules to retrieve a user's Twitter username and password: Here is my first attempt (using easygui): import easygui username = easygui.enterbox("Enter your Twitter username") password = easygui.passwordbox("Enter your Twitter password") Here is my second attempt (using tkinter): import tkinter as tk from tkinter import simpledialog application_window = tk.Tk() application_window.attributes("-topmost", True) username = simpledialog.askstring("Input", "What is your Twitter username?") password = simpledialog.askstring("Input", "What is your Twitter password?", show="*") application_window.destroy() Currently, the neither gui appears automatically. Rather, a Python icon appears on my Windows taskbar and I have to click the icon to make the gui appear. Is there any programmatic way to make the gui automatically pop up? Or perhaps there's another module I can use to achieve this?
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89124975
has answer: http://stackoverflow.com/a/52721613
favorite count: 0
score: 0

http://stackoverflow.com/q/51111247
has comment: http://stackoverflow.com/comment/89283689
score: 0
has comment: http://stackoverflow.com/comment/89270771
has comment: http://stackoverflow.com/comment/89268554
has title: A .png Image Set convert A .raw File in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89262608
tagged with: rawimage
tagged with: python
has comment: http://stackoverflow.com/comment/89238046
answer count: 0
tagged with: file
type: Question
has body: I have this images: And I have lots of images I will use 3d reconstructions these images but I sould convert one .raw file these images How can I use ?
has comment: http://stackoverflow.com/comment/89279754
has comment: http://stackoverflow.com/comment/89293126
tagged with: image

http://stackoverflow.com/comment/89090291
has text: Removed the UAC part from the answer, thank you for the side note
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51045656
type: AnswerComment

http://stackoverflow.com/q/51103555
score: -1
has title: How to use function print value in tkinter label.config(text="printed value")
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/89194671
has body: I require help to use the function output to be used in a label. I have tried lbl.config(text=row.empid, row.joineddate) and lbl.config(text=print(row.empid, row.joineddate)) and none of them is working. The function is: def sqlstatement(): con = pyodbc.connect("Driver={SQL Server};server=localhost;database=employee;uid=admin;pwd=pwd") cur = con.cursor() sql= '''SELECT empid,joineddate from employee where empid= ?''' param_values=['11001'] cur.execute(sql) rows = cur.fetchall() for row in rows: print(row.empid, row.joineddate)
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51103715
type: UnansweredQuestion
tagged with: python
tagged with: tkinter

aws-lambda
tags question: http://stackoverflow.com/q/51094284
type: Tag
tags question: http://stackoverflow.com/q/51018963
tags question: http://stackoverflow.com/q/51064261
tags question: http://stackoverflow.com/q/51105990
tags question: http://stackoverflow.com/q/51094961
tags question: http://stackoverflow.com/q/51056178
tags question: http://stackoverflow.com/q/51047209
tags question: http://stackoverflow.com/q/51101099
tag name: aws-lambda
tags question: http://stackoverflow.com/q/51028310
tags question: http://stackoverflow.com/q/51105860
tags question: http://stackoverflow.com/q/51011448
tags question: http://stackoverflow.com/q/51111922
tags question: http://stackoverflow.com/q/51060408
tags question: http://stackoverflow.com/q/51132370
tags question: http://stackoverflow.com/q/51058660
tags question: http://stackoverflow.com/q/51031493
tags question: http://stackoverflow.com/q/51104230

http://stackoverflow.com/a/69345971
type: Answer
answers question: http://stackoverflow.com/q/51077064
has body: You can use batch file as a tool to execute SSIS packages. First, you need to setup batch file and then just use the following code in python: import subprocess subprocess.call([r'full_path_to_batch_file_directory/batch_file.bat'])
score: 0

http://stackoverflow.com/q/51084582
tagged with: inheritance
has comment: http://stackoverflow.com/comment/89160655
score: 0
tagged with: class-method
has comment: http://stackoverflow.com/comment/89157553
answer count: 1
has title: class methods not found when extending Django User model
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51084666
tagged with: python
has body: In Django 2.0, python 3.6.5 on Ubuntu: class UserProxy (django.contrib.auth.models.User): foo = django.contrib.auth.models.User.normalize_username ('abc') # OK bar = normalize_username ('abc') # ERROR class Meta: proxy = True The bar= line throws this exception: NameError: name 'normalize_username' is not defined Why isn't this method visible without the explicit namespace? The same error is thrown from within UserProxy.objects.create_user, which expects self.model.normalize_username to exist. This occurs during a database migration def commit (apps, schema_editor): apps.get_model ('myapp', 'UserProxy').objects.create_user (...)
has comment: http://stackoverflow.com/comment/89160829
tagged with: django-users
has comment: http://stackoverflow.com/comment/89161091
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89157742

http://stackoverflow.com/q/51094806
tagged with: docker
has comment: http://stackoverflow.com/comment/93713346
has answer: http://stackoverflow.com/a/53419546
tagged with: user-interface
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/107539179
tagged with: python
linked to: http://stackoverflow.com/q/21810452
score: 2
upvote count: 2
has title: Opencv Not displaying image inside docker
has body: I am trying to use the OpenCV imshow GUI from inside the docker container. I used the following to start the container I using nvidia-docker because, the container contains GPU version of Tensorflow xhost + nvidia-docker run \ --rm \ --name tf_keras \ --link mongodb_database:data_mongo \ -e DISPLAY=$DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $1:/abhijit_home \ -p 8888:8888 -p 6006:6006 \ tensorflow_gpu_v1 When I try to display am image using OpenCV I am just getting a blank screen. The Image I am trying to display is displayed using matplotlib. How can I correct this? Thanks
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/111417626

http://stackoverflow.com/a/51166304
has comment: http://stackoverflow.com/comment/89315926
has body: Using collections.OrderedDict Ex: import collections d = { "server" : { "2" : { "name" : "Chris", "text" : "Hello!" }, "1" : { "name" : "David", "text" : "Hey!" } } } print collections.OrderedDict(sorted(d["server"].items(), key=lambda x: int(x[0]))) output: OrderedDict([('1', {'text': 'Hey!', 'name': 'David'}), ('2', {'text': 'Hello!', 'name': 'Chris'})])
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89315807
score: 3
answers question: http://stackoverflow.com/q/51166266

http://stackoverflow.com/q/51158303
has comment: http://stackoverflow.com/comment/89299994
has comment: http://stackoverflow.com/comment/89300534
type: Question
has comment: http://stackoverflow.com/comment/89364477
score: 0
has comment: http://stackoverflow.com/comment/89300392
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89300611
has body: I can't seem to find a solution to this, and I'm really hoping someone can help my horribly archaic Python ability. I have a few Tkinter tabs, and they are starting to get really long. They are somewhat similar in format/layout, and I am planning on adding a LOT more. Is there no way I can hold each tab in its own file and import them? The only thing I can seem to find is importing classes and modules. Is there a better way to do this, or am I really just adding each tabs elements in the same file? My code looks like this so far: tabControl = ttk.Notebook(win) firstTab = ttk.Frame(tabControl) tabControl.add(firstTab, text='First Tab') tabControl.pack(expand=1, fill="both") secondTab = ttk.Frame(tabControl) tabControl.add(secondTab, text='Second Tab') thirdTab = ttk.Frame(tabControl) tabControl.add(thirdTab, text='Third Tab') And then when I add stuff to a tab I do something like: firstTabLabel=ttk.Label(firstTab, text="First Tab Purpose: \n " \ "a bunch of junk I'm providing to the people " \ "because reasons, and requirements") firstTabLabel.grid(column=0, row=0, padx=10, pady=5, columnspan=2, sticky=tk.W) Also with that "pack" on the first one, I'm not 100% sure what that is. I wasn't sure that I could call it like a class, as I'm not really passing anything to it to do anything, other than what's in the tab section.
has comment: http://stackoverflow.com/comment/89300065
has title: Python Tabs in Different Files / Modules - Tkinter
tagged with: tabs
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/89301176

http://stackoverflow.com/a/51168198
score: 1
answers question: http://stackoverflow.com/q/51166473
downvote count: 0
type: Answer
has body: Figured I share my solution anyways: from numpy import nan mess = [{40258: [['2018-07-03T14:13:41'], ['Open'], ['Closed']]}, {40257: [['2018-07-03T13:47:55', '2018-07-03T14:21:52', '2018-07-04T11:56:44'], ['Open', 'In Progress', 'Waiting on 3rd Party'], ['In Progress', 'Waiting on 3rd Party', 'In Progress']]}, {40255: [['2018-07-03T13:12:58'], ['Open'], ['Closed']]}, {40250: [[], [], []]}] master = dict() for dicto in mess: key = list(dicto.keys())[0] master[key] = {('List{}-{}'.format(j+1,i+1)): (dicto[key][j][i] if i &lt; len(dicto[key][j]) else nan ) for i in range(3) for j in range(3)} output = pd.DataFrame.from_records(master, columns=list(master.keys())).T print(output.to_string()) Output: List1-1 List1-2 List1-3 List2-1 List2-2 List2-3 List3-1 List3-2 List3-3 40258 2018-07-03T14:13:41 NaN NaN Open NaN NaN Closed NaN NaN 40257 2018-07-03T13:47:55 2018-07-03T14:21:52 2018-07-04T11:56:44 Open In Progress Waiting on 3rd Party In Progress Waiting on 3rd Party In Progress 40255 2018-07-03T13:12:58 NaN NaN Open NaN NaN Closed NaN NaN 40250 NaN NaN NaN NaN NaN NaN NaN NaN NaN
upvote count: 1

http://stackoverflow.com/a/51150485
answers question: http://stackoverflow.com/q/51150260
has comment: http://stackoverflow.com/comment/89285251
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You could read the process output message to debug it, example code: inputString = '' ps = subprocess.Popen(["java", "-jar", "C:\\path\to\my\jarFile\file.jar", inputString],stdout=subprocess.PIPE,stderr=subprocess.STDOUT) val = ps.stdout.read() print("val: " + val) and in my pc, it output error like this: val: Error: Unable to access jarfile C:\path o\my\jarFileile.jar
accepted answer of: http://stackoverflow.com/q/51150260

http://stackoverflow.com/comment/89089288
has text: I _wish_ this was pseudocode.
comment on: http://stackoverflow.com/q/51049062
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51067231
type: Answer
has body: using np.repeat with array slicing, you can create a resampled dataframe where the date (index) is repeated twice. df_resample = df.set_index(np.repeat(df.index[::2],2)[:len(df)]) # outputs: price date 2018-01-08 88.28 2018-01-08 88.22 2018-01-10 87.82 2018-01-10 88.08 2018-01-12 89.60 2018-01-12 88.35 2018-01-17 90.14 2018-01-17 90.10 2018-01-19 90.00 2018-01-19 91.61 2018-01-23 91.90 2018-01-23 91.82 2018-01-25 92.33 2018-01-25 94.06 Then grouping as usual yields the desired output: df_resampled.groupby(level=0).agg(['last', 'min', 'max', 'sum']) price last min max sum date 2018-01-08 88.22 88.22 88.28 176.50 2018-01-10 88.08 87.82 88.08 175.90 2018-01-12 88.35 88.35 89.60 177.95 2018-01-17 90.10 90.10 90.14 180.24 2018-01-19 91.61 90.00 91.61 181.61 2018-01-23 91.82 91.82 91.90 183.72 2018-01-25 94.06 92.33 94.06 186.39
answers question: http://stackoverflow.com/q/51064030
score: 0

http://stackoverflow.com/q/51160247
has body: I have two signup pages, student view, and parent view. The default signup url is on the student page http://127.0.0.1:8000/account/student-sign-up/. However, when the parent button is pressed the page redirects to an unknown url at http://127.0.0.1:8000/account/student-sign-up/parent_sign_up.html. I was wondering how to make the button redirect to just http://127.0.0.1:8000/account/parent-sign-up, without the student-sign-up prefix. HTML &lt;!-- Radio check 1 --&gt; &lt;div class="form-check form-check-inline radio"&gt; &lt;label class="form-check-label"&gt; &lt;input class="form-check-input" type="radio" name="radios" id="radio1" onclick="document.location.href='student_sign_up.html'" checked /&gt; Individual &lt;/label&gt; &lt;/div&gt; &lt;!-- Radio check 2 --&gt; &lt;div class="form-check form-check-inline radio"&gt; &lt;label class="form-check-label"&gt; &lt;input class="form-check-input" type="radio" name="radios" id="radio2" onclick="document.location.href='parent_sign_up.html'" /&gt; Parent of a child under 13 &lt;/label&gt; &lt;/div&gt; urls.py urlpatterns = [ path('login/', views.login_view, name='login'), path('student-sign-up/', views.student_sign_up, name='student_sign_up'), path('parent-sign-up/', views.parent_sign_up, name='parent_sign_up'), path('teacher-sign-up/', views.teacher_sign_up, name='teacher_sign_up'), path('reset-password/', views.reset_password, name='reset_password'), path('reset-password-after/', views.reset_password2, name='reset_password_after'),
type: UnansweredQuestion
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/51161618
type: Question
answer count: 1
downvote count: 0
tagged with: url
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Radio button redirect url not working
favorite count: 0

http://stackoverflow.com/q/51023038
upvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51219023
has body: I was recently ''forced'' to use gradient free optimizers (including the ones in pyoptsparse) Before, the number of iterations were considerably low so recording the data was never a big problem and i was opting for the internal recorder. But for an optimization problem with more than say 30.000 iterations reading the in data from the case-recorder becomes very cumbersome. If I were to use a code to simply append to a txt file in every iteration it is much quicker to read in and plot. I would like to ask if i am making a mistake or is it really better to use ''append binary txt file''. The steps: optimization problem of 1 des var, 1 constraint, 1 objective ~ 60000 iterations sql file size ~ 30 MB cr = CaseReader(fname) case_keys = cr.driver_cases.list_cases() ab=[cr.driver_cases.get_case(case_key).get_objectives()['a.obj'][0] for case_key in case_keys ] time spent : i stopped after 10 minutes still reading.... f=open('out.dat','ab') np.savetxt(f,[desvar,constraint,objec]) f.close() np.loadtxt( 'out.dat') time spent: within seconds....
type: Question
downvote count: 0
tagged with: openmdao
has title: OpenMDAO Internal recorder efficiency low?
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51219023

http://stackoverflow.com/q/51106402
type: AnsweredQuestion
tagged with: machine-learning
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51106833
has comment: http://stackoverflow.com/comment/89199894
score: 0
has title: Tensorflow 1.9 DNNClassifier unequal output labels optimization
answer count: 1
has answer: http://stackoverflow.com/a/51106833
tagged with: python
tagged with: artificial-intelligence
has body: I have a classification problem which requires some optimization, as my results are not quite adequate. I'm using the DNNClassifier for a huge dataset in order to classify items in 5 different classes (labels). I have over 2000 distinct items (in a hashbucket column with size 2000 and dims 6 - is this adequate?) and multiple numeric columns for said classification. My problem is the following: the amount of items belonging in each class is very variable. Class 1 is very common, class 2 is common but classes 3 4 and 5 are highly uncommon (under 2% of the dataset) but they are the most interesting ones in my test case. Even if I tweak the network size/number of neurons or the training epoch, I get close to no results in classes 3, 4 and 5, so class 1 and 2 are clearly overfitted. I saw the weight_column option in the documentation - would that be a good idea to change the learning weight of these three class to "normalize" the weight in each class ? Is there a more efficient way to get better results on rarer cases without losing the detection precision on the common classes? Many thanks!

http://stackoverflow.com/q/51151263
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: star-schema
downvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51152822
accepted answer: http://stackoverflow.com/a/51152822
score: -2
type: Question
upvote count: 0
has body: I have 6 dimension tables, all in the form of csv files. I have to form a star schema using Python. I'm not sure how to create the fact table using Python. The fact table (theoretically) has at least one column that is common with a dimension table. How can I create the fact table, keeping in mind that quantities from multiple dimension tables should correspond correctly in the fact table? I am not allowed to reveal the code or exact data, but I'll add a small example. File 1 contains the following columns: student_id, student_name. File 2 contains : student_id, department_id, department_name, sem_id. Lastly File 3 contains student_id, subject_code, subject_score. The 3 dimension tables are in the form of csv files. I now need the fact table to contain: student_id, student_name, department_id, subject_code. How can I form the fact table in that form? Thank you for your help.
answer count: 1
has title: Creating star schema from csv files using Python
favorite count: 0

http://stackoverflow.com/q/51157996
has comment: http://stackoverflow.com/comment/89379017
has comment: http://stackoverflow.com/comment/89299564
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89341224
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100081131
tagged with: python
has comment: http://stackoverflow.com/comment/89299747
upvote count: 6
has body: Using windows and python 3.6 I am having trouble with the multiprocessing once I import the function which is to be mapped. This code works (gives output [2, 12, 30, 56, 90]): from multiprocessing import Pool def f(x,y): return x*y if __name__ == '__main__': args=[(1,2),(3,4),(5,6),(7,8),(9,10)] with Pool(4) as p: result=p.starmap(f,args) print(result) Now I move the function f to a different .py file called 'test' and instead import it: from multiprocessing import Pool from test import f if __name__ == '__main__': args=[(1,2),(3,4),(5,6),(7,8),(9,10)] with Pool(4) as p: result=p.starmap(f,args) print(result) with test.py only containing: def f(x,y): return x*y Running this leads to an infinite loop (doesn't return anything with cpu usage high). What is causing this and is there a way to fix it? I have successfully got multiprocessing to work on a program by copying all the code into one huge .py which obviously is not ideal.
has comment: http://stackoverflow.com/comment/89300021
has comment: http://stackoverflow.com/comment/89380756
answer count: 0
has comment: http://stackoverflow.com/comment/89342171
has title: Python multiprocessing pool with imported function
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/89337415
score: 6
has comment: http://stackoverflow.com/comment/89299910
tagged with: windows
downvote count: 0

http://stackoverflow.com/comment/129394973
has text: @AnonymousUser: use `@shopkeeper_required(login_url='<path-for-home>')`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51127599
score: 1

chatbot
tags question: http://stackoverflow.com/q/51116772
tags question: http://stackoverflow.com/q/51102183
tags question: http://stackoverflow.com/q/51037880
tag name: chatbot
tags question: http://stackoverflow.com/q/51150754
tags question: http://stackoverflow.com/q/51063665
tags question: http://stackoverflow.com/q/51129201
tags question: http://stackoverflow.com/q/51084199
tags question: http://stackoverflow.com/q/51118600
type: Tag

http://stackoverflow.com/comment/89023694
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51015217
has text: Sorry, I have just corrected it. Total is a given value
score: 0

http://stackoverflow.com/comment/89166882
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51089099
has text: @thalesian1 Edit your post. Don't comment!
score: 0

http://stackoverflow.com/q/51121693
has body: After installed IronPython 2.7.8 (latest stable build) on Windows 10, I tried run pip but I got error like this: PS C:\Program Files\IronPython 2.7&gt; ipy.exe -m pip install numpy Unhandled exception: Traceback (most recent call last): File "C:\Program Files\IronPython 2.7\Lib\runpy.py", line 187, in run_module File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\pyparsing.py", line 1261, in setParseAction File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\pyparsing.py", line 1043, in _trim_arity File "C:\Program Files\IronPython 2.7\Lib\runpy.py", line 81, in _run_module_code File "C:\Program Files\IronPython 2.7\Lib\runpy.py", line 72, in _run_code File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\__main__.py", line 16, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\__init__.py", line 42, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\cmdoptions.py", line 16, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 25, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\download.py", line 40, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\utils\logging.py", line 9, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\utils\misc.py", line 21, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 77, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\packaging\requirements.py", line 9, in &lt;module&gt; File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\pyparsing.py", line 4734, in &lt;module&gt; IndexError: index out of range: -1 PS C:\Program Files\IronPython 2.7&gt; I have no clue to solve this error. It seems to be problem of IronPython? I have no way to install packag…
type: UnansweredQuestion
tagged with: pip
has answer: http://stackoverflow.com/a/51122750
tagged with: ironpython
type: Question
answer count: 1
score: 0
tagged with: python
has title: IronPython 2.7.8 with pip

http://stackoverflow.com/q/51038266
score: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/89068228
has body: After 85 epochs the loss (a cosine distance) of my model (a RNN with 3 LSTM layers) become NaN. Why does it happen and how can I fix it? Outputs of my model also become NaN. My model : tf.reset_default_graph() seqlen = tf.placeholder(tf.int32, [None]) x_id = tf.placeholder(tf.int32, [None, None]) y_id = tf.placeholder(tf.int32, [None, None]) embeddings_matrix = tf.placeholder(np.float32, [vocabulary_size, embedding_size]) x_emb = tf.nn.embedding_lookup(embeddings_matrix, x_id) y_emb = tf.nn.embedding_lookup(embeddings_matrix, y_id) cells = [tf.contrib.rnn.LSTMCell(s, activation=a) for s, a in [(400, tf.nn.relu), (400, tf.nn.relu), (400, tf.nn.tanh)]] cell = tf.contrib.rnn.MultiRNNCell(cells) outputs, _ = tf.nn.dynamic_rnn(cell, x_emb, dtype=tf.float32, sequence_length=seqlen) loss = tf.losses.cosine_distance(tf.nn.l2_normalize(outputs, 2), tf.nn.l2_normalize(y_emb, 2), 1) tf.summary.scalar('loss', loss) opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) merged = tf.summary.merge_all() The output of the training : Epoch 80/100 Time : 499 s Loss : 0.972911523852701 Val Loss : 0.9729658 Epoch 81/100 Time : 499 s Loss : 0.9723407568655597 Val Loss : 0.9718646 Epoch 82/100 Time : 499 s Loss : 0.9718870568505438 Val Loss : 0.971976 Epoch 83/100 Time : 499 s Loss : 0.9913996352643445 Val Loss : 0.990693 Epoch 84/100 Time : 499 s Loss : 0.9901496524596137 Val Loss : 0.98957264 Epoch 85/100 Time : 499 s Loss : nan Val Loss : nan Epoch 86/100 Time : 498 s Loss : nan Val Loss : nan Epoch 87/100 Time : 498 s Loss : nan Val Loss : nan Epoch 88/100 Time : 499 s Loss : nan Val Loss : nan Epoch 89/100 Time : 498 s Loss : nan Val Loss : nan Epoch 90/100 Time : 498 s Loss : nan Val Loss : nan And here sis the curve of the loos during the entire training : The blue curve is the loss on training data and the orange one in the loss on validation data. The learning rate used for ADAM is 0.001. My x and y got the following shape : [batch size, maximum sequence length…
tagged with: python
tagged with: nlp
has answer: http://stackoverflow.com/a/51039297
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89069122
upvote count: 7
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89069309
has title: Why my tensorflow model outputs become NaN after x epochs?
accepted answer: http://stackoverflow.com/a/51039297
tagged with: deep-learning
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89018690
type: Comment
comment on: http://stackoverflow.com/q/51012961
score: 1
has text: Could you please add a question into your post, we do not understand what you have a problem with.
type: QuestionComment

http://stackoverflow.com/comment/89291783
comment on: http://stackoverflow.com/q/51154330
has text: Use `df_eind['count'] = df_eind.groupby(['year', 'week'])['year'].transform('size')`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51115311
has body: One way to do this would be to return a copy of the attribute, rather than the list itself. &gt;&gt;&gt; class C: ... def __init__(self, value): ... self._x = value ... @property ... def x(self): ... return self._x[:] ... &gt;&gt;&gt; c = C([1, 2, 3]) &gt;&gt;&gt; c.x [1, 2, 3] &gt;&gt;&gt; c.x.append(5) &gt;&gt;&gt; c.x [1, 2, 3] &gt;&gt;&gt; c.x[0] = 6 &gt;&gt;&gt; c.x [1, 2, 3] Alternatively, the property could return an iterator over attribute, or a view (for example dict.items() instead of a dict). Returning iterators or views may help limit memory use if the attribute is large, and is more consistent with the behaviour of modern Python builtin functions and types. If the mutable attribute contains mutable attributes itself - for example a list of lists or dictionaries - then it may be necessary to return copies these objects too. This can be expensive in terms of time and resources if the object graph is deep. See the docs for the copy module for ways to customise how objects are copied. This technique is commonly used to prevent the problem of aliasing - where other objects hold references to your object's internal state. It does mean that the copies may go out of sync with the real attribute, but if your code is well designed then other classes should not be holding onto the values of your class anyway.
answers question: http://stackoverflow.com/q/51114984
accepted answer of: http://stackoverflow.com/q/51114984
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/a/51022073
score: 1
has body: It really depends how you need your data to be sent. You are also overwriting read_pressures with every pass of the loop. import json import time from decimal import Decimal count = 0 read_pressures = [] while (count &lt; 100): current_time=time.time() data = dict(pressure=2,time=current_time) time.sleep(0.01) count = count + 1 print(data) # read_pressures.append(data) print ("printing all values") print(read_pressures)
upvote count: 1
answers question: http://stackoverflow.com/q/51021898
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89117660
score: 0
type: Comment
type: QuestionComment
has text: and it is the same for outlook, it will be not possible to create automatically account with python code ?
comment on: http://stackoverflow.com/q/51057304

http://stackoverflow.com/a/51146914
has comment: http://stackoverflow.com/comment/89317234
downvote count: 0
has body: There are a number of approaches to handling inconsistent header names in the file. The best approach is to prevent it by rejecting such files at upload time, obliging the uploader to correct them. Assuming this isn't possible, you could try to transform the provided headers into what you want import csv import io import re with open(tmp_file, 'r') as f: reader = csv.reader headers = next(reader) # Make a new header list with placeholders fixed_headers = [None * len(headers)] for i, value in enumerate(headers) fixed = re.sub(r'(\w+)(?&lt;=[a-z])([A-Z]\w+)', r'\1_\2', v).lower() new_headers[i] = fixed The regex finds capital letters in the middle of strings and inserts an underscore; then str.lower is called on the result (so values like 'Email' will be converted to 'email'. Now rewrite the csv with the fixed headers: with open(tmp_file, 'r') as f: reader = csv.reader(f) next(reader) new_file = io.StringIO() writer = csv.writer(new_file) writer.writerow(fixed_headers) for row in reader: writer.writerow(row) # Rewind the file pointer new_file.seek(0) Use csv.DictReader to get rows as dictionaries of values mapped to headers. dr = csv.DictReader(new_file) for data_dict in dr: #adds to form try: form = AddContactForm(data_dict) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user.username first_name = form.cleaned_data.get(data_dict["first_name"]) last_name = form.cleaned_data.get(data_dict["last_name"]) phone = form.cleaned_data.get(data_dict["phone"]) email = form.cleaned_data.get(data_dict["email"]) address = form.cleaned_data.get(data_dict["address"]) company = form.cleaned_data.get(data_dict["company"]) obj.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass
type: Answer
answers question: http://stackoverflow.com/q/51144702
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89337824
has comment: http://stackoverflow.com/comment/89310229

http://stackoverflow.com/comment/89316528
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51166326
has text: edited*, also this is same my question with details: https://stackoverflow.com/questions/51147008/django-test-parallel-appregistrynotready

http://stackoverflow.com/comment/89195990
comment on: http://stackoverflow.com/q/51084028
score: 0
type: Comment
type: QuestionComment
has text: I am in your same situation. For now my advice is to learn C#. I am doing this right now and I found out it's a beautiful language. Also,OpenCV exist also for C# with the name EmguCV. This said, if you know the logic of your project (which should be obvious), a port should not be too difficult.

http://stackoverflow.com/comment/89272296
type: QuestionComment
has text: Thanks for the reply, but I am not sure how to setting property using javascript executor in Python.
type: Comment
comment on: http://stackoverflow.com/q/51127442
score: 0

http://stackoverflow.com/a/51153008
score: 4
has body: In case anyone is having the same problem as me, I just changed self.canvas.draw() to self.canvas.draw_idle()
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/133088100
downvote count: 0
has comment: http://stackoverflow.com/comment/102063895
answers question: http://stackoverflow.com/q/51133678

http://stackoverflow.com/q/51016095
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/43265818
type: Question
has comment: http://stackoverflow.com/comment/89025835
has body: Example code: class Post(models.Model): ... class Comment(models.Model): ... post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=False) post_comment_number = models.PositiveIntegerField(unique=True, null=False) Imagine a blog post with a bunch of comments underneath it. I want to assign a secondary ID to each one of these comments, representing the relationship between the comment and the blog post - for example: Comment #1: ..., Comment #2: ..., etc etc. I don't want to do this on the frontend because, for example, if comment #2 is ever deleted, I don't want to assign another comment associated with this particular blog post the #2 ID again. Any thoughts on how to do this? Thanks so much!
duplicate of: http://stackoverflow.com/q/43265818
has comment: http://stackoverflow.com/comment/89026972
has comment: http://stackoverflow.com/comment/89025030
tagged with: sql
has title: How can you add a secondary ID for a model, based on its association with a particular object?
has comment: http://stackoverflow.com/comment/89026351
answer count: 1
downvote count: 0
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/89025776
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51016465

http://stackoverflow.com/q/51028001
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51029184
accepted answer: http://stackoverflow.com/a/51029184
type: AnsweredQuestion
has title: Logical indexing with list comprehensions
has body: My code currently stands as follows: z = np.diagflat(c).dot(D).dot(x); idxN, idxP = z&lt;0, z&gt;=0 # logical indexing y1 = [-1 + np.exp(x)/(1+np.exp(x)) for x in z[idxN]] y1 = np.array(y1) # Size (504,) y2 = [-np.exp(-x)/(1+np.exp(-x)) for x in z[idxP]] y2 = np.array(y2) # Size (496,) Now I'm trying to form a (1000,) list y which will incorporate y1 or y2 depending on whether the index is +/-. I'm guessing a list comprehension would be the easiest but I'm struggling with the form. Thanks for your inputs.
downvote count: 0
has comment: http://stackoverflow.com/comment/89049362
score: 1
tagged with: list-comprehension
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/89050988
tagged with: matrix-indexing

http://stackoverflow.com/comment/89112341
has text: @min2bro can you give me an example for that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51060567

http://stackoverflow.com/q/51164091
tagged with: influxdb-python
favorite count: 0
has comment: http://stackoverflow.com/comment/89386736
has comment: http://stackoverflow.com/comment/89386681
tagged with: python-asyncio
has title: How to send UDP requests via asyncio in python 3
tagged with: python
tagged with: influxdb
has body: I would like to send UDP messages to my InfluxDB server using asyncio. This is my synchronous code: import socket import requests from logger import get_logger log = get_logger(__name__) class InfluxDB(object): def __init__(self, username, password, host, port, udp=True, udp_port=4444): log.info("InfluxDBClient()") self.udp = udp if self.udp: self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_port_tuple = (host, udp_port) self.session = requests.session() self.session.auth = (username, password) self.base_url = "http://{}:{}".format(host, port) def _query(self, payload, endpoint="/query"): log.debug(payload) return self.session.post(self.base_url + endpoint, params=payload) def _write(self, db, data, endpoint="/write"): log.debug("{} \t {}".format(db, data)) return self.session.post(self.base_url + endpoint, params={"db": db}, data=data) def write_udp(self, data_str): if self.udp: return self.udp_socket.sendto(data_str.encode("utf-8"), self.udp_port_tuple) else: raise Exception("UDP disabled") How do I rewrite the "write_udp" function using the async/await syntax? -- edit 7/5/2018 -- To be more specific, I am unsure how to reference the asyncio equivalent of "socket". Presumably there is a version of an asyncio based socket, which I would reference as self.udp_socket = socket.socket_asyncio, and then I would fire off messages via await socket.socket_asyncio.sendto(....) what I need to understand is how to reference this asyncio based socket object.
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89376714
type: Question
has comment: http://stackoverflow.com/comment/89375748
tagged with: async-await
has comment: http://stackoverflow.com/comment/89311888
upvote count: 2
has comment: http://stackoverflow.com/comment/89375715
downvote count: 1

http://stackoverflow.com/comment/89210845
type: QuestionComment
score: 0
has text: So when doing prediction, during training like how is the error minimized? Can you please take a small statement and give an example, like how loss is minimised using gradient descent?
comment on: http://stackoverflow.com/q/51082572
type: Comment

http://stackoverflow.com/comment/89164390
type: QuestionComment
comment on: http://stackoverflow.com/q/51086879
score: 0
has text: @Engineero my question is, how to calculate the error, between the numerically calculated integral with Monte-Carlo (which I am calculating) and that the real integral, and how to plot the error and its evolution, as the number of random numbers (N in this example) grow.
type: Comment

http://stackoverflow.com/a/51139255
downvote count: 0
has comment: http://stackoverflow.com/comment/89262653
has comment: http://stackoverflow.com/comment/89262999
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89262821
has comment: http://stackoverflow.com/comment/89262757
has body: Found an answer- at least with regards to copy()- after posting the question: it seems this issue was discussed quite a while ago in the bug tracker. A couple quotes: I don't think this is needed nor do I think that it is a good idea to have a copy() method in the ABCs because they know so little about their concrete underlying class (perhaps the backing store in the filesystem or a database). and: The return type of copy() for ABCs feels problematic. MutableMapping doesn't have it either. As I expected, this was discussed and there seem to be sound reasons behind it. This little tidbit from GVR is also worth including: I personally despise almost all uses of "copying" (including the entire copy module, both deep and shallow copy functionality).
answers question: http://stackoverflow.com/q/51138328
has comment: http://stackoverflow.com/comment/89262723
has comment: http://stackoverflow.com/comment/89262675

http://stackoverflow.com/q/51076415
has comment: http://stackoverflow.com/comment/89141996
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89142696
has answer: http://stackoverflow.com/a/51077045
tagged with: geocoding
upvote count: 2
has comment: http://stackoverflow.com/comment/89141975
has comment: http://stackoverflow.com/comment/89142400
answer count: 1
downvote count: 1
tagged with: latitude-longitude
tagged with: python
has title: printing function output to csv in python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89141735
has body: I am a beginner in Python and i need to export my function output in csv/xlsx format. Please see my code. I need to print my output of pixel2coord function to csv. Thanks from osgeo import gdal # Open raster file ds = gdal.Open('C:\\Users\\ADMIN\\Desktop\\datanew\\ndvi_alig_landsat_clipped.img') # GDAL affine transform parameters, According to gdal documentation xoff/yoff are image left corner, a/e are pixel wight/height and b/d is rotation and is zero if image is north up. xoff, a, b, yoff, d, e = ds.GetGeoTransform() def pixel2coord(x, y): """Returns global coordinates from pixel x, y coords""" xp = a * x + b * y + xoff yp = d * x + e * y + yoff return(xp, yp) # get columns and rows of your image from gdalinfo rows = 15381+1 colms = 15081+1 if __name__ == "__main__": for row in range(0,rows): for col in range(0,colms): print pixel2coord(col,row)

http://stackoverflow.com/comment/89091982
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51050486
has text: change `for item in Mssg: writer.writerow(item)` to `writer.writerow(Mssg)`

buffer
tags question: http://stackoverflow.com/q/51045578
tags question: http://stackoverflow.com/q/51086428
tag name: buffer
tags question: http://stackoverflow.com/q/51082703
type: Tag
tags question: http://stackoverflow.com/q/51156970

http://stackoverflow.com/comment/89233169
has text: checking the same, will revert accordingly.
type: Comment
comment on: http://stackoverflow.com/a/51123489
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89191097
has text: By the way, the code you say "works just fine" shouldn't. At least not how you show it to us with invalid indentation. For most languages indentation is just nice to have for people reading the code, but in the case of Python it's actually significant for the code to compile without errors. When posting code here, please copy-paste it, don't rewrite it. Rewriting the code might lead to mistakes that can confuse us or think that's the real error.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51101834
type: QuestionComment

http://stackoverflow.com/q/51061732
has body: I have parsed a tsv file and have this structure: [['x1','y1','x2','y2'], [1,1,0,80], [.95,1,.05,70], [.93,1,.1,65], … ] My x1 values are in descending order; starting from 1 going down to 0. My x2 values are in ascending order; starting from 0 going up to 1. I need both to be in ascending order. I can't just flip the list or else x2 will be in descending order. Also, note that x1 and y1 are pairs, so whatever we do to x1 we must do to y1 to make sure the data is still preserved. I have omitted my attempt out of shame, but if everyone promises not to laugh, what I tried was adding a -i to get the nth last item from my original list. raw_data is the data structure seen above. new_list = [[raw_data[2][-i], raw_data[3][-i]] for i in raw_data Unfortunately, that did not work. Question: How can I write a list comprehension such that my x1 (and the corresponding y1 values) are in ascending order?
has answer: http://stackoverflow.com/a/51062189
accepted answer: http://stackoverflow.com/a/51062189
answer count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/89113543
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
has title: Python sort partial list items
upvote count: 1
has comment: http://stackoverflow.com/comment/89114019
downvote count: 1
type: Question

http://stackoverflow.com/q/51106542
has answer: http://stackoverflow.com/a/51106636
has comment: http://stackoverflow.com/comment/89202421
has comment: http://stackoverflow.com/comment/89200161
has comment: http://stackoverflow.com/comment/89203022
has comment: http://stackoverflow.com/comment/89200175
score: 2
answer count: 1
has title: How to tell if a script is run by double-clicking .py file?
favorite count: 0
has comment: http://stackoverflow.com/comment/89203333
has body: I'm working on a Python 3X program which requires at least one command line argument. Currently, I'm handling arguments using the argparse library, which handles insufficient arguments by displaying a help text, and killing the program. This works great when the program is run from the command line. However, if the user clicks on the .py or .pyc file itself, there is no opportunity for the user to read the help text, or enter arguments - the program runs and finishes almost instantly. I'd like to find out when my program is run by double-clicking a file so I can run an interactive UI in that case. In other words, I'd like to have the arguments fed in interactively if the program is clicked on, but to keep the standard behavior of argparse if the program is run on the command line i.e., have the user specify them all at once e.g. python myprogram.py argument1. In order to do this, I need to know if the program was run from the command line or by double-clicking a file. I know that python does have a facility somewhat like this for checking if a module is imported or run as a script if __name__ == "__main__":. Minimal Example: #test.py import argparse parser = argparse.ArgumentParser() parser.add_argument("inputpath", help="path to plaintext input file") args = parser.parse_args() print(args.inputpath) Running on the command line gives us nice error handling if a user doesn't enter appropriate arguments: user@MyPC:path/to/file$ python test.py usage: test.py [-h] inputpathtest.py: error: the following arguments are required: inputpath However, trying to doubleclick on the file just runs it and exits immediately. There is no time to enter arguments or read the error message. Possible solutions: One way to do this would be an optional "interactive" argument, which if not present, would prompt the user manually. Defaulting to interactivity on would allow the user to enter inputs if the script was run by doubleclick. However, it would still allow the command line user to u…
tagged with: python-3.x
linked to: http://stackoverflow.com/q/4480075
has comment: http://stackoverflow.com/comment/89206725
has comment: http://stackoverflow.com/comment/89206819
accepted answer: http://stackoverflow.com/a/51106636
has comment: http://stackoverflow.com/comment/89202171
tagged with: python
has comment: http://stackoverflow.com/comment/89201739
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89202144
has comment: http://stackoverflow.com/comment/89200191
downvote count: 2
has comment: http://stackoverflow.com/comment/89206422
has comment: http://stackoverflow.com/comment/89200177
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89206375
has comment: http://stackoverflow.com/comment/89203135
has comment: http://stackoverflow.com/comment/89206272

http://stackoverflow.com/comment/129540779
comment on: http://stackoverflow.com/a/73271232
score: 0
type: AnswerComment
has text: Your answer could be improved by adding more information on what the code does and how it helps the OP.
type: Comment

http://stackoverflow.com/q/51125546
answer count: 3
possible better answer: http://stackoverflow.com/a/51125760
has answer: http://stackoverflow.com/a/51125760
accepted answer: http://stackoverflow.com/a/51125662
tagged with: if-statement
tagged with: pandas
type: AnsweredQuestion
score: 3
has title: I want to populate value in Dataframe based on matching values in other Dataframe
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51125662
tagged with: python
has body: I am editing the question. I dont want to use groupby to use group values. I would appreciate if someone could help with just the query to transform data in the following way: I have one dataframe given as follows: df1: col1 col2 ------------ VG 12 G 11 A 10 P 06 VP 0 I want the new dataframe such as: df2: VG G A P VP --------------------- 12 11 10 06 0 I tried achieving this using if condition and I got following error: Code: if df1.Score=='VG': df2['VG']=df1.loc[df1['col1'] == 'VG', 'col2'] The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
has answer: http://stackoverflow.com/a/51125843
upvote count: 3

http://stackoverflow.com/a/51065108
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51064563
has body: Since you need to parse it in the end anyway, it is more straightforward to use parsing as validation. Many Python libraries use this approach as well, for example JSON. It avoids duplicated logic (1. validation, 2. parsing), allows for more expressive error messages and is often much easier. To parse a single literal, such as 4 or 1 - 3, split it and convert the start/stop values. This automatically raises a ValueError if numbers are not valid integers. def page_range(literal): """ Convert a single page literal into a sequence of pages :raises ValueError: if literal does not denote a valid page range """ start, sep, stop = literal.partition('-') # '1 -3' =&gt; '1 ', '-', '3'; ' 4' =&gt; ' 4', '', '' if not start: # may want to raise an error for empty page literals return [] if not sep: # no '-' in literal, just the start return [int(start)] # sep is present, literal is a range of pages return list(range(int(start), int(stop) + 1)) You can use this to aggregate the pages of multiple literals, such as 4, 1-3. By using exceptions, you can raise an error for the portion of the literal that is invalid: def pages(literals): for literal in literals.split(','): try: yield page_range(literal.strip()) except ValueError: # parsing failed, raise manually to add details raise ValueError('Invalid page range: %r' % literal)
downvote count: 0

http://stackoverflow.com/a/77473780
upvote count: 1
answers question: http://stackoverflow.com/q/51054529
has body: leg = plt.legend(loc=0) for line in leg.get_lines(): line.set_linestyle('-')
type: Answer
has comment: http://stackoverflow.com/comment/139834094
downvote count: 0
score: 1

http://stackoverflow.com/a/51095509
has body: When scheduling a coroutine from a different thread, you must use asyncio.run_coroutine_threadsafe. For example: def fetch_something(self): future = asyncio.run_coroutine_threadsafe( self._client.fetch_something(), loop) return future.result() run_coroutine_threadsafe schedules the coroutine with the event loop in a thread-safe way and returns a concurrent.futures.Future. You can use the returned future to simply wait for the result as shown above, but you can also pass it to other functions, poll whether the result has arrived, or implement timeouts. When combining threads and asyncio, remember to make sure that all interfacing with the event loop from other threads (even to call something as simple as loop.stop to implement Network.stop) is done using loop.call_soon_threadsafe and asyncio.run_coroutine_threadsafe.
has comment: http://stackoverflow.com/comment/89283637
upvote count: 2
has comment: http://stackoverflow.com/comment/89299660
answers question: http://stackoverflow.com/q/51090555
accepted answer of: http://stackoverflow.com/q/51090555
has comment: http://stackoverflow.com/comment/89282320
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89261068
downvote count: 0
has comment: http://stackoverflow.com/comment/89260356
type: Answer

http://stackoverflow.com/a/51135076
type: Answer
accepted answer of: http://stackoverflow.com/q/51089318
has body: With reference of my another post.(.copy()) function is the change required in order to replace new set of values in column['word'] in each iteration. df_series=[] for d in range(0,2): df_series.append(df.copy()) so that this loop will work the way I expected final=[] L=['NA','****'] for eachtable in df_series: eachtable.loc[pos(df1),'word'] = random.choice(L) final.append(eachtable)
answers question: http://stackoverflow.com/q/51089318
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89341075
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51161334
has text: I have realised my original answer only applies to words that occur consecutively as you have suggested. Please see the updated answer for the matrix multiplication you have asked about. I am not sure this would work if you corpus has millions of words.
type: AnswerComment

http://stackoverflow.com/q/51044704
linked to: http://stackoverflow.com/q/27370046
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2276200
type: Question
tagged with: python-2.7
has body: I am new to python and programming in general, so this is probably a stupid question. I am currently preparing a psychology experiment using PsychoPy v1.90.2 standalone, python 2.7, the coder version, based on both an existing script and a tutorial from a colleague. It works perfectly on my computer (Mac) and on a Windows 10 computer, but on a computer using Windows7, it does not save the output (i.e. the participant's responses) to a csv file. An empty file is created, without any file specification, but the correct file name and in the correct location. I can correctly import the underlying csv file for stimulus creation if I include print df, I can see the dataframe in the console, so the data exists somewhere, at least temporarily My system (Mac) is german, but the Windows 10 and 7 computers are set to french There is no error message at all. I have successfully done this experiment on a (belgian) french Mac before. from psychopy import visual, core, event, gui, info, data import pandas as pd import numpy as np import os import random import sys import time GUI = gui.Dlg(title = "example") GUI.addField('participant:') GUI.show() if GUI.OK: metadata = GUI.data else: sys.exit('participant cancelled') w = visual.Window([1000, 600], color='black', units='pix') df = pd.DataFrame([[1, 2], [5, 3], [4, 6]], columns=['stim_a', 'stim_b']) df['participant'] = int(metadata[0]) df['ans'] = '' df = df.iloc[random.sample(df.index, len(df))] df.index = range(len(df)) output_df = "S_" + str(df.participant) + "_df" + "_" + time.strftime("%Y-%m:%d_%Hh%M") + ".csv" for j in range(df.shape[0]): event.clearEvents() stim_a = visual.TextStim(w, df.stim_a[j]) stim_a.draw() w.flip() resp = event.waitKeys() df.ans[j] = resp print df df.to_csv(output_df, index = False, header = True, sep = ',', encoding = 'utf-8') What should be there in the end: a csv file containing all the information contained in df initially, plus the "participant" column containing the participant number and the "ans…
score: 5
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: psychopy
has title: pandas to_csv creates empty, unspecified file
favorite count: 0
upvote count: 5
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51051296
accepted answer: http://stackoverflow.com/a/51051296
tagged with: python

http://stackoverflow.com/q/51103763
tagged with: celery-task
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: django
tagged with: celery
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/89196729
has body: I've deployed my working django application on heroku. The whole application along with the celery tasks is working in local environment. But when I deploy it in heroku the tasks are not being run. When I manually open heroku python manage.py shell and start the task from there, its running. The task is actually supposed to run when I click a button on a page. There it's not working. Files for reference: myapp/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os from vms.settings import USE_ELASTIC_SEARCH os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vms.settings') app = Celery('vms', broker=os.environ.get('REDIS_URL','redis://localhost'), include=['cve.tasks','cpe.tasks']) app.conf.update( result_backend='django-db', result_expires=86400*2, timezone = 'Asia/Kolkata' ) if __name__ == '__main__': app.start() Procfile web: gunicorn vms.wsgi worker: celery -A vms worker -l info [Edit] There are no errors in heroku log. import os import dj_database_url import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'blah blah' DEBUG = True ALLOWED_HOSTS = ["localhost","127.0.0.1","blahblah.herokuapp.com"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vms', 'notifications', 'cpe', 'cve', 'products', 'django_celery_results', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'vms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'contex…
has comment: http://stackoverflow.com/comment/89199172
score: 0
has title: Celery tasks not executed in Django app deployed on Heroku

http://stackoverflow.com/a/51123260
has body: Also possible like this: stock = {'apple': 1, 'banana': 4, 'orange': 10} delivery = ['apple', 'apple', 'grapefruit'] stock.update({item: delivery.count(item) + stock.get(item,0) for item in set(delivery)}) print(stock) # {'apple': 3, 'banana': 4, 'orange': 10, 'grapefruit': 1})
answers question: http://stackoverflow.com/q/51123094
score: 0
type: Answer

http://stackoverflow.com/a/51134043
downvote count: 0
has body: It waits up to 1 millisecond for the user to press a key. It then takes the value of the key read, and ANDs it with 0xFF which masks off (removes) anything above the bottom 8-bits and compares the result of that with the ASCII code for the letter q which would mean the user has decided to quit by pressing q on the keyboard. During that time, it also updates and refreshes any OpenCV windows that are currently displaying images by responding to display events. In short, it waits for up to 1 ms for a keypress and then checks if quit was pressed.
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/89252878
answers question: http://stackoverflow.com/q/51133545

http://stackoverflow.com/comment/89094352
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51049603
has text: Sorry for not writing the question better. Thank you for the advice. The code takes awhile to run for the data set I am trying to generate.
score: 0

http://stackoverflow.com/comment/89183340
comment on: http://stackoverflow.com/a/51097035
type: Comment
has text: What about number of days to better calculate K and N in my formula? Should I assume a year of 365, 360 (I don't understand why the website video reports 360) or 272 (the number of days the stock market is open)?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51164351
has body: Using pandas: import pandas as pd d = '''\ "12345","string1","string2","string3","string4","string5" "67890","string6","string7","string8","string9","string10"''' l = pd.read_csv(pd.compat.StringIO(d), header=None, dtype='object').values And you have l: [['12345', 'string1', 'string2', 'string3', 'string4', 'string5'], ['67890', 'string6', 'string7', 'string8', 'string9', 'string10']]
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51164294
downvote count: 0

http://stackoverflow.com/comment/89094650
has text: I updated the outputs for each example with sys.executable results.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51051606
type: QuestionComment

http://stackoverflow.com/comment/89190698
type: QuestionComment
has text: @Chris_Rands requirement is not to use any string operations
comment on: http://stackoverflow.com/q/51101668
score: 0
type: Comment

http://stackoverflow.com/q/51062176
favorite count: 0
upvote count: 8
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51062292
has title: Pandas read data from a secure FTP server in Python 3
tagged with: ftp
type: AnsweredQuestion
score: 7
downvote count: 1
has body: I am looking for a neat solution to read data (using either read_csv or read_sas) to a Pandas Dataframe from a secure FTP server in Python 3. All the examples I can find are many lines and some for Python 2. Isn't there a neat way to insert your username+password to Pandas read_csv-like method together with an ftp url and folder?
type: Question
accepted answer: http://stackoverflow.com/a/51062292
answer count: 1
has comment: http://stackoverflow.com/comment/89114059

http://stackoverflow.com/q/51016265
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89025240
score: 1
tagged with: group-by
has answer: http://stackoverflow.com/a/51016390
tagged with: dataframe
type: Question
upvote count: 2
has body: I am trying to return a running count based off two columns in a pandas df. For the df below I'm trying to determine the count based off Column 'Event' &amp; Column 'Who'. import pandas as pd import numpy as np d = ({ 'Event' : ['A','B','E','','C','B','B','B','B','E','C','D'], 'Space' : ['X1','X1','X2','','X3','X3','X3','X4','X3','X2','X2','X1'], 'Who' : ['Home','Home','Even','Out','Home','Away','Home','Away','Home','Even','Away','Home'] }) d = pd.DataFrame(data = d) I have tried the following. df = d.groupby(['Event', 'Who'])['Space'].count().reset_index(name="count") Which produces this: Event Who count 0 Out 1 1 A Home 1 2 B Away 2 3 B Home 3 4 C Away 1 5 C Home 1 6 D Home 1 7 E Even 2 But I would like it to be a running count rather than a total count. Can df = d.groupby(['Event', 'Who'['Space'].count().reset_index(name="count") be amended to filter additional constraints or will it have to be a mask function or similar? So my intended Output is: A_Away A_Home B_Away B_Home C_Away C_Home D_Away D_Home Event Space Who 0 1 A X1 Home 1 B X1 Home 2 E X2 Even 3 Out 4 1 C X3 Home 5 1 B X3 Away 6 1 B X3 Home 7 B X4 Away 8 2 B X3 Home 9 2 E X2 Even 10 1 C X2 Away 11 1 D X1 Home So the count gets added to the row. Not a total count for the entire dataset.
has title: Return running count of values in a pandas df
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51016390
tagged with: python

http://stackoverflow.com/q/51134971
possible better answer: http://stackoverflow.com/a/51135848
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51135848
has body: Regarding example from documentation: https://docs.python.org/2/library/queue.html#Queue.Queue.get def worker(): while True: item = q.get() do_work(item) q.task_done() How actually the worker would know all work is done, the queue is empty and we can exit? I don't understand it...
upvote count: 3
has comment: http://stackoverflow.com/comment/89254047
type: Question
accepted answer: http://stackoverflow.com/a/51135373
answer count: 2
has comment: http://stackoverflow.com/comment/89254390
has title: Python - how exactly Queue works?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51135373
tagged with: multithreading
tagged with: python

http://stackoverflow.com/a/51014316
type: Answer
answers question: http://stackoverflow.com/q/51012350
has body: There are a number of ways to do this, but I prefer to use a central "window manager" to acts as the owner and inter-communication hub of the two windows. Below is a sample of that technique that will need to be adapted to your needs. Note that I use Qt5. I tested on Qt5, and then attempted to translate to Qt4 without testing. It should be right, but might need a little tweeking. from PyQt4 import QtCore, QtGui class WindowManager(QtCore.QObject): """ Inheriting from QObject has benefits. For instance, the WindowManager can not have pyQtSignal members, if needed """ def __init__(self): super(WindowManager, self).__init__() self.firstWindow = FirstWindow(self) self.secondWindow = SecondWindow(self) self.firstWindow.show() self.secondWindow.show() class FirstWindow(QtGui.QMainWindow): def __init__(self, manager): super(FirstWindow, self).__init__() self.manager = manager self.mainWidget = QtGui.QWidget() self.setCentralWidget(self.mainWidget) self.mainLayout = QtGui.QVBoxLayout(self.mainWidget) self.clickyButton = QtGui.QPushButton("Click me") self.mainLayout.addWidget(self.clickyButton) self.clickyButton.clicked.connect(self.clickyButtonClicked) def clickyButtonClicked(self, checked=None): self.manager.secondWindow.setMessage("Clicky button clicked") class SecondWindow(QtGui.QMainWindow): def __init__(self, manager): super(SecondWindow, self).__init__() self.manager = manager self.mainWidget = QtGui.QWidget() self.setCentralWidget(self.mainWidget) self.mainLayout = QtGui.QVBoxLayout(self.mainWidget) self.messageBox = QtGui.QLabel() self.mainLayout.addWidget(self.messageBox) def setMessage(self, message): self.messageBox.setText(message) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) manager = WindowManager() sys.exit(app.exec_())
score: 0

http://stackoverflow.com/q/51128387
type: Question
has title: What is the difference between @property and getattr()?
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/89243246
upvote count: 2
answer count: 1
tagged with: oop
has body: What is the difference between @property, @property.setter and getattr(), setattr(). When will I use them? If both are the same, which one is preferred to use in python 3.x? I am new to python and not understanding where to use and how to use them with OO python I have gone through many websites, but I'm not sure which one to use. Please give me some real time example. Appreciate your help. EX: getattr() class emp: name='Harsh' salary='25000' def show(self): print self.name print self.salary e1 = emp() print getattr(e1,'name') setattr(e1,'height',152) @ property class P: def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x &lt; 0: self.__x = 0 elif x &gt; 1000: self.__x = 1000 else: self.__x = x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89241793
downvote count: 4
has answer: http://stackoverflow.com/a/51129169
linked to: http://stackoverflow.com/q/2627002
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89242982

http://stackoverflow.com/comment/89296266
type: AnswerComment
score: 0
type: Comment
has text: I guess you have infinite recursion which is dangerous. You need to optimize your code so that it doesn't exceed the recursion limit.
comment on: http://stackoverflow.com/a/51155707

http://stackoverflow.com/q/51156221
downvote count: 2
has comment: http://stackoverflow.com/comment/89336422
has title: Compiling and linking Python module in Mac Os
score: -2
has body: I am working on a Python module. I have C source file and a compiled library. I was having problems when linking in Mac Os, so I followed the instructions provided at Python runtime_library_dirs doesn&#39;t work on Mac. This post says that add extra link arguments should be added when linking in Mac Os. It also says that install_name_tool should be used to change the install name of the library. However, I am getting this error message when using install_name_tool: string table not at the end of the file (can't be processed) in file: The library is compiled from Go source.
tagged with: http://stackoverflow.com/tag/c
type: Question
upvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/19123623
has answer: http://stackoverflow.com/a/51201529
tagged with: go
has comment: http://stackoverflow.com/comment/89302290
has comment: http://stackoverflow.com/comment/89339143
tagged with: python
has comment: http://stackoverflow.com/comment/89302188
has comment: http://stackoverflow.com/comment/89297347
has comment: http://stackoverflow.com/comment/89302142
has comment: http://stackoverflow.com/comment/89297625
has comment: http://stackoverflow.com/comment/89317508
type: UnansweredQuestion

http://stackoverflow.com/comment/89111191
comment on: http://stackoverflow.com/q/51060477
score: 0
type: Comment
type: QuestionComment
has text: @BcK In fairness to myself, I've already hit the rep cap for the day and just wanted to write a `itertools` answer. ;) ...Though closing as duplicate was probably the more accurate thing to do.

http://stackoverflow.com/q/51026983
upvote count: 1
has answer: http://stackoverflow.com/a/51027093
tagged with: python
has title: Install Keras/Tensorflow on Mac with cpu python2.7
has answer: http://stackoverflow.com/a/51027760
tagged with: cpu
has comment: http://stackoverflow.com/comment/89046533
has body: I recently found an article that indicates that the conventional methods for downloading python machine learning modules such as tensorflow and keras are not optimized for computers with a cpu. How can I configure tensorflow and keras to make it most compatible with my processor on MacOSX in python 2.7? If it helps, I use pycharm to download most of my libraries and for my coding interface.
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89046607
type: Question
linked to: http://stackoverflow.com/q/37660312
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/50044649
tagged with: python-2.7
score: 1
tagged with: macos
has comment: http://stackoverflow.com/comment/89046415
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51051436
tagged with: mod-wsgi
linked to: http://stackoverflow.com/q/39464485
type: Question
has comment: http://stackoverflow.com/comment/89093997
score: 3
has comment: http://stackoverflow.com/comment/89095199
upvote count: 3
has body: Scenario: I'm using Python Falcon framework for my REST API service. The application is initially run by Gunicorn. Right now when I call https://example.com:8000/, I get a proper response that the API logic dictates. Goal: I want to deploy it on Apache2 along with mod_wsgi on my personal development server. The API would still be running under Gunicorn, and Apache should interact with Gunicorn whenever a request is made on that end-point. Directory structure: | - abc_service | - abc_service | - __init__.py | - app.py | - wsgi.py | - .abc_venv The source code for app.py looks something like this: import falcon from .abc import ABC api = application = falcon.API() # pylint: disable=invalid-name # Creating a unique GET resource from the ABC class test_handler_resource = ABC() # pylint: disable=invalid-name # Mapping the HTTP GET endpoint with the unique resource api.add_route('/abc', test_handler_resource) # Mapping the HTTP POST endpoint with the unique resource api.add_route('/abc/filters', test_handler_resource) In my wsgi.py, I have the following contents: from abc_service import application The configuration for Apache in /etc/apache2/sites-available/000-default.conf is as follows: # WSGI WSGIDaemonProcess python-path=/home/uname/abc-service/src/abc_service/.abc_venv/lib/python3.5/site-packages WSGIScriptAlias /abc /home/uname/abc-service/src/abc_service/wsgi.py ProxyPass /abc http://localhost:8000/abc ProxyPassReverse /abc http://localhost:8000/abc &lt;Location /abc&gt; AuthType None Require all granted # Always set these headers. Header always set Access-Control-Allow-Origin "https://example.com" Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT" Header always set Access-Control-Max-Age "1000" Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token" &lt;/Location&gt; I can't find any helpful resource on the web regarding the same on the web that uses this c…
tagged with: apache
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52502968
accepted answer: http://stackoverflow.com/a/52502968
favorite count: 0
has comment: http://stackoverflow.com/comment/89094036
tagged with: python
has title: Deploying Python Falcon on Apache2 with mod_wsgi
type: AnsweredQuestion

http://stackoverflow.com/a/51100838
answers question: http://stackoverflow.com/q/51098540
score: 1
has comment: http://stackoverflow.com/comment/89199606
has comment: http://stackoverflow.com/comment/89200332
has body: Got it to work! Had to cast the types in the insert code as: ins = Sensor(sensor_id = int(sensor_coords['sensor_code'][0]), code = int(sensor_coords['sensor'][0]), lat = float(sensor_coords['lat'][0]), lon = float(sensor_coords['long'][0]), x = float(sensor_coords['x'][0]), y = float(sensor_coords['y'][0])) Didn't realize numpy used its own int and float types...
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/127840853
has comment: http://stackoverflow.com/comment/127824161
accepted answer of: http://stackoverflow.com/q/51098540
upvote count: 1

http://stackoverflow.com/comment/89196924
comment on: http://stackoverflow.com/a/51102652
score: 0
type: AnswerComment
type: Comment
has text: That's worked brilliantly, thank you so much! In addition to that, do you know how I can get the difference plot to be a subplot, such that both plots are on the same figure? The difference plot would ideally be below the main plot.

http://stackoverflow.com/comment/89101739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51055568
score: 0
has text: What's the problem with your code?

http://stackoverflow.com/a/51060856
upvote count: 2
has comment: http://stackoverflow.com/comment/89213026
has body: TL;DR: the actual issue had nothing to do with circular dependency — it turned out to be misconfiguration of my virtual environment (Python version was actually 2.7.10, as was suggested in the comment by hjpotter92). How I found out it was the cause (posting as a collection of recipes for debugging your Python venv, which might later be handy for myself, and hopefully someone else): Right after reading the comments to my quertion (hjpotter92's comment, in particular) I've rushed to check the version of Python inside the virtualenv I run my app from (even though I've checked it right before posting the question — you can't be too careful in this kind of things =). Running (inside the virtual environment): python --version gave me (just as I have expected): Python 3.6.1 I wasn't convinced, though =). As was suggested by the this answers: 1 and 2, I have added the following to code to both modules: app.py and test_mail.py (in order to check which version of Python they are actually ran by): import sys ... print(sys.version) it was outputting (surprisingly for me): 2.7.10 Ok, clearly something is wrong here. I have decided to refresh my basic knowledge of virtualenv setup. The first article I stumbled upon, suggested pip --version as a second step of the setup process (after python --version). Having nothing to loose I ran it (inside the virtual environment, of course), and (to my amazement) it gave me: pip 9.0.1 from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (python 2.7) So, somehow pip used inside the virtual environment was a system level one... At this point I was in doubt that my app was running from virtualenv at all. Following the recipe from this answer (and comment to it), I have composed and added to app.py and test_mail.py, the following snippet: import sys ... if hasattr(sys, 'real_prefix'): print('Python 2 venv') elif (hasattr(sys, 'base_prefix') and sys.prefix != sys.base_prefix): print('Python 3 venv') else: prin…
answers question: http://stackoverflow.com/q/51039756
type: Answer
has comment: http://stackoverflow.com/comment/89133113
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89122698

http://stackoverflow.com/q/51149809
linked to: http://stackoverflow.com/q/24832715
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/89283441
downvote count: 2
tagged with: mixed
type: Question
has answer: http://stackoverflow.com/a/51149984
tagged with: numpy
has comment: http://stackoverflow.com/comment/89298292
linked to: http://stackoverflow.com/q/49751000
upvote count: 5
tagged with: arrays
has title: Python ndarray with elements of different types
has body: I wanted to create an array to hold mixed types - string and int. The following code did not work as desired - all elements got typed as String. &gt;&gt;&gt; a=numpy.array(["Str",1,2,3,4]) &gt;&gt;&gt; print a ['Str' '1' '2' '3' '4'] &gt;&gt;&gt; print type(a[0]),type(a[1]) &lt;type 'numpy.string_'&gt; &lt;type 'numpy.string_'&gt; All elements of the array were typed as 'numpy.string_' But, oddly enough, if I pass one of the elements as "None", the types turn out as desired: &gt;&gt;&gt; a=numpy.array(["Str",None,2,3,4]) &gt;&gt;&gt; print a ['Str' None 2 3 4] &gt;&gt;&gt; print type(a[0]),type(a[1]),type(a[2]) &lt;type 'str'&gt; &lt;type 'NoneType'&gt; &lt;type 'int'&gt; Thus, including a "None" element provides me with a workaround, but I am wondering why this should be the case. Even if I don't pass one of the elements as None, shouldn't the elements be typed as they are passed?
answer count: 2
tagged with: types
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51157492

http://stackoverflow.com/comment/89016708
has text: https://stackoverflow.com/questions/16788310/what-is-the-difference-between-css-selector-xpath-which-is-betteraccording-t
score: 0
comment on: http://stackoverflow.com/a/51011917
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89026725
comment on: http://stackoverflow.com/a/51011519
score: 0
type: AnswerComment
has text: Note: TF and DF might be different though. The OP code seems to be asking for DF `#Count in how many reviews the word appears` ;P I encourage the OP user to look at https://drive.google.com/file/d/1lxRclJablHF-veuRzWBgJ9gaqMNo6fPa/view
type: Comment

http://stackoverflow.com/comment/89037741
comment on: http://stackoverflow.com/a/51022293
type: AnswerComment
score: 0
has text: Thank you very much for replies but this did not work either. I got the below error: ValueError: iAt based indexing can only have integer indexers
type: Comment

latex
tags question: http://stackoverflow.com/q/51021971
type: Tag
tags question: http://stackoverflow.com/q/51060126
tag name: latex

http://stackoverflow.com/q/51114759
tagged with: python
has title: Python process not running in paralell
has comment: http://stackoverflow.com/comment/89215939
has comment: http://stackoverflow.com/comment/89215835
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89216222
has body: I have a very simple process and it seems its not running in paralell. Heres an example to illustrate that: class BattleQueueProcess(Process): def __init__(self): self._runWorker = True super(Process, self).__init__() def run(self): while self._runWorker: print('loop') time.sleep(1) def stop(self): self._runWorker = False self.join() self.terminate() So i have this following code. print('starting') process = BattleQueueProcess() process.start() print('started') However my output is ´starting´ ´loop´ ´loop´ ´loop´ ... and so on ´started´ is never printed. Why is the process not running in parallel ?
has comment: http://stackoverflow.com/comment/89215847
has answer: http://stackoverflow.com/a/51115785
type: Question
has comment: http://stackoverflow.com/comment/89216041
has comment: http://stackoverflow.com/comment/89216169
answer count: 1
has comment: http://stackoverflow.com/comment/89215970
has comment: http://stackoverflow.com/comment/89215886
score: 0
has comment: http://stackoverflow.com/comment/89216323

http://stackoverflow.com/a/51126605
has comment: http://stackoverflow.com/comment/89249572
has body: You need to configure the (one and only) root logger in the main module of your software. This is done by calling logger = logging.getLogger() #without arguments instead of logger = logging.getLogger(__name__) (Python doc on logging) The second example creates a separate, child logger with the name of your script. If there are no handlers defined in the submodules, the log message is being passed down to the root logger to handle it. A related question can be found here: Python Logging - How to inherit root logger level &amp; handler
has comment: http://stackoverflow.com/comment/89238153
has comment: http://stackoverflow.com/comment/89244020
has comment: http://stackoverflow.com/comment/89243810
accepted answer of: http://stackoverflow.com/q/51125808
has comment: http://stackoverflow.com/comment/89238388
has comment: http://stackoverflow.com/comment/89238178
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89238658
downvote count: 0
answers question: http://stackoverflow.com/q/51125808
has comment: http://stackoverflow.com/comment/89238221
has comment: http://stackoverflow.com/comment/89249735
has comment: http://stackoverflow.com/comment/89247712
type: Answer
has comment: http://stackoverflow.com/comment/89238255
score: 2
has comment: http://stackoverflow.com/comment/89249666
upvote count: 2
has comment: http://stackoverflow.com/comment/89249786

http://stackoverflow.com/q/51055696
possible better answer: http://stackoverflow.com/a/51055941
tagged with: python-3.x
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51055958
has body: I am making a python blackjack game. I have an error in this code which I can't figure out. In the end when I test out the hit function and print the hand, it does not show me the list. Instead, it says [&lt;main.Card object at 0x02F9F5F0>]. Here is my code. #Blackjack import random suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts'] ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'] values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} game_on = True class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return(f'{self.rank} of {self.suit}') class Deck: def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): deck_comp = '' for card in self.deck: deck_comp += '\n ' + card.__str__() return deck_comp def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card class Hand: def __init__(self): self.cards = [] # start with an empty list as we did in the Deck class self.value = 0 # start with zero value self.aces = 0 # add an attribute to keep track of aces def add_card(self, card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': self.aces += 1 # add to self.aces def adjust_for_ace(self): while self.value &gt; 21 and self.aces: self.value -= 10 self.aces -= 1 class Chips: def __init__(self): self.total = 100 self.bet = 0 def win_bet(self): self.chips += self.bet def lose_bet(self): self.chips -= self.bet def go_for_bet(chips): while True: try: chips.bet = int(input('Please enter a betting amount: ')) except TypeError: print('Please enter an integer') continue else: if chips.bet &gt; chips.total: print(f'You do not have enough chips to bet {chips.bet}') else: break def hit(deck, hand): hand.add_card(deck.deal()) hand.adjus…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89102180
has answer: http://stackoverflow.com/a/51055988
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51055988
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51055941
has title: __str__ python method issue
favorite count: 0

http://stackoverflow.com/q/51117106
tagged with: tensorflow
type: Question
score: 4
has title: How to do one-dimensional linear interpolation in TensorFlow efficiently?
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/76408098
answer count: 2
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/45884453
has answer: http://stackoverflow.com/a/76687239
type: UnansweredQuestion
tagged with: python
has body: I need to do one-dimensional linear interpolation for building my model in TensorFlow. I tried to follow the definition and write a linear interpolation function. But it is computationally intensive and almost unusable in my model. Is there any efficient method to perform one-dimensional interpolation in TensorFlow? Here is my code for linear interpolation. similar to NumPy.interp(). t contains interpolated values and it has shape [64,64]. x contains x-coordinates data points and it has shape [91,1]. y contains y-coordinates data points and it has shape [91,1]. t and x are numpy arraies and y is a tensor. def tf_interpolation_v2(t, x, y, left, right): # perform one dimensional linear interpolation # returns tensor same shape as t # t is the interpolated values # x is the The x-coordinates of the data points, must be increasing # y is the The y-coordinates of the data points, same length as x. # left is the Value to return for x &lt; x[0] # right is the Value to return for x &gt; x[-1] t = np.asarray(t) t = t.astype(np.float32) x = x.astype(np.float32) y = tf.cast(y, tf.float32) t_return = [] t_return_row = [] for row in t: for v in row: if v &lt; x[0]: # value smaller than x[0] a = left t_return_row.append(a) elif v &gt; x[-1]: # value larger than x[-1] a = right t_return_row.append(a) else: # finding interval where t is in nearest_index = 0 # initialize interval index for i in range(1, len(x) - 1): if (v &gt;= x[i]) &amp; (v &lt;= x[i+1]): # if t larger than x[i] but smaller than x[i+1]. i is the index nearest_index = i # we need break k = tf.subtract(tf.gather(y, nearest_index + 1), tf.gather(y, nearest_index)) # calculate slope de_x = x[nearest_index + 1] - x[nearest_index] k = tf.divide(k, de_x) b_sub = tf.multiply(k, x[nearest_index]) # calculate bias b = tf.subtract(tf.gather(y, nearest_index), b_sub) a = tf.multiply(k, v) a = tf.add(a, b) t_return_row.append(a) t_return.append(t_return_row) t_return_row = [] t_return = tf.convert_to_tensor(t_return) t_return …

http://stackoverflow.com/a/51136818
has comment: http://stackoverflow.com/comment/97876629
has comment: http://stackoverflow.com/comment/89281656
has comment: http://stackoverflow.com/comment/89282878
has comment: http://stackoverflow.com/comment/97345231
answers question: http://stackoverflow.com/q/51136288
has comment: http://stackoverflow.com/comment/97882971
has comment: http://stackoverflow.com/comment/97877432
score: 0
has comment: http://stackoverflow.com/comment/89263483
type: Answer
has body: To release the session reliable you should use a try/except/finally construction like this: try: #Your code except: print("something unexpected happend") finally: self.session.console.power_down()

http://stackoverflow.com/comment/89288036
type: QuestionComment
comment on: http://stackoverflow.com/q/51152245
score: 0
has text: Sorry, it was capital letter so they are identical. But the issue is that my data structure is very complicated, it is basically a NoSQL DB which retrieve this from different resources so duplication is and needs to be part of the structure for that field. I need a python filter for the display output only so that to show them neatly rather than applying it from the DB level.
type: Comment

http://stackoverflow.com/q/51159622
tagged with: regex
tagged with: nlp
has title: regex pattern/text analysis
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/89302552
has answer: http://stackoverflow.com/a/51159717
type: Question
has comment: http://stackoverflow.com/comment/89302515
score: -3
upvote count: 0
answer count: 1
favorite count: 0
has body: **edit: I’ve looked more into it and I’ll present it easier for both you guys and for me: specific str, a bunch of stuff that I can’t know the str inside the square brackets is what I need to find. So how do I present the bunch of stuff inside? I tried .* and .*? And both did not work..
tagged with: python

http://stackoverflow.com/q/51036659
downvote count: 1
type: Question
has body: [{"id":360015384872,"action":"article_created","timestamp":"2018-06-26T05:43:05Z","breadcrumbs"] lets say i have timestamp: 2018-06-26T05:43:05Z and another timestamp2: 2018-06-26T05:43:55Z - this one is more current by 50 seconds i want to make it so that if timestamp2 > timestamp1 (meaning timestamp2 is the latest time or more current), print (timestamp2) how can i do that in python json? i know how i would do this if it was integers which is timestamp2 > timestamp1.. but seem more difficult with timestamp
has answer: http://stackoverflow.com/a/51036724
score: 0
has answer: http://stackoverflow.com/a/51036728
answer count: 2
favorite count: 0
linked to: http://stackoverflow.com/q/21378977
type: UnansweredQuestion
tagged with: python
tagged with: timestamp
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
has comment: http://stackoverflow.com/comment/89065152
has title: comparing 2 timestamp in python json

http://stackoverflow.com/a/53921209
answers question: http://stackoverflow.com/q/51146399
score: 2
downvote count: 0
upvote count: 2
has body: I'm just a newbie.. but check this out. It seems like to work well though. def is_repeating_playlist(self): n = self x = set() while n is not None: x.add(n) n = n.next if n in x: return True return False
type: Answer

http://stackoverflow.com/a/51609363
upvote count: 22
has body: If your server already processing maximum_concurrent_rpcs number of requests concurrently, and yet another request is received, the request will be rejected immediately. If the ThreadPoolExecutor's max_workers is less than maximum_concurrent_rpcs then after all the threads get busy processing requests, the next request will be queued and will be processed when a thread finishes its processing. I had the same question. To answer this, I debugged a bit what happens with maximum_concurrent_rpcs. The debugging went to py36/lib/python3.6/site-packages/grpc/_server.py in my virtualenv. Search for concurrency_exceeded. The bottom line is that if the server is already processing maximum_concurrent_rpcs and another request arrives, it will be rejected: # ... elif concurrency_exceeded: return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted, b'Concurrent RPC limit exceeded!'), None # ... I tried it with the gRPC Python Quickstart example: gRPC quick start python example In the greeter_server.py I modified the SayHello() method: # ... def SayHello(self, request, context): print("Request arrived, sleeping a bit...") time.sleep(10) return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) # ... and the serve() method: def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), maximum_concurrent_rpcs=2) # ... Then I opened 3 terminals and executed the client in them manually (as fast as I could using python greeter_client.py: As expected, for the first 2 clients, processing of the request started immediately (can be seen in the server's output), because there were plenty of threads available, but the 3rd client got rejected immediately (as expected) with StatusCode.RESOURCE_EXHAUSTED, Concurrent RPC limit exceeded!. Now to test what happens when there are not enough threads given to ThreadPoolExecutor I modified the max_workers to be 1: server = grpc.server(futures.ThreadPoolExecutor(max_workers=1), maximum_concurrent_rpcs=2) I ran my 3 c…
downvote count: 0
answers question: http://stackoverflow.com/q/51089746
accepted answer of: http://stackoverflow.com/q/51089746
score: 22
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51049340
has answer: http://stackoverflow.com/a/51049381
has body: I have a list lst = ['orb|2|3|4', 'obx|2|3|4', 'orb|2|3|4', 'obx|1|2|3', 'obx|1|2|3','obx|1|2|3'] How can I group the list by the initial three lines, so that in the end it's like this. Grouping occurs on three characters of the line. If the line starts with "orb", then subsequent lines are added to the list that begins with this line. Thanks for the answer. result = [['orb|2|3|4', 'obx|2|3|4'], ['orb|2|3|4', 'obx|1|2|3', 'obx|1|2|3','obx|1|2|3']]
favorite count: 0
has comment: http://stackoverflow.com/comment/89091817
has answer: http://stackoverflow.com/a/51052442
has comment: http://stackoverflow.com/comment/89090347
possible better answer: http://stackoverflow.com/a/51049381
tagged with: python
accepted answer: http://stackoverflow.com/a/51052442
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89091113
upvote count: 3
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89091551
has title: Grouping the nested attribute list in Python
has comment: http://stackoverflow.com/comment/89089743
score: 0
answer count: 2

http://stackoverflow.com/q/51042086
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
tagged with: django-cms
type: Question
tagged with: django-models
has answer: http://stackoverflow.com/a/51045745
has body: I have created a website using Django cms. When I save the custom plugin the template is not rendered. But it is rendered when I refresh the page. So, how to refresh the page while saving the django cms custom plugin or any other way to render the template when the plugin is saved. But the content is saved in the admin side. I am not able to see the content in the template.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: How to refresh the page when custom plugin is saved?

http://stackoverflow.com/q/51098590
has comment: http://stackoverflow.com/comment/89184792
tagged with: python
has body: the following script is working perfectly fine for IPv4 but however my job is to do same for IPv6.. #!/usr/bin/python import pyping response = pyping.ping('8.8.8.8') if response.ret_code == 0: print("reachable") else: print("unreachable") is there any way.. i tried to install aioping or aio_ping.. but didnt work,.. is there any workaround to run the same as above for IPv6 in linux machines
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89186248
upvote count: 1
tagged with: ping
type: Question
linked to: http://stackoverflow.com/q/12101239
has comment: http://stackoverflow.com/comment/89184703
score: 1
has comment: http://stackoverflow.com/comment/89184948
has title: Python ping list of IPv6 hosts and make a dictionary of reachable and unreachable hosts with time
has comment: http://stackoverflow.com/comment/89185093
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51098823
accepted answer: http://stackoverflow.com/a/51098823

http://stackoverflow.com/q/51089238
tagged with: python
has title: How is the usage of @classmethod causing difference in outputs?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51089299
downvote count: 0
has body: I was learning about classes and objects in Python when I came across this dilemma. Below are two cases of the same code, one without @classmethod and the other with @classmethod: #without @classmethod &gt;&gt;&gt; class Human: ... name = "Rounak" ... def change_name(self, new_name): ... self.name=new_name ... &gt;&gt;&gt; Human().change_name("Agarwal") &gt;&gt;&gt; print(Human().name) Rounak #with @classmethod &gt;&gt;&gt; class Human: ... name = "Rounak" ... @classmethod ... def change_name(self, new_name): ... self.name=new_name ... &gt;&gt;&gt; Human().change_name("Agarwal") &gt;&gt;&gt; print(Human().name) Agarwal As you can see that when not using @classmethod, the name doesn't change from Rounak to Agarwal. I don't seem to understand how. I went through the definition of @classmethod in the Python documentation and also went through various questions on Stack Overflow that have detailed explanation about the usage of @classmethod but I still don't understand how it is causing this difference in output. I am new to Python, so if I am missing some fundamental knowledge, please let me know.
score: 6
possible better answer: http://stackoverflow.com/a/51089299
type: Question
upvote count: 6
has comment: http://stackoverflow.com/comment/92098760
has answer: http://stackoverflow.com/a/51089463
answer count: 3
has answer: http://stackoverflow.com/a/51089262
accepted answer: http://stackoverflow.com/a/51089262
favorite count: 0

http://stackoverflow.com/q/51154330
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17995024
tagged with: python
has comment: http://stackoverflow.com/comment/89361729
duplicate of: http://stackoverflow.com/q/17995024
tagged with: join
has comment: http://stackoverflow.com/comment/89291783
has comment: http://stackoverflow.com/comment/89292058
tagged with: group-by
type: Question
score: 0
has body: I want to figure out number of customers per week during 6 years and add an extra column of number. this is what I tried: df = df_eind'year', 'week'.copy() countv = df.groupby(['year', 'week']).year.count() and then joined it with the main table which has the customer information like this: df4 = df_eind.join(countv) but gives an error because can not join a series with a data frame. can you please help me. the data is like this(ex): year week 2012 2 2018 50 2015 16 2012 2 and the file view should be like this(ex): year week count 2012 2 2 2015 16 1 2018 50 1
tagged with: pandas
has title: counting number of customers per week during 6 years
answer count: 0

api
tags question: http://stackoverflow.com/q/51091402
tags question: http://stackoverflow.com/q/51073780
tags question: http://stackoverflow.com/q/51029120
tags question: http://stackoverflow.com/q/51112426
type: Tag
tags question: http://stackoverflow.com/q/51131301
tags question: http://stackoverflow.com/q/51128072
tags question: http://stackoverflow.com/q/51066740
tags question: http://stackoverflow.com/q/51047307
tags question: http://stackoverflow.com/q/51067409
tags question: http://stackoverflow.com/q/51089470
tag name: api
tags question: http://stackoverflow.com/q/51134093
tags question: http://stackoverflow.com/q/51088698
tags question: http://stackoverflow.com/q/51027259
tags question: http://stackoverflow.com/q/51068938
tags question: http://stackoverflow.com/q/51113767
tags question: http://stackoverflow.com/q/51156632
tags question: http://stackoverflow.com/q/51142123
tags question: http://stackoverflow.com/q/51065046
tags question: http://stackoverflow.com/q/51045895

http://stackoverflow.com/comment/89149488
score: 1
has text: @Zion Try the solution given by `jterrace` https://stackoverflow.com/questions/7217196/python-delete-old-files
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51080451

http://stackoverflow.com/comment/89089204
has text: So, the problem is probably with some invisible whitespace. In most cases, you may either match it with `\s*` or `\W*` (any 0+ non-word chars).
comment on: http://stackoverflow.com/q/51044993
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51082758
tagged with: apache-spark-sql
possible better answer: http://stackoverflow.com/a/57769250
favorite count: 0
has body: I have a dataframe which consists lists in columns similar to the following. The length of the lists in all columns is not same. Name Age Subjects Grades [Bob] [16] [Maths,Physics,Chemistry] [A,B,C] I want to explode the dataframe in such a way that i get the following output- Name Age Subjects Grades Bob 16 Maths A Bob 16 Physics B Bob 16 Chemistry C How can I achieve this?
tagged with: apache-spark
upvote count: 49
tagged with: python
has answer: http://stackoverflow.com/a/77625655
has comment: http://stackoverflow.com/comment/89155944
has answer: http://stackoverflow.com/a/51082875
accepted answer: http://stackoverflow.com/a/51085148
downvote count: 0
has comment: http://stackoverflow.com/comment/89156774
has answer: http://stackoverflow.com/a/57769250
has answer: http://stackoverflow.com/a/74974161
has answer: http://stackoverflow.com/a/51085148
answer count: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/71789875
score: 49
tagged with: pyspark
has answer: http://stackoverflow.com/a/70956187
tagged with: dataframe
has answer: http://stackoverflow.com/a/74502657
has title: How to explode multiple columns of a dataframe in pyspark
type: Question

http://stackoverflow.com/comment/89099951
has text: What is the outcome of this logic?
comment on: http://stackoverflow.com/a/51042882
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89171181
type: AnswerComment
score: 0
type: Comment
has text: This works but only if your `range` starts at 0 and has no steps
comment on: http://stackoverflow.com/a/51091411

http://stackoverflow.com/comment/89224050
score: 0
has text: It would help a lot if you gave an example of two arrays and the desired result.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51119074

http://stackoverflow.com/comment/89084700
type: AnswerComment
score: 0
has text: you should explain all that in the answer, anyway still lack some logit there
type: Comment
comment on: http://stackoverflow.com/a/51046595

http://stackoverflow.com/a/60598204
type: Answer
has body: I got this error while installing mysqlclient in my Django project. _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.14.26428\bin\HostX86\x64\cl.exe' failed with exit status 2 I have found workaround to fix this issue. The reason was to mysqlclient version mismatch according to your Python version First, You can check python version python --version And then You can install mysqlclient version according to python version. If python version is 3.7, then you can install mysqlclient==1.3.14 or directly download mysqlclient-1.3.14-cp37-cp37m-win_amd64.whl file. If you python version is 3.6, then you can install mysqlclient==1.3.13 or directly download mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl file.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51118963

http://stackoverflow.com/a/51076150
has comment: http://stackoverflow.com/comment/89141463
type: Answer
has comment: http://stackoverflow.com/comment/89141280
has comment: http://stackoverflow.com/comment/89141237
downvote count: 1
answers question: http://stackoverflow.com/q/51076123
upvote count: 5
has comment: http://stackoverflow.com/comment/89141498
score: 4
accepted answer of: http://stackoverflow.com/q/51076123
has comment: http://stackoverflow.com/comment/89141193
has body: Instead of pasing pk as GET argument you should pass it as part of url like this: http://127.0.0.1:8000/api/v1/deployments/1/ URL you are trying to use http://127.0.0.1:8000/api/v1/deployments/?pk=1/ performed by DeploymentsList since it's not contain pk url kwarg. Also you should serialize object before return it as response: class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView): def retrieve(self, request, *args, **kwargs): pk = self.kwargs.get('pk') object = DeploymentOnUserModel.objects.get(pk=kwargs['pk']) serializer = DeploymentOnUserSerializer(object) return Response(serializer.data)
type: AcceptedAnswer

http://stackoverflow.com/comment/89282605
type: Comment
comment on: http://stackoverflow.com/a/51130341
score: 0
type: AnswerComment
has text: Is not clear to me how to stop it (coding it right now). By checking the nr of elements in a solution you would stop with 14-14-18 and if you do want to check the top solution you need to have all the combination for finding the best one.

http://stackoverflow.com/comment/89155737
comment on: http://stackoverflow.com/a/51083615
type: Comment
has text: but when I create fig = plt.figure() inside loop. I only get one plot. I want to use same x values but different y values on the same plot
score: 0
type: AnswerComment

http://stackoverflow.com/q/51131805
tagged with: python
has title: QGridLayout Widgets Overlapping
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I am trying to create a program where the user has three options to answer a question. I used QGridLayout for this but only the last widget added to the QGridLayout is shown. Expected: ################################ # Text # ################################ ########## ########## ########## #Button 1# #Button 2# #Button 3# ########## ########## ########## Reality: ########## #Button 3# ########## Simplified Python 3 Code (No Text Widget): from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys QApp = QApplication(sys.argv) QMWRoot = QMainWindow() QGLRoot = QGridLayout(QMWRoot) QMWRoot.setLayout(QGLRoot) QPB0 = QPushButton('B0x0', QMWRoot) QGLRoot.addWidget(QPB0, 0, 0) QPB1 = QPushButton('B0x1', QMWRoot) QGLRoot.addWidget(QPB1, 0, 1) QPB2 = QPushButton('B1x0', QMWRoot) QGLRoot.addWidget(QPB2, 1, 0) QMWRoot.show() sys.exit(QApp.exec_()) Original (Unfinished) Python 3 Code: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Root(QMainWindow): def __init__(self, QApp): super().__init__() self.QApp = QApp def setupUi(self): self.setWindowTitle('') self.QGLRoot = QGridLayout() self.setLayout(self.QGLRoot) self.QLBTool = QLabel() self.QLBTool.setText('Tool') self.QGLRoot.addWidget(self.QLBTool, 0, 0) self.QPB0 = QPushButton(self) self.QPB0.setText('0') self.QGLRoot.addWidget(self.QPB0, 1, 0) self.QPB1 = QPushButton(self) self.QPB1.setText('1') self.QGLRoot.addWidget(self.QPB1, 1, 1) self.QPB2 = QPushButton(self) self.QPB2.setText('2') self.QGLRoot.addWidget(self.QPB2, 1, 2) def startUi(self): self.show() def updateUi(self): pass QApp = QApplication(sys.argv) App = Root(QApp) App.setupUi() App.startUi() sys.exit(QApp.exec_())
tagged with: pyqt5
has answer: http://stackoverflow.com/a/51131940
accepted answer: http://stackoverflow.com/a/51131940
type: Question
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: qmainwindow

http://stackoverflow.com/comment/89169950
score: 0
type: Comment
has text: Thanks ,I shall try it once i am home.Outside right now. Also i did not have have any issues installing the numpy on python 3.6.6 . Just a FYI.
comment on: http://stackoverflow.com/a/51089259
type: AnswerComment

http://stackoverflow.com/comment/117384765
type: AnswerComment
has text: This function don't create any new cells, it just affects cell instance you passed to function, so you can can continue work with cell instance you passed set_cell_margins(cell, top=50, start=50, bottom=50, end=50); cell.value = "test"
type: Comment
score: 1
comment on: http://stackoverflow.com/a/55177526

http://stackoverflow.com/comment/89221829
score: 0
type: AnswerComment
has text: This is surely true, and I just corrected it, but the two still don't match.
type: Comment
comment on: http://stackoverflow.com/a/51117896

http://stackoverflow.com/a/52828096
score: 0
answers question: http://stackoverflow.com/q/51058880
type: Answer
has body: Or to only allow spaces and letters: phrases=[''.join(x for x in i if x.isalpha() or x==' ') for i in phrases] Now: print(phrases) Is: ['hi there', 'thanks']

http://stackoverflow.com/q/51032814
upvote count: 1
has comment: http://stackoverflow.com/comment/89057952
has answer: http://stackoverflow.com/a/51032854
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51032895
score: 1
has comment: http://stackoverflow.com/comment/89057885
type: Question
has body: I am new to Pandas. I have the following data types in my dataset. (The dataset is Indian Startup Funding downloaded from Kaggle.) Date datetime64[ns] StartupName object IndustryVertical object CityLocation object InvestorsName object InvestmentType object AmountInUSD object dtype: object data['AmountInUSD'].groupby(data['CityLocation']).describe() I did the above operation and found that many cities are similar for example, Bangalore Bangalore / Palo Alto Bangalore / SFO Bangalore / San Mateo Bangalore / USA Bangalore/ Bangkok I want to do following operation, but I do not know the code to this. In column CityLocation, find all cells which starts with 'Bang' and replace them all with 'Bangalore'. Help will be appreciated. I did this data[data.CityLocation.str.startswith('Bang')] and I do not know what to do after this.
answer count: 2
downvote count: 0
tagged with: data-science
favorite count: 0
accepted answer: http://stackoverflow.com/a/51032895
has title: How do I replace the similar looking values in a pandas dataframe?
tagged with: data-analysis
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/51032854

http://stackoverflow.com/comment/89056993
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51032147
has text: Try it and see. Maybe try measuring a round-trip time and half the result as that's easier than accurately synchronising clocks.

http://stackoverflow.com/a/51119875
type: Answer
has body: Here's a solution using NumPy. It requires numbers in D to have at least 2 digits. df = pd.DataFrame({'D': [1663, 8818, 9232, 9643, 31, 455, 43153, 45]}) df['F'] = df['D'] // np.power(10, np.log10(df['D']).astype(int) - 1) print(df) D F 0 1663 16 1 8818 88 2 9232 92 3 9643 96 4 31 31 5 455 45 6 43153 43 7 45 45 If all your numbers have 4 digits, you can simply use df['F'] = df['D'] // 100. For larger dataframes, these numeric methods will be more efficient than converting integers to strings, extracting the first 2 characters and converting back to int.
score: 2
has comment: http://stackoverflow.com/comment/89228280
has comment: http://stackoverflow.com/comment/89225476
downvote count: 0
answers question: http://stackoverflow.com/q/51119308
has comment: http://stackoverflow.com/comment/89225442
upvote count: 2

smtp
tags question: http://stackoverflow.com/q/51112877
tags question: http://stackoverflow.com/q/51117357
tag name: smtp
type: Tag

http://stackoverflow.com/comment/89291032
score: 0
comment on: http://stackoverflow.com/q/51102039
type: Comment
type: QuestionComment
has text: Thanks @DanielRoseman for the docs, I am following and applying them. But I will edit the question because I have some doubts

http://stackoverflow.com/a/51165723
has body: I think your view are incorrect what is this: response = requests.get(endpoint, auth=auth, params=params) instead, you should use this code: response = request.data but if you don't have problem with generics module. use this module please class MyCreateAPIView(generics.CreateAPIView): serializer_class = PackageSerializer queryset = Package.objects.all() class MyRetrieveUpdateAPIView(generics.RetrieveUpdateAPIView): serializer_class = PackageSerializer queryset = Package.objects.all()
score: -1
answers question: http://stackoverflow.com/q/51144514
type: Answer
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/89174416
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51093054
has text: and for some reason it wasn't letting me `yield` dicts before. it was working fine with `-t basic`, but not `-t crawl` for some reason :/

http://stackoverflow.com/comment/89095584
score: 0
type: Comment
has text: @bphi i don't want to create a new answer, as yours is fine, but what about putting the functions in a separate module?
type: AnswerComment
comment on: http://stackoverflow.com/a/51051934

http://stackoverflow.com/comment/89281631
type: Comment
has text: Why do you need to compare with None?
comment on: http://stackoverflow.com/q/51148873
score: 0
type: QuestionComment

http://stackoverflow.com/q/51162074
has answer: http://stackoverflow.com/a/51162140
has body: I see the below statement in the github link and would like to how this condition is executed. The right expression to the or checks for a condition but the left side is more of a assigment statement. https://github.com/wkentaro/labelme/blob/30a29a4a9c1f355cdbd69e65a0f3aad6948f458d/labelme/canvas.py#L464 shape.fill = shape.selected or shape == self.hShape
has answer: http://stackoverflow.com/a/51162128
favorite count: 0
has answer: http://stackoverflow.com/a/51162135
has comment: http://stackoverflow.com/comment/89307561
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51162134
accepted answer: http://stackoverflow.com/a/51162135
type: Question
possible better answer: http://stackoverflow.com/a/51162134
has title: python expression with or statement
upvote count: 4

http://stackoverflow.com/comment/89097630
score: 0
type: AnswerComment
type: Comment
has text: This appears to be some commercial software which can provide Access file format support in linux... https://www.easysoft.com/products/data_access/odbc-access-driver/index.html#section=tab-1 Instructions for configuring it are here: https://www.easysoft.com/products/data_access/odbc-access-driver/getting-started.html You'll obviously need to copy the access file or mount it over an SMB/CIFS share and modify your /etc/odbc.ini file accordingly
comment on: http://stackoverflow.com/a/51053260

http://stackoverflow.com/comment/89320742
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51132060
type: Comment
has text: @mmaz Update the code in question with the one you are now using and paste the error message in the question. Formatting is not preserved inside comments and it's difficult to see what is happening.

http://stackoverflow.com/comment/132194218
type: AnswerComment
score: 0
type: Comment
has text: Where did you copy this from?
comment on: http://stackoverflow.com/a/74908077

http://stackoverflow.com/q/51098715
tagged with: random-forest
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51098795
has body: I used the following code to create a scikit RandomForest model and train it then save it : import pandas as pd import sklearn from pandas import Series, DataFrame from sklearn.model_selection import train_test_split import sklearn.metrics from sklearn.ensemble import RandomForestClassifier import pickle data = pd.read_csv("data_30000_30.csv") data.head() #Just to give you an idea about how my CSV file looks like feature_cols = ["width1", "width2", "width3", "width4", "width5", "width6", "width7", "width8", "width9", "width10"] x = data[feature_cols] y = data.label x_train, x_test, y_train, y_test = train_test_split(x, y , test_size = 0.3) classifier = RandomForestClassifier(n_estimators = 100) classifier.fit(x_train, y_train) predictions = classifier.predict(x_test) conf_matrix = sklearn.metrics.confusion_matrix(y_test, predictions) print(conf_matrix) print(sklearn.metrics.accuracy_score(y_test, predictions)) with open('myclassifier.pkl', 'wb') as fid: pickle.dump(classifier, fid) fid.close() Everything went well, and I got the following output: The head of the CSV file: The parameters of the classifier: RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False) The output of the conf_matrix: array([[6272, 2513, 26, 153, 54], [3073, 5634, 37, 322, 27], [ 1, 5, 5057, 775, 3072], [ 22, 65, 429, 8245, 208], [ 58, 50, 1458, 509, 6935]]) The accuracy: 0.7142888888888889 Then I used the following code to load my saved pre-trained model and test it with new data: import pandas as pd import sklearn from pandas import Series, DataFrame from sklearn.model_selection import train_test_split import sklearn.metrics import pickle with open('saved_model/myclassifier.pkl', 'rb') as fid: classifie…
type: AnsweredQuestion
favorite count: 0
type: Question
tagged with: pickle
upvote count: 1
tagged with: python
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/51098795
score: 0
has title: Get percentages of predicted elements using Scikit Learn

http://stackoverflow.com/a/51128661
has body: It is more like you have some value in df1 tuples refer to None value from df2 You can do with reindex before apply lookup name=set(list(itertools.chain(*list(itertools.chain(*df1.values.tolist()))))) df2=df2.reindex(name).reindex(name,axis=1) df1.applymap(lambda x : df2.lookup([x[0]],[x[1]])[0])
has comment: http://stackoverflow.com/comment/89242371
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51128396

http://stackoverflow.com/q/51139028
has answer: http://stackoverflow.com/a/74513882
downvote count: 0
has body: I'm trying to use my own dataset to train a GAN network. I'm having issues with loading my own dataset in .jpg format. I have existing jpg datasets that work, I can't see a difference in the jpg encoding between the working and not working datasets. The photos are converted using a windows machine and renamed to 001.jpg 002.jpg etc. For training I'm using a linux machine. The python program I'm using the following code to load and convert images to tensors: def _image_batch(image_paths, batch_size, load_size=286, crop_size=256, channels=3, prefetch_batch=2, drop_remainder=True, num_threads=16, shuffle=True, buffer_size=4096, repeat=-1): def _parse_func(path): img = tf.read_file(path) img = tf.image.decode_jpeg(img, channels=channels) img = tf.image.random_flip_left_right(img) img = tf.image.resize_images(img, [load_size, load_size]) img = (img - tf.reduce_min(img)) / (tf.reduce_max(img) - tf.reduce_min(img)) img = tf.random_crop(img, [crop_size, crop_size, channels]) img = img * 2 - 1 return img The full error is: Traceback (most recent call last): File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 510, in _apply_op_helper preferred_dtype=default_dtype) File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1040, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 883, in _TensorTensorConversionFunction (dtype.name, t.dtype.name, str(t))) ValueError: Tensor conversion requested dtype string for Tensor with dtype float32: 'Tensor("arg0:0", shape=(), dtype=float32)' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "train.py", line 112, i…
favorite count: 0
tagged with: type-conversion
answer count: 3
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51141722
tagged with: http://stackoverflow.com/tag/jpeg
tagged with: tensorflow
has title: Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32
tagged with: image
has answer: http://stackoverflow.com/a/54626644
type: Question

http://stackoverflow.com/comment/89303740
type: Comment
has text: When running your script with python36, I got the error name "app" is not defined
type: AnswerComment
comment on: http://stackoverflow.com/a/51159648
score: 0

http://stackoverflow.com/q/51035150
downvote count: 0
has body: I'm facing an issue. Indeed, I work with vietnamese texts and I want to find every word containing uppercase(s) (capital letter). When I use the 're' module, my function (temp) does not catch word like "Đà". The other way (temp2) is to check each character at a time, it works but it is slow since I have to split the sentences into words. Hence I would like to know if there is a way of the "re" module to catch all the special capital letter. I have 2 ways : def temp(sentence): return re.findall(r'[a-z]*[A-Z]+[a-z]*', sentence) lis=word_tokenize(sentence) def temp2(lis): proper_noun=[] for word in lis: for letter in word: if letter.isupper(): proper_noun.append(word) break return proper_noun Input: 'nous avons 2 Đồng et 3 Euro' Expected output : ['Đồng','Euro'] Thank you!
possible better answer: http://stackoverflow.com/a/51035740
type: Question
has answer: http://stackoverflow.com/a/51035253
accepted answer: http://stackoverflow.com/a/51035253
score: 5
has answer: http://stackoverflow.com/a/51035740
has comment: http://stackoverflow.com/comment/89062196
has comment: http://stackoverflow.com/comment/89062613
has answer: http://stackoverflow.com/a/51040649
has comment: http://stackoverflow.com/comment/89062659
has title: Regex to match capital/special/unicode/vietnamese characters
linked to: http://stackoverflow.com/q/36187349
linked to: http://stackoverflow.com/q/393843
has comment: http://stackoverflow.com/comment/89085161
answer count: 3
has comment: http://stackoverflow.com/comment/89062971
has comment: http://stackoverflow.com/comment/89063100
has comment: http://stackoverflow.com/comment/89062545
has comment: http://stackoverflow.com/comment/89062851
has comment: http://stackoverflow.com/comment/89063529
linked to: http://stackoverflow.com/q/6314614
has comment: http://stackoverflow.com/comment/89062500
favorite count: 0
upvote count: 5
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90736353
has comment: http://stackoverflow.com/comment/89062229
type: AnsweredQuestion

http://stackoverflow.com/comment/89312444
comment on: http://stackoverflow.com/a/51164533
score: 0
type: AnswerComment
type: Comment
has text: but this solution still leaves the last charter missing. example xaabx the program will return just a xb and not the remaining x

http://stackoverflow.com/q/51160152
favorite count: 0
has comment: http://stackoverflow.com/comment/89309212
has comment: http://stackoverflow.com/comment/89303993
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51163690
has body: I have two python classes, both of them scriptable independently from VBA using COM interop mechanisms. But I want one to control the creation of the other, in a Parent Child pattern or Factory pattern. I have experimented but cannot get to work, I have distilled into MCRE below. I am new at Python. I was wondering if there was someway to inherit a mixin which will give the class the necessary COM interop methods. Ok, so I have created a MCRE, here is the Python code which must be run at least one from command line with admin privileges to get the COM registration done (thereafter admin not required). import win32com.client class MyParent(object): _reg_clsid_ = "{C61A7C6E-B657-4D55-AD36-8850B2E501AC}" _reg_progid_ = 'PythonInVBA.MyParent' _public_methods_ = ['Greet', 'GetChild'] def __init__(self): # Rules of Com say paramerless constructors self.child = MyChild() self.child.SetName("foo") def Greet(self): return "Hello world" def GetChild(self): return self.child class MyChild(object): _reg_clsid_ = "{15DAAEE2-3A37-4DE1-9973-CCD011DF4888}" _reg_progid_ = 'PythonInVBA.MyChild' _public_methods_ = ['Initialize', 'GetName', 'SetName'] def __init__(self): # Rules of Com say paramerless constructors pass def GetName(self): return self.name def SetName(self, sName): self.name = sName if __name__ == '__main__': print ("Registering COM servers...") import win32com.server.register win32com.server.register.UseCommandLine(MyParent) win32com.server.register.UseCommandLine(MyChild) And here is the VBA code, the first two Sub Procedures work but the third one fails. Option Explicit Sub Test_MyParent_OnItsOwn() On Error GoTo ErrHand: Dim objMyParent As Object Set objMyParent = VBA.CreateObject("PythonInVBA.MyParent") Debug.Assert objMyParent.Greet = "Hello world" Exit Sub ErrHand: Debug.Print Err.Description End Sub Sub Test_MyChild_OnItsOwn() On Error GoTo ErrHand: Dim objMyChild As Object Set objMyChild = VBA.CreateObject("PythonInVBA.MyChild") objMyChild.SetName "Kevin" Debug.A…
tagged with: com-interop
has comment: http://stackoverflow.com/comment/89303969
tagged with: excel
type: Question
has title: Python COM Interop - Factory Pattern
has answer: http://stackoverflow.com/a/51163690
score: 1
has comment: http://stackoverflow.com/comment/89304165
has comment: http://stackoverflow.com/comment/89304212
has comment: http://stackoverflow.com/comment/89304044
has comment: http://stackoverflow.com/comment/89304280
tagged with: com
has comment: http://stackoverflow.com/comment/89304068
upvote count: 1
answer count: 1
downvote count: 0
tagged with: vba

http://stackoverflow.com/comment/89467204
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51044806
has text: In that case use `fields.get("StartTime", '')` to default the value to an empty string.
type: Comment

http://stackoverflow.com/comment/89028722
has text: I guess that's because Python returns `None` by default if nothing is returned by your function(s)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51018048

selenium
tags question: http://stackoverflow.com/q/51014205
tags question: http://stackoverflow.com/q/51160246
tags question: http://stackoverflow.com/q/51072712
tags question: http://stackoverflow.com/q/51035436
tags question: http://stackoverflow.com/q/51049664
tags question: http://stackoverflow.com/q/51060217
tags question: http://stackoverflow.com/q/51106564
tags question: http://stackoverflow.com/q/51115698
tags question: http://stackoverflow.com/q/51149253
tags question: http://stackoverflow.com/q/51129513
tags question: http://stackoverflow.com/q/51112309
tags question: http://stackoverflow.com/q/51044182
tags question: http://stackoverflow.com/q/51021140
tags question: http://stackoverflow.com/q/51055025
tags question: http://stackoverflow.com/q/51122020
tags question: http://stackoverflow.com/q/51032139
tags question: http://stackoverflow.com/q/51056256
tags question: http://stackoverflow.com/q/51149507
tags question: http://stackoverflow.com/q/51069749
tags question: http://stackoverflow.com/q/51157815
tags question: http://stackoverflow.com/q/51083617
tags question: http://stackoverflow.com/q/51028340
tags question: http://stackoverflow.com/q/51048725
tags question: http://stackoverflow.com/q/51020857
tags question: http://stackoverflow.com/q/51116417
tags question: http://stackoverflow.com/q/51013308
tags question: http://stackoverflow.com/q/51149304
tags question: http://stackoverflow.com/q/51119896
tags question: http://stackoverflow.com/q/51058879
tags question: http://stackoverflow.com/q/51152519
tags question: http://stackoverflow.com/q/51129628
tags question: http://stackoverflow.com/q/51092362
tags question: http://stackoverflow.com/q/51140415
tag name: selenium
tags question: http://stackoverflow.com/q/51112312
tags question: http://stackoverflow.com/q/51133132
tags question: http://stackoverflow.com/q/51018477
tags question: http://stackoverflow.com/q/51050863
tags question: http://stackoverflow.com/q/51165060
tags question: http://stackoverflow.com/q/51157906
tags question: http://stackoverflow.com/q/51035611
tags question: http://stackoverflow.com/q/51153612
tags question: http://stackoverflow.com/q/51118079
tags question: http://stackoverflow.com/q/51118805
tags question: http://stackoverflow.com/q/51063540
tags question: http://stackoverflow.com/q/51078879
tags question: http://stackoverflow.com/q/51017384
tags question: http://stackoverflow.com/q/51058867
tags question: http://stackoverflow.com/q/51133630
tags question: http://stackoverflow.com/q/51159965
tags question: http://stackoverflow.com/q/51159879
tags question: http://stackoverflow.com/q/51140732
tags question: http://stackoverflow.com/q/51107514
tags question: http://stackoverflow.com/q/51107814
tags question: http://stackoverflow.com/q/51107309
tags question: http://stackoverflow.com/q/51146964
tags question: http://stackoverflow.com/q/51046454
tags question: http://stackoverflow.com/q/51072792
tags question: http://stackoverflow.com/q/51084668
tags question: http://stackoverflow.com/q/51160385
tags question: http://stackoverflow.com/q/51073042
tags question: http://stackoverflow.com/q/51044413
tags question: http://stackoverflow.com/q/51129410
tags question: http://stackoverflow.com/q/51044646
tags question: http://stackoverflow.com/q/51050540
tags question: http://stackoverflow.com/q/51099292
tags question: http://stackoverflow.com/q/51112016
tags question: http://stackoverflow.com/q/51133144
tags question: http://stackoverflow.com/q/51151666
tags question: http://stackoverflow.com/q/51016452
tags question: http://stackoverflow.com/q/51147710
tags question: http://stackoverflow.com/q/51082806
tags question: http://stackoverflow.com/q/51154023
type: Tag
tags question: http://stackoverflow.com/q/51076418
tags question: http://stackoverflow.com/q/51052735
tags question: http://stackoverflow.com/q/51011754
tags question: http://stackoverflow.com/q/51145596
tags question: http://stackoverflow.com/q/51121973
tags question: http://stackoverflow.com/q/51144481

http://stackoverflow.com/a/51103183
has comment: http://stackoverflow.com/comment/89224903
type: Answer
has comment: http://stackoverflow.com/comment/89225244
has comment: http://stackoverflow.com/comment/89223432
has comment: http://stackoverflow.com/comment/89225120
has comment: http://stackoverflow.com/comment/89224956
accepted answer of: http://stackoverflow.com/q/51092258
has body: The code below uses a recursive generator to build solutions. To store the target letters we use a collections.Counter, this acts like a set that permits repeated items. To simplify searching we create a dictionary for each word length that we want, storing each of those dictionaries in a dictionary called all_words, with the word length as the key. Each sub-dictionary stores lists of words containing the same letters, with the sorted letters as the key, eg 'aet': ['ate', 'eat', 'tea']. I use the standard Unix '/usr/share/dict/words' word file. If you use a file with a different format you may need to modify the code that puts words into all_words. The solve function starts its search with the smallest word length, and works up to the largest. That's probably the most efficient order if the set containing the longest words is the biggest, since the final search is performed by doing a simple dict lookup, which is very fast. The previous searches have to test each word in the sub-dictionary of that length, looking for keys that are still in the target bag. #!/usr/bin/env python3 ''' Create anagrams from a string of target letters and a list of word lengths ''' from collections import Counter from itertools import product # The Unix word list fname = '/usr/share/dict/words' # The target letters to use target = 'lndjobeawrl' # Word lengths, in descending order wordlengths = [5, 4, 2] # A dict to hold dicts for each word length. # The inner dicts store lists of words containing the same letters, # with the sorted letters as the key, eg 'aet': ['ate', 'eat', 'tea'] all_words = {i: {} for i in wordlengths} # A method that tests if a word only contains letters in target valid = set(target).issuperset print('Scanning', fname, 'for valid words...') count = 0 with open(fname) as f: for word in f: word = word.rstrip() wlen = len(word) # Only add words of the correct length, with no punctuation. # Using word.islower() eliminates most abbreviations. if (wlen in wordlengths and w…
answers question: http://stackoverflow.com/q/51092258
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89208640
score: 0

http://stackoverflow.com/comment/89130116
type: AnswerComment
score: 0
type: Comment
has text: I'm mostly looking for a db query which generates the final list, and don't want to do the same logic in memory.
comment on: http://stackoverflow.com/a/51070084

http://stackoverflow.com/q/51098959
has answer: http://stackoverflow.com/a/51105940
has body: I've created a MySQL table with these fields: id - int - auto_increment dt - DateTime desc - VARCHAR 255 Now I would like know know how to select only the years from this table with Peewee in Python. Equal years should be removed. In SQL I would simply do SELECT DISTINCT YEAR(dt) AS yr from data; to get the desired result. I'm aware of the db.execute_sql method to execute a raw SQL-query. I wonder however if there is a cleaner way. Thanks and best regards.
tagged with: python
type: AnsweredQuestion
tagged with: mysql
type: Question
tagged with: peewee
has title: How to select distinct years from DateTime with Peewee
answer count: 1
accepted answer: http://stackoverflow.com/a/51105940
score: 0

http://stackoverflow.com/comment/89158338
type: Comment
has text: Thanks, it worked finally. My aim now is to create a dict fetching this one with ```[{u'count': 1, u'_id': UUID('31140d2e-15a1-4203-bdbb-55c14cd6b83a')}, {u'count': 17, u'_id': UUID('c0a36d2e-f7dd-4d62-abe8-c26249e52520')}, {u'count': 1, u'_id': UUID('a650e642-ee41-4ab7-8ad1-797c7bdcd2aa')}, {u'count': 1, u'_id': UUID('d0576830-df96-4411-ac33-4bac597f2010')}]``` in order to get an array containing number of machines per cloud_account
comment on: http://stackoverflow.com/a/51080557
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89262328
comment on: http://stackoverflow.com/q/51113112
type: QuestionComment
score: 0
has text: could you please tell the steps. Or else maybe the Tokens passed out by stc.STC_LEX_CONTAINER. I guess it would be easy to make one for JSON
type: Comment

http://stackoverflow.com/a/51068419
type: Answer
answers question: http://stackoverflow.com/q/51068194
has comment: http://stackoverflow.com/comment/89126912
has comment: http://stackoverflow.com/comment/89126978
has comment: http://stackoverflow.com/comment/89126970
has comment: http://stackoverflow.com/comment/89126845
has body: I don't think it gets stuck inside the try/except. I think it does the append, then loops back to the top and gets stuck because something happens to the network communications, so it just hangs waiting for the server. Most likely. But you're not very precise about what you're observing, so it's hard to tell. We also don't know what you're using to connect to the server, which makes things tricky. What is s? You may be able to set a socket timeout that makes it return after a certain time without hanging forever. A print statement up with the s.get(url) would help. Also, if you showed the actual output that would also help.
has comment: http://stackoverflow.com/comment/89126903
score: 0

http://stackoverflow.com/a/51085148
score: 19
has body: This works, import pyspark.sql.functions as F from pyspark.sql.types import * df = sql.createDataFrame( [(['Bob'], [16], ['Maths','Physics','Chemistry'], ['A','B','C'])], ['Name','Age','Subjects', 'Grades']) df.show() +-----+----+--------------------+---------+ | Name| Age| Subjects| Grades| +-----+----+--------------------+---------+ |[Bob]|[16]|[Maths, Physics, ...|[A, B, C]| +-----+----+--------------------+---------+ Use udf with zip. Those columns needed to explode have to be merged before exploding. combine = F.udf(lambda x, y: list(zip(x, y)), ArrayType(StructType([StructField("subs", StringType()), StructField("grades", StringType())]))) df = df.withColumn("new", combine("Subjects", "Grades"))\ .withColumn("new", F.explode("new"))\ .select("Name", "Age", F.col("new.subs").alias("Subjects"), F.col("new.grades").alias("Grades")) df.show() +-----+----+---------+------+ | Name| Age| Subjects|Grades| +-----+----+---------+------+ |[Bob]|[16]| Maths| A| |[Bob]|[16]| Physics| B| |[Bob]|[16]|Chemistry| C| +-----+----+---------+------+
upvote count: 21
has comment: http://stackoverflow.com/comment/93865493
accepted answer of: http://stackoverflow.com/q/51082758
answers question: http://stackoverflow.com/q/51082758
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/125375470
downvote count: 2
type: Answer

http://stackoverflow.com/a/51131358
answers question: http://stackoverflow.com/q/51129847
score: 2
accepted answer of: http://stackoverflow.com/q/51129847
type: AcceptedAnswer
has body: Calling subprocess.Popen() with the shell parameter set to True in production is a generally bad idea. One of the dangers include shell injection vulnerabilities, as quoted by the Python 3 docs: 17.5.2. Security Considerations Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. Source: https://docs.python.org/3.6/library/subprocess.html
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/51103232
type: Answer
has body: When you don't define __eq__, __eq__ will resolve to object.__eq__. That is what's happening when you create a dataclass with eq=False. object.__eq__(self, other) is False unless self is other, i.e. unless the two are the same object.
downvote count: 0
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/51102758

http://stackoverflow.com/comment/89199971
has text: It does work, but I actually timed slightly slower using that compared to `astype`
comment on: http://stackoverflow.com/a/51106481
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51143747
has comment: http://stackoverflow.com/comment/89272579
type: Answer
accepted answer of: http://stackoverflow.com/q/51143356
has comment: http://stackoverflow.com/comment/89272476
has comment: http://stackoverflow.com/comment/89272365
answers question: http://stackoverflow.com/q/51143356
has comment: http://stackoverflow.com/comment/89272449
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89272142
has comment: http://stackoverflow.com/comment/89272263
has body: def get_dotted_form(val, old=""): lines = [] if isinstance(val, dict): for k in val.keys(): lines += get_dotted_form(val[k], old + "." + str(k)) elif isinstance(val, list): for i,k in enumerate(val): lines += get_dotted_form(k, old + "." + str(i)) else: lines += ["{}.{}".format(old,str(val))] return [line.lstrip('.') for line in lines] dotted_list = get_dotted_form(json_data) dotted_string = ',\n'.join(s) print (dotted_string) Output $schema.http:, title.al, description.An enitity , id.a.json#, type.object, required.0.symbol, required.1.symbolText, required.2.gene, required.3.taxonId, required.4.primaryId, additionalProperties.False, properties.primaryId.$ref..., properties.primaryId.description.The, properties.symbol.type.string, properties.symbol.description.The symbol of the entity., properties.symbolText.type.string, properties.symbolText.description.the , properties.taxonId.$ref.../g, properties.taxonId.description.The , properties.synonyms.type.array, properties.synonyms.items.type.string, properties.synonyms.uniqueItems.True, properties.secondaryIds.type.array, properties.secondaryIds.items.$ref.., properties.secondaryIds.uniqueItems.True, properties.gene.$ref.../globalId.json#/properties/globalId, properties.gene.description.The , properties.crossReferences.description.Collection, properties.crossReferences.type.array, properties.crossReferences.items.$ref.../crossReference.json#, properties.crossReferences.uniqueItems.True

http://stackoverflow.com/comment/89021671
comment on: http://stackoverflow.com/q/51014386
score: 0
type: Comment
has text: I have no idea, why it is liking java dependencies
type: QuestionComment

http://stackoverflow.com/comment/93713346
score: 0
type: QuestionComment
type: Comment
has text: Jupyter notebooks have known issues displaying images with `cv2.imshow()`. The short of it is, don't use it inside a Jupyter notebook. Use another plotting library to show the image in-line. Alternatively, you can save the image and then display it inline with HTML or other Jupyter notebook features. However, there is possible workarounds using `cv2.startWindowThread()`. See [here](https://stackoverflow.com/a/29584090/5087436).
comment on: http://stackoverflow.com/q/51094806

http://stackoverflow.com/q/51039393
tagged with: python
has comment: http://stackoverflow.com/comment/89146123
has answer: http://stackoverflow.com/a/77794915
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72236328
has title: Get or build PEM certificate chain in Python
has answer: http://stackoverflow.com/a/51046093
type: Question
score: 5
has body: Is it possible to get the whole certificate chain in a PEM format using ssl with Python ? I can get the specific one with : import ssl addr = '192.0.2.1' cert_str = ssl.get_server_certificate((addr, 443)) which give me something like : -----BEGIN CERTIFICATE----- [...] -----END CERTIFICATE----- But I'd like to have : -----BEGIN CERTIFICATE----- [...] -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- [...] -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- [...] -----END CERTIFICATE----- I'm pretty sure this is possible since I can download this from my web browser. Any idea ? (I have already checked Getting certificate chain with Python 3.3 SSL module but I'm not sure this is what I want ...) EDIT: What I tried after Patrick Mevzek answer : from OpenSSL import SSL import socket dst = ('192.0.2.1', 443) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_alpn_protos([b'http/1.1']) if sock.connect_ex(dst) == 0: connection = SSL.Connection(ctx, sock) cert_str = connection.get_peer_cert_chain() But cert_str is None. I think this is because i'm missing something with the use of OpenSSL.
possible better answer: http://stackoverflow.com/a/72236328
upvote count: 5
tagged with: ssl
tagged with: pem
has comment: http://stackoverflow.com/comment/89125726
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51046093
linked to: http://stackoverflow.com/q/19145097
favorite count: 0

http://stackoverflow.com/q/51117208
tagged with: mysql
type: Question
has title: How to add another field in connection with a ManyToManyField?
accepted answer: http://stackoverflow.com/a/51117288
tagged with: django-models
score: 0
has answer: http://stackoverflow.com/a/51117288
answer count: 1
tagged with: django
tagged with: python
has body: class Team(models.Model): college = models.CharField(max_length=20) image = models.FileField(upload_to='documents/',null=True) def __str__(self): return self.college class Athletics(Match): time = ? player = models.ManyToManyField(Player, related_name='player') game_level = models.CharField(max_length=256, null=True, choices=LEVEL_CHOICES) # like semi-final, final etc game_specific = models.CharField(max_length=256,null=True, choices=EVENT_CHOICES) #like Men's Shot Put or Men's Triple Jump etc def __str__(self): return str(self.game_level) I am making an Athletics Sports Model for a sports tournament. I have an existing Player Model where I have listed players names and their teams. Now as you can see, I have added player field as ManyToManyField to choose for say 4-5 players match. Now I need finishing time for each player for judging who qualifies for the next round. Can it be possible to do this in this model only? Or I have to add another model? Help me!
type: AnsweredQuestion

import
type: Tag
tags question: http://stackoverflow.com/q/51158742
tags question: http://stackoverflow.com/q/51053272
tag name: import
tags question: http://stackoverflow.com/q/51089040
tags question: http://stackoverflow.com/q/51022700
tags question: http://stackoverflow.com/q/51017114
tags question: http://stackoverflow.com/q/51011855
tags question: http://stackoverflow.com/q/51051606
tags question: http://stackoverflow.com/q/51122781

http://stackoverflow.com/a/51146223
has body: Twilio developer evangelist here! We recommend building conversations like this using sessions - you can check out a tutorial for that using Python and Flask here: https://www.twilio.com/docs/sms/tutorials/how-to-create-sms-conversations-python So you could do something like: from flask import Flask, request, session from twilio.twiml.messaging_response import MessagingResponse # The session object makes use of a secret key. SECRET_KEY = 'a secret key' app = Flask(__name__) app.config.from_object(__name__) @app.route("/sms", methods=['GET', 'POST']) def sms_logic(): # Increment the counter counter = session.get('counter', 0) counter += 1 # Save the new counter value in the session session['counter'] = counter resp = MessagingResponse() if counter == 1: resp.message('Hi! Please enter your name') else: body = request.values.get('Body', 'Friend') resp.message('Thanks {}!'.format(body)) return str(resp) if __name__ == "__main__": app.run(debug=True) For a bigger example check out this tutorial on building an Employee directory with Python and Flask: https://www.twilio.com/docs/sms/tutorials/employee-directory-python-flask
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89293218
upvote count: 1
answers question: http://stackoverflow.com/q/51145995

http://stackoverflow.com/comment/89315601
score: 0
type: AnswerComment
has text: Last line should be `exec python app.py`
type: Comment
comment on: http://stackoverflow.com/a/51154465

http://stackoverflow.com/comment/89051879
has text: I've updated the post to include better example data/code. The sum function is expecting an array of ints. hex() just converts the ints to a hex string, its unimportant in this example
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51027966

http://stackoverflow.com/comment/89289436
type: QuestionComment
has text: Yes It prints for me too. I need age also in the same line like `[('John') , '30')]`
score: 0
comment on: http://stackoverflow.com/q/51152939
type: Comment

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51132010
tags question: http://stackoverflow.com/q/51045911
tag name: wsgi

http://stackoverflow.com/comment/89314816
score: 1
comment on: http://stackoverflow.com/a/51165832
type: Comment
has text: @Ultraviolet For easy merge.
type: AnswerComment

http://stackoverflow.com/q/51073392
tagged with: python
has comment: http://stackoverflow.com/comment/89136400
favorite count: 0
possible better answer: http://stackoverflow.com/a/51073650
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89136405
upvote count: 1
has answer: http://stackoverflow.com/a/51073435
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89136423
has comment: http://stackoverflow.com/comment/89136558
score: 1
has body: I have some problems making a post request with a custom header. I'm using the Requests library and as endpoint jsonplaceholder, where you can get for a POST request a fake JSON back. I call my script with py request.py // request.py import requests import json from pprint import pprint def postReqCustom( url, headers, data): print('Making request to: ', url) r = requests.post(url, headers=headers, data=data) print('status code: ' + str(r.status_code)) response = r.json() pprint(response) def postReq( url, data): print('Making request to: ', url) r = requests.post(url, data=data) print('status code: ' + str(r.status_code)) response = r.json() pprint(response) headers = {'content-type': 'application/json'} data = { "title": "foo", "body": "bar", "userId": 1 } post_url = "https://jsonplaceholder.typicode.com/posts" #postReq(post_url, data) #ok postReqCustom(post_url, headers, data) #error For postReq I don't get any errors(status code 201) but when I try postReqCustom with a custom header I'm getting following error: Making request to: https://jsonplaceholder.typicode.com/posts status code: 500 Traceback (most recent call last): File "request.py", line 55, in &lt;module&gt; postReqCustom(post_url, headers, payload) File "request.py", line 24, in postReqCustom response = r.json() File "C:\Users\Samy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\models.py", line 892, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\Samy\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\Samy\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Samy\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
answer count: 2
accepted answer: http://stackoverflow.com/a/51073435
downvote count: 0
has comment: http://stackoverflow.com/comment/89136371
has answer: http://stackoverflow.com/a/51073650
has title: Python: request with custom header fails

http://stackoverflow.com/q/51079739
answer count: 1
tagged with: python
has title: Reading every Nth line from a .txt file (Python)
type: AnsweredQuestion
tagged with: matplotlib
has body: I am making a program that reads time values and readings from a .txt file and plots them on a web-page with matplotlib. In my case there are lots of values, and the plot can look very confusing, and with thousands of data points it can also be sluggish. I am currently reading the .txt lines with this code to put the values into plottable lists: with open('C:/Email/file.txt') as f: lines = f.readlines() dates = [str(line.split(';')[0]) for line in lines] y = [float(line.split(';')[1]) for line in lines] z = [float(line.split()[2]) for line in lines] The .txt file content looks like this: 30.05.18_12:27:17; 13.0; -0.0 30.05.18_12:27:18; 14.0; -0.0 30.05.18_12:27:19; 15.0; -0.0 30.05.18_12:27:20; 16.0; -0.0 So, is there any way to read and plot every Nth (for example every 30. would be ideal) timestamp and value? I've been researching different ways but they seem confusing. One solution that I was thinking about is to make a counter that counts the amount of read lines, then when the counter is 30, skip 30 the next lines and read and plot the data in line 31. I have no idea how to do this, since I am relatively new to Python. Help would be appreciated. Just in case, the whole code here: from flask import Flask import numpy as np import matplotlib.pyplot as plt, mpld3 from datetime import datetime app = Flask(__name__) @app.route("/") def hello(): with open('C:/Email/file.txt') as f: lines = f.readlines() dates = [str(line.split(';')[0]) for line in lines] y = [float(line.split(';')[1]) for line in lines] z = [float(line.split()[2]) for line in lines] date = [datetime.strptime(x,'%d.%m.%y_%H:%M:%S') for x in dates] plt.figure(figsize=(10,5)) plt.title('Temperature', fontsize=15) plt.ylabel('Temperature' + u'\u2103', fontsize=15) plt.plot_date(date, y, 'r-', label='quadratic') plt.ylim([10,35]) # Print as HTML return mpld3.show() if __name__ == "__main__": app.run() EDIT: HUGE THANKS TO MR. F-ROCHE Got it working with the following code: @app.route("/") def hello(): wit…
type: Question
has answer: http://stackoverflow.com/a/51079875
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51079875
score: 0

http://stackoverflow.com/q/51032552
answer count: 2
has answer: http://stackoverflow.com/a/51032629
tagged with: pandas
has comment: http://stackoverflow.com/comment/89057530
has comment: http://stackoverflow.com/comment/89057504
has body: My df: Date AAPL NFLX INTC AAPL_Ret NFLX_Ret INTC_Ret 0 2008-01-31 27.834286 3.764286 25.350000 1 2008-02-29 27.847143 3.724286 24.670000 -0.07 0.25 -0.05 2 2008-03-31 25.721428 3.515714 22.670000 0.15 0.10 0.06 3 2008-04-30 25.377142 3.554286 22.879999 etc 4 2008-05-31 24.464285 3.328571 22.260000 I want to calculate quintiles for the stock returns going across the rows in my df. I thought maybe I can use pd.qcut with something like axis=1 in the formula but the method doesn't take an argument like that. Any ideas? Thanks for your help!
has title: Relative Quintiles
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89057699
tagged with: python
linked to: http://stackoverflow.com/q/51031033
score: 0
type: Question
has comment: http://stackoverflow.com/comment/89057442
has answer: http://stackoverflow.com/a/51043624

http://stackoverflow.com/q/51081782
type: Question
answer count: 2
tagged with: temporary-files
has answer: http://stackoverflow.com/a/51081825
score: 10
has comment: http://stackoverflow.com/comment/89151992
has comment: http://stackoverflow.com/comment/89151950
has comment: http://stackoverflow.com/comment/89152180
possible better answer: http://stackoverflow.com/a/64956902
has body: I'm working on a python(3.6) project in which I need to write a JSON file from a Python dictionary. Here's my dictionary: {'deployment_name': 'sec_deployment', 'credentials': {'type': 'type1', 'project_id': 'id_001',}, 'project_name': 'Brain', 'project_id': 'brain-183103', 'cluster_name': 'numpy', 'zone_region': 'europe-west1-d', 'services': 'Single', 'configuration': '', 'routing': ''} And I need to write credentials key to a JSON file. Here's how I have tried: tempdir = tempfile.mkdtemp() saved_umask = os.umask(0o077) path = os.path.join(tempdir) cred_data = data['credentials'] with open(path + '/cred.json', 'a') as cred: cred.write(cred_data) credentials = prepare_credentials(path + '/cred.json') print(credentials) os.umask(saved_umask) shutil.rmtree(tempdir) It's not writing a JSON formatted file, then generated file is as: { 'type': 'type1', 'project_id': 'id_001', } it comes with single quotes instead of double quotes.
has answer: http://stackoverflow.com/a/64956902
linked to: http://stackoverflow.com/q/4528099
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51081825
tagged with: python
has title: Python Write a JSON temporary file from a dictionary
upvote count: 11
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
downvote count: 1

http://stackoverflow.com/a/51116108
upvote count: 2
has comment: http://stackoverflow.com/comment/89218433
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51116016
has body: Python 3.7 just released 2 days ago and not many modules are not supported on Python 3.7 yet. If you don't really need Python 3.7, then downgrade to Python 3.6 to download packages. Or Download Anaconda 5.2 to use matplotlib and opencv in Python 3.6. Here is Anaconda Download link for Windows: [link] (https://www.anaconda.com/download/#windows) I recommend to download Anaconda for using both matplotlib and opencv.
type: Answer
accepted answer of: http://stackoverflow.com/q/51116016
has comment: http://stackoverflow.com/comment/89218618
score: 2

http://stackoverflow.com/a/52685453
has body: While initializing the parameters do wrap those in torch.nn.Parameter() class for the optimizer to update these. If you are using pytorch &lt; 0.4 try using torch.autograd.Variable(). For example: import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F class TEMP(nn.Module): # Whole architecture def __init__(self): super(TEMP, self).__init__() self.input = nn.Parameter(torch.ones(1,requires_grad = True)) # &lt;----wrap it like this def forward(self,x): wt = self.input y = wt*x return y model = TEMP() optimizer = optim.Adam(model.parameters(), lr=0.001) x = torch.randn(100) y = 5*x loss = torch.sum((y - model(x)).pow(2)) optimizer.zero_grad() loss.backward() optimizer.step() print(model.input) And Please note if you are initializing a tensor in pytorch >= 0.4 do change the value of requires_grad = True if you want that variable to be updated.
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51104648
type: Answer
score: 2

http://stackoverflow.com/comment/89236078
type: Comment
comment on: http://stackoverflow.com/a/51123608
type: AnswerComment
has text: Indeed. But I already have the things you named in your list. The problem is that SLURM randomly assigns 4 nodes to my job. Now, I have to figure out, inside python somehow, which nodes have been assigned to my job, and then, run the master script to give every node its part of the job. Then, the client scripts will each do 20% of the job. So how do I retrieve the node list, into python?
score: 0

http://stackoverflow.com/a/51038012
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89072498
has comment: http://stackoverflow.com/comment/89068765
has comment: http://stackoverflow.com/comment/89070518
has comment: http://stackoverflow.com/comment/89072355
has body: Numpy's function mean_squared_error expects two arrays of the same size. The error you are getting implies that these two do not have the same size. You can check your array sizes by print(array_1.shape) print(array_2.shape) if the output you get is output: &gt; (4200,) &gt; (4200, 1) you can fix by doing new_array_2 = array_2.transpose()[0] and then mean_squared_error(array_1, new_array_2) if the two input arguments, whatever they are give you the following shapes print(array_1.shape) print(array_2.shape) output: &gt; (4200,) &gt; (16800, 1) try new_array_1 = scalar.transform(array_1) or new_array_2 = scalar.transform(array_2) until you get arrays with the same number whether it's 16800 or 4200. Once you have two of the same size, but the one or both still comes with an extra dimension, then again do new_new_array_1 = scalar.transform(new_array_1)[0] and feed these to mean_squared_error, e.g. mean_squared_error(new_new_array_1, new_array_2)
answers question: http://stackoverflow.com/q/51037737
has comment: http://stackoverflow.com/comment/89068804
has comment: http://stackoverflow.com/comment/89068937

http://stackoverflow.com/q/51152563
has title: Not able to plot the series type when using python3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51388791
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89288589
has body: I am using Python3 and I got the problem when I have been working on it. I coded as below and I found the right results that I expected. And then I want to see the result as diagram. So I tried to plot it but I got the unexpected error indicating that I need the matplotlib. Since I imported the matplotlib at the first code, I have no idea solving this issue. import matplotlib.pyplot as plt %matplotlib inline train.Survived[train['Name']=='Mr'].value_counts() #Result 0 436 1 81 Name: Survived, dtype: int64 I typed the below code to see them as pie-like diagram. train.Survived[train['Name']=='Mr'].value_counts().plot(kind='pie') The error message is as below. --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-191-7f60a15206ad&gt; in &lt;module&gt;() 1 import pandas.plotting ----&gt; 2 train.Survived[train['Name']=='Mr'].value_counts().plot(kind='pie') /usr/local/lib/python3.6/site-packages/pandas/plotting/_core.py in __call__(self, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds) 2739 colormap=colormap, table=table, yerr=yerr, 2740 xerr=xerr, label=label, secondary_y=secondary_y, -&gt; 2741 **kwds) 2742 __call__.__doc__ = plot_series.__doc__ 2743 /usr/local/lib/python3.6/site-packages/pandas/plotting/_core.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds) 2000 yerr=yerr, xerr=xerr, 2001 label=label, secondary_y=secondary_y, -&gt; 2002 **kwds) 2003 2004 /usr/local/lib/python3.6/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds) 1757 data = data[y].copy() 1758 data.index.name = y -&gt; 1759 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) 1760 else: 17…
score: 1
tagged with: matplotlib
type: Question
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51161935
has comment: http://stackoverflow.com/comment/89331978
tagged with: pyside
type: Question
has title: Python QtCore.Object Baseclass inheritance
has comment: http://stackoverflow.com/comment/89309374
has comment: http://stackoverflow.com/comment/89308342
tagged with: inheritance
tagged with: qtcore
score: 0
has comment: http://stackoverflow.com/comment/89331582
has comment: http://stackoverflow.com/comment/89332018
has comment: http://stackoverflow.com/comment/89331320
has comment: http://stackoverflow.com/comment/89331733
linked to: http://stackoverflow.com/q/222877
duplicate of: http://stackoverflow.com/q/23981625
type: UnansweredQuestion
has body: I've searched around online for the answer however I was not entirely clear on the content i was readying so i figured i would post it here. I wanted to know if the way I'm creating a class inheriting from Baker is being done correctly. Say I have a base class: class Baker(QtCore.QObject): changedProperty = QtCore.Signal() def __init__(self, **kwargs): QtCore.QObject.__init__(self) ... Then I create classes based off of Baker like this: class NormalBaker(Baker): def __init__(self): Baker.__init__(self, name='Normal Baker') ... is this correct? UPDATED Is this snippet of code the proper way to subclass from Baker? def __init__(self): Baker.__init__(self, name='Normal Baker')
linked to: http://stackoverflow.com/q/576169
duplicate of: http://stackoverflow.com/q/222877
tagged with: python
duplicate of: http://stackoverflow.com/q/576169
answer count: 0

http://stackoverflow.com/comment/89076838
score: 0
has text: Yes. It is always sorted.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51042742

http://stackoverflow.com/comment/89059005
type: QuestionComment
has text: What is the intention of this code? Why do you want to override the initializer of `Enum` in `Foo` to do nothing, and why do you want to override it in `Bar` to take a value and ignore it?
comment on: http://stackoverflow.com/q/51033366
score: 0
type: Comment

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/51124241
tags question: http://stackoverflow.com/q/51151220
type: Tag
tags question: http://stackoverflow.com/q/51099873
tags question: http://stackoverflow.com/q/51044259

http://stackoverflow.com/q/51134939
upvote count: 4
has comment: http://stackoverflow.com/comment/89256583
has comment: http://stackoverflow.com/comment/89254560
has answer: http://stackoverflow.com/a/51170035
type: AnsweredQuestion
downvote count: 0
has body: I am trying to gauss fit my data using scipy and curve fit, here is my code : import csv import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit A=[] T=[] seuil=1000 range_gauss=4 a=0 pos_peaks=[] amp_peaks=[] A_gauss=[] T_gauss=[] new_A=[] new_T=[] def gauss(x,a,x0,sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) with open("classeur_test.csv",'r') as csvfile: reader=csv.reader(csvfile, delimiter=',') for row in reader : A.append(float(row[0])) T.append(float(row[1])) npA=np.array(A) npT=np.array(T) for i in range(1,len(T)): #PEAK DETECTION if (A[i]&gt;A[i-1] and A[i]&gt;A[i+1]) and A[i]&gt;seuil: pos_peaks.append(i) amp_peaks.append(A[i]) #GAUSSIAN RANGE for j in range(-range_gauss,range_gauss): #ATTENTION AUX LIMITES if(i+j&gt;0 and i+j&lt;len(T)-1): A_gauss.append(A[i+j]) T_gauss.append(T[i+j]) npA_gauss = np.array(A_gauss) npT_gauss = np.array(T_gauss) for i in range (0,7): new_A.append(npA_gauss[i]) new_T.append(npT_gauss[i]) new_npA=np.array(new_A) new_npT=np.array(new_T) n = 2*range_gauss mean = sum(new_npT*new_npA)/n sigma = sum(new_npA*(new_npT-mean)**2)/n popt,pcov = curve_fit(gauss,new_npT,new_npA,p0=[1,mean,sigma]) plt.plot(T,A,'b+:',label='data') plt.plot(new_npT,gauss(new_npT,*popt),'ro:',label='Fit') print ("new_npA : ",new_npA) print ("new_npT : ",new_npT) plt.legend() plt.title('Fit') plt.xlabel('X') plt.ylabel('Y') plt.show() My arrays new_npT and new_npA are numpy arrays like this : new_npA : [ 264. 478. 733. 1402. 1337. 698. 320.] new_npT : [229.609344 231.619385 233.62944 235.639496 237.649536 239.659592 241.669647] This is the result I don't understand why I can't successfully plot the gauss curves... Any explanations?
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89256262
tagged with: gaussian
answer count: 1
has title: Python Curve fit, gaussian
has comment: http://stackoverflow.com/comment/89254846
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/89259559
accepted answer: http://stackoverflow.com/a/51170035
tagged with: curve-fitting
tagged with: python

http://stackoverflow.com/q/51071691
has body: In the R programming language, there is a site.profile file that defines some code that R processes execute on start up. Is there similar functionality in Python? Edit: to clarify, this script should be executed if the user calls python from the command line, but also if python is spawned from another process (e.g. if the user's script uses subprocess to spawn another python).
has title: Is there a way to always execute a script when python starts? (similar site.profile in R)
has comment: http://stackoverflow.com/comment/89133159
answer count: 3
has comment: http://stackoverflow.com/comment/89133264
favorite count: 0
has answer: http://stackoverflow.com/a/51071772
has answer: http://stackoverflow.com/a/51071890
accepted answer: http://stackoverflow.com/a/51071890
linked to: http://stackoverflow.com/q/76438582
score: 6
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89133676
downvote count: 0
possible better answer: http://stackoverflow.com/a/51071885
has answer: http://stackoverflow.com/a/51071885
tagged with: startup
type: Question
upvote count: 6

http://stackoverflow.com/comment/89130050
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51070029
has text: You're right - That's the issue, but he is using requests incorrectly. Resp returns a dictionary and you then search for `status` which doesn't exist. The correct usage would be `status_code` which was pointed out in my answer.
score: 0

http://stackoverflow.com/a/51089090
has body: So, scrapy has in-built support for Caching which can be used to cache all the responses, and that really eliminates to mock the responses. There are various settings found in HttpCacheMiddleware. Some of those are as follows. (to be included in settings.py for a scrapy project) # Cache settings HTTPCACHE_POLICY = 'scrapy.extensions.httpcache.DummyPolicy' HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' HTTPCACHE_ENABLED = True HTTPCACHE_EXPIRATION_SECS = 0 # Never Expire HTTPCACHE_DIR = 'httpcache' HTTPCACHE_IGNORE_HTTP_CODES = [301, 302, 404] HTTPCACHE_IGNORE_MISSING = False HTTPCACHE_IGNORE_RESPONSE_CACHE_CONTROLS = ["no-cache", "no-store"] This also stores the cache in a specified directory. Here is the whole list of options.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51085665
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51070275
type: AnsweredQuestion
tagged with: pytest
score: 0
possible better answer: http://stackoverflow.com/a/51070769
has answer: http://stackoverflow.com/a/51070769
type: Question
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/51089177
tagged with: teardown
answer count: 2
has title: PyTest teardown_class is being run too soon
has body: The Python "teardown_class" is not behaving as I expect it to. Below is a summary of my code: @classmethod def setup_class(cls): cls.create_table(table1) cls.create_table(table2) cls.create_table(table3) @classmethod def create_table(cls, some_arg_here): """Some code here that creates the table""" def test_foo(self): """Some test code here""" @classmethod def teardown_class(cls): """Perform teardown things""" I believe the way it is executing is that: create_table is being called from setup with 1st parameter (table1) Code in create_table executes Code in teardown_class executes 1-3 above is executed again with the 2nd parameter 1-3 above is executed again with the 3rd parameter Code in test_foo executes How I expect it to perform: create_table is called with 1st parameter (table1) Code in create_table executes create_table is called with 2nd parameter (table 2) Code in create_table executes create_table is called with 3rd parameter (table 3) Code in create_table executes Code in test_foo executes Code in teardown_class executes Python 2.7.10, pytest-3.6.2, py-1.5.3, pluggy-0.6.0
tagged with: python
accepted answer: http://stackoverflow.com/a/51089177

http://stackoverflow.com/a/51145599
has comment: http://stackoverflow.com/comment/89320714
downvote count: 0
has comment: http://stackoverflow.com/comment/89304409
has comment: http://stackoverflow.com/comment/89346981
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89279934
accepted answer of: http://stackoverflow.com/q/51143378
has comment: http://stackoverflow.com/comment/89277406
has comment: http://stackoverflow.com/comment/89311490
answers question: http://stackoverflow.com/q/51143378
type: Answer
has comment: http://stackoverflow.com/comment/89338529
score: 2
has comment: http://stackoverflow.com/comment/89280187
has body: Please refer to my work steps and see if the error still shows up. Step 1 : Create azure web app and add Extensions(here is Python 3.6.1 x64) Step 2 : Publish your flask project and add the web.config. web.config: &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="WSGI_HANDLER" value="&lt;Your Project Name&gt;.app"/&gt; &lt;add key="PYTHONPATH" value="D:\home\site\wwwroot"/&gt; &lt;add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/&gt; &lt;/appSettings&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\Python361x64\python.exe|D:\home\Python361x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; If you deploy successfully, you could see following structure in the KUDU path: D:\home\site\wwwroot&gt;. If you want to use additional python package, please go on. Step 3: Switch to the Kudu CMD and commands cd Python361x64 and touch get-pip.py and copy the content of the url https://bootstrap.pypa.io/get-pip.py into the get-pip.py via Edit button, then run python get-pip.py to install the pip tool. Step 4 : Install any packages you need via python -m pip install pyodbc Hope it helps you. Any concern ,please let me know. Update: In my steps, copy content in https://bootstrap.pypa.io/get-pip.py to install pip. It could identify the system python version, install the corresponding python package. So,you just need to run the command python -m pip install newspaper3k to install newspaper3k.
has comment: http://stackoverflow.com/comment/89278865
upvote count: 2

http://stackoverflow.com/comment/89348424
comment on: http://stackoverflow.com/a/51166986
has text: @ASHUTOSHBBHATT - Problem is not same types of both columns, so need convert to same: `df1['movieId'] = df1['movieId'].astype(int)` and `df2['movieId'] = df2['movieId'].astype(int)` before `map`.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89228337
score: 0
type: Comment
type: QuestionComment
has text: are m_uio and b_uio constants? there appears to be a casting issue.
comment on: http://stackoverflow.com/q/51121524

http://stackoverflow.com/comment/89265923
has text: I like how you used another dict as the return val ```e.get("sensor_data", dict())``` so you didn't have to do any error checking. Never though about doing that.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51110897
type: Comment

http://stackoverflow.com/comment/89114120
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51062006
has text: https://github.com/micktwomey/docker-python2.7/blob/master/Dockerfile go through this docker file and check you are using right commands.
score: 0

kubernetes
tags question: http://stackoverflow.com/q/51120417
tags question: http://stackoverflow.com/q/51032599
tags question: http://stackoverflow.com/q/51136741
tag name: kubernetes
tags question: http://stackoverflow.com/q/51130596
tags question: http://stackoverflow.com/q/51030560
tags question: http://stackoverflow.com/q/51164215
tags question: http://stackoverflow.com/q/51066721
tags question: http://stackoverflow.com/q/51092807
type: Tag

http://stackoverflow.com/comment/89148867
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51079127
has text: `"25.075.0"` is inherently ambiguous, though. Is it `"25.0", "75.0"` or `"25.07", "5.0"`? You need to assume that each number has exactly one place after the decimal point for any of the answers to work. It would be better if you could modify whatever produces that string to use a separating character.

http://stackoverflow.com/q/51070229
tagged with: python
has comment: http://stackoverflow.com/comment/134784701
linked to: http://stackoverflow.com/q/59737296
linked to: http://stackoverflow.com/q/34929985
has comment: http://stackoverflow.com/comment/134785332
type: Question
linked to: http://stackoverflow.com/q/52820971
has title: When using boto is it safe to have a long running client object?
score: 5
upvote count: 5
tagged with: boto3
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/53790668
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: So let's say I have a long running web server that makes calls to the aws api? Is it safe to have a long running client object, or will that object possibly get corrupted and mess up my web server? For concreteness is it better to do something like this import boto3 client = boto3.client('elb') def function(): do stuff with client or this import boto3 def function(): client = boto3.client('elb') do stuff with client The former option is better because I can reuse the same client object in multiple function. The latter option would be better if my above safety concern is valid.
has answer: http://stackoverflow.com/a/51070265

http://stackoverflow.com/comment/89147082
score: 0
type: QuestionComment
type: Comment
has text: In your question, you provide `[[6, 7], [5, 0, 4], [6, 0, 4], [9, 4], [8, 2], [4, 9, 10], [1], [0], [9, 0], [7, 7], [8, 3, 1]]` -> node 0 connect to `[6, 7]`. This is **directed** graph, and the **start node** is 0, not 10, you just reverse the path from the end node.
comment on: http://stackoverflow.com/q/51078671

http://stackoverflow.com/q/51164771
has comment: http://stackoverflow.com/comment/101856414
type: Question
has body: My Jupyter notebook's python kernel keeps dying. I have run all of the following code successfully before. Presently, there are issues. First, I will show you the code chunk that I am able to run successfully: import xgboost as xgb xgtrain = xgb.DMatrix(data = X_train_sub.values, label = Y_train.values) # create dense matrix of training values xgtest = xgb.DMatrix(data = X_test_sub.values, label = Y_test.values) # create dense matrix of test values param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic'} # specify parameters via map where my data is small: X_train_imp_sub.shape (1365, 18) however, my notebook's kernel keeps dying on this chunk: xgmodel = xgb.train(param, xgtrain, num_boost_round = 2) # train the model predictions = xgmodel.predict(xgtest) # make prediction from sklearn.metrics import accuracy_score accuracy = accuracy_score(y_true = Y_test, y_pred = predictions.round(), normalize = True) # If False, return # of correctly classified samples. Else, return fraction of correctly classified samples print("Accuracy: %.2f%%" % (accuracy * 100.0)) When I break it apart and run line-by-line, the kernel appears to die on the xgb.train() line. The data is small. The xgboost parameters should be conservative (i.e. num_boost_round = 2, max_depth:2, eta:1 and not computationally expensive. Not sure what is going on. As stated before, I have been able to run both chunks successfully before. I have shut down all other notebooks and restarted my computer without luck. I am launching jupyter through Anaconda Navigator on a Macbook Pro. -- UPDATE -- When I selected a cell beneath my xgboost training cell, then selected: Cells --> Run All Above, the kernel would always die on the xgboost training line. This happened ~40-50 times in a row. I tried that many times because I was making changes to the code, thinking I would resolve the xgboost issue later. Later on, I ran the same cells one-by-one and the xgboost completed fine on the first time I tried …
upvote count: 20
score: 20
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51752425
has title: Python xgboost: kernel died
tagged with: xgboost
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90472935
has comment: http://stackoverflow.com/comment/89322212
has answer: http://stackoverflow.com/a/66668393
has answer: http://stackoverflow.com/a/61071123

http://stackoverflow.com/comment/89191794
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51102237
has text: Whats the content of `output_file_name`?

http://stackoverflow.com/comment/89092009
score: 0
type: AnswerComment
has text: Clarity: The [:] implies lst and caller list share the same memory space and both aliases will be modified
type: Comment
comment on: http://stackoverflow.com/a/51050410

http://stackoverflow.com/comment/89197511
comment on: http://stackoverflow.com/a/51105067
type: Comment
score: 0
type: AnswerComment
has text: can you try another library like import dask.dataframe as dd

http://stackoverflow.com/comment/89027356
comment on: http://stackoverflow.com/a/51017467
type: AnswerComment
score: 0
type: Comment
has text: i dont care about what it writes, just whether or not it created the file. when i move the `with open` to above the loop, it works strangely

http://stackoverflow.com/q/51055596
tagged with: python
has answer: http://stackoverflow.com/a/51057497
linked to: http://stackoverflow.com/q/42556063
score: 1
has comment: http://stackoverflow.com/comment/89101867
has title: Working with Urdu and Arabic names in Python
upvote count: 1
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/89101897
has comment: http://stackoverflow.com/comment/89101910
tagged with: urdu
answer count: 1
downvote count: 0
tagged with: arabic
tagged with: string
has comment: http://stackoverflow.com/comment/89101762
favorite count: 0
has body: I'm trying to work with Urdu text but am unable to get the right output. name = '\xd9\x87\xd9\x84\xd9\x84\xd8\xa7 \xd8\xa7\xd9\x85\xd8\xa7\xd9\x86' print name OUTPUT هللا امان DESIRED OUTPUT امان اللہ please advise.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89101752

http://stackoverflow.com/a/51159576
upvote count: 2
has comment: http://stackoverflow.com/comment/89303860
has body: i think your problem is that you execute the spider like so: python infograbber.py but you need to go in your folder where is scrapy.cfg and run scrapy like this: scrapy crawl infograbber
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89304010
has comment: http://stackoverflow.com/comment/89303933
accepted answer of: http://stackoverflow.com/q/51159487
type: Answer
answers question: http://stackoverflow.com/q/51159487
score: 2

http://stackoverflow.com/a/51029720
type: Answer
has body: Traverse the list and delete is_overnight key and its value of every dict. Like: my_list = [{'open': [{'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 0}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 1}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 2}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 3}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 4}, {'is_overnight': False, 'start': '1100', 'end': '2200', 'day': 5}, {'is_overnight': False, 'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR', 'is_open_now': False}] for i in my_list[0]["open"]: del i["is_overnight"] print(my_list) Output: [{'open': [{'start': '1100', 'end': '2200', 'day': 0}, {'start': '1100', 'end': '2200', 'day': 1}, {'start': '1100', 'end': '2200', 'day': 2}, {'start': '1100', 'end': '2200', 'day': 3}, {'start': '1100', 'end': '2200', 'day': 4}, {'start': '1100', 'end': '2200', 'day': 5}, {'start': '1100', 'end': '2100', 'day': 6}], 'hours_type': 'REGULAR', 'is_open_now': False}]
has comment: http://stackoverflow.com/comment/89060981
score: 0
answers question: http://stackoverflow.com/q/51029516
has comment: http://stackoverflow.com/comment/89053149

http://stackoverflow.com/comment/89046415
comment on: http://stackoverflow.com/q/51026983
score: 0
has text: I don't think the installing pathway is different. Did you have a look into configuring e.g. tensorflow for CPU only usage? https://stackoverflow.com/questions/37660312/how-to-run-tensorflow-on-cpu
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51142313
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51142961
tagged with: http://stackoverflow.com/tag/json
tagged with: subclassing
type: Question
has body: I would like to define a subclass of dict with, in particular, custom JSON serialization. The problem I'm running into is that if I directly subclass dict, then the json module does not enter into the 'default' function, when encountering instances of my dict subclass, there by bypassing my custom serialization. Consider: import collections class MyDictA(dict): # subclass of dict def to_json(self): return { "items": dict(self), "_type": self.__module__ + "." + self.__class__.__name__, } def __repr__(self): return self.__class__.__name__ + "(" + repr(dict(self)) + ")" class MyDictB(collections.MutableMapping): # behaves like a dict, is not a dict # can easily implement the remaining dict methods def __getitem__(self, item): return self.__dict__[item] def __setitem__(self, key, value): self.__dict__[key] = value def to_json(self): return { "items": vars(self), "_type": self.__module__ + "." + self.__class__.__name__, } def __repr__(self): return self.__class__.__name__ + "(" + repr(self.__dict__) + ")" def __iter__(self): return self.__dict__.__iter__() def __len__(self): return len(self.__dict__) def __delitem__(self, key): del self.__dict__[key] I can easily implement the remaining dict methods, so that MyDictB is a drop-in replacement for dict, but this somehow feels non-pythonic. Now we implement the custom serialization: import json def my_default(obj): if hasattr(obj, "to_json"): return obj.to_json() else: return obj Example: A = MyDictA() A["foo"] = "bar" B = MyDictB() B["foo"] = "bar" Result: &gt;&gt;&gt; print(A) MyDictA({'foo': 'bar'}) &gt;&gt;&gt; print(B) MyDictB({'foo': 'bar'}) &gt;&gt;&gt; print(jsonA) {"foo": "bar"} &gt;&gt;&gt; print(jsonB) {"_type": "__main__.MyDictB", "items": {"foo": "bar"}} As you can see, only MyDictB passes through the custom serialization, 'my_default'; instances of MyDictA never do, since they are dict instances. the problem in the json module is that it conditions on isinstance(obj, dict), see the implementation of "_iterencod…
downvote count: 0
has title: python json module and subclassing dict
score: 2
linked to: http://stackoverflow.com/q/16405969
answer count: 1
favorite count: 0
tagged with: serialization
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/89208141
type: Comment
comment on: http://stackoverflow.com/a/51109672
type: AnswerComment
has text: Care to provide some counterexamples? I'd be more than happy to correct it if I know what's wrong.
score: 0

http://stackoverflow.com/comment/89162261
type: Comment
type: QuestionComment
has text: Maybe you should open an issue on github, sounds like a bug to me. May related to optimization in low precision floating-point calculation, not sure though.
comment on: http://stackoverflow.com/q/51078039
score: 2

http://stackoverflow.com/comment/89129308
type: AnswerComment
has text: @Rive11 I have updated my answer to fix any typos. You should be able to copy, paste, and run my entire code in a new .py file without any errors. The error you received may be because your existing DF has more rows than the length of List abc - this means the for loop is trying to access an index greater than the number of elements in List abc. In this case, you can replace `enumerate(range(0, len(df)))` with `enumerate(range(0, len(abc)))` which only checks the rows up to index `len(abc)-1`
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51052016

http://stackoverflow.com/comment/89203574
has text: You shouldn't use Python without virtual environments or containers. And you definitely should not be messing with system-level Python interpreters (you're lucky Windows doesn't rely on Python for any system utilities).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51108226
type: Comment

repeat
tags question: http://stackoverflow.com/q/51109076
tag name: repeat
tags question: http://stackoverflow.com/q/51047954
type: Tag
tags question: http://stackoverflow.com/q/51156339

http://stackoverflow.com/a/77525235
score: 0
answers question: http://stackoverflow.com/q/51076494
type: Answer
has body: L = [1,2,3,4,5] for i in L: L.remove(i) print(L) In the above code, we will expect an empty list but it will display the following output [2,4]. Let me explain what happens at each iteration to make it easier to understand. In the 1st iteration, element 1 is removed which is at the 0th index i.e., L[0]. In the second iteration, the length of the list changes, and the elements move to the left i.e., L is now [2,3,4,5]. Again, indices in Python start with 0, so L[0] = 2, L[1] = 3, etc. Now the variable i is L[1] in the updated list, so L[1] = 3 is removed and this process will continue until the end of the list. The solution is, as others suggested, del L[:].

http://stackoverflow.com/comment/95100860
has text: @JorenV thank you for the explanation. That is the best way IMHO to do it currently. I *still* wish dataclasses even did that dance for you (but I can settle for this) - it is more explicit after all.
comment on: http://stackoverflow.com/a/51080197
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51140389
upvote count: 7
favorite count: 0
has title: Returning errors from Python to PowerShell?
tagged with: python
has body: I'm running multiple Python scripts in PowerShell, and I want at specific condition in Python script to notify PowerShell main script. Like throwing an error from Python and catching it with PowerShell. Python example: import os print "Running Python script ..." raise Exception("This Error is coming from Python") And PowerShell main script: $ErrorActionPreference = 'Stop' try { python runThisScript.py -ErrorAction Stop # Write-Error -Message 'Oh no! An error!' Write-Host "What is that?" } catch { Write-Host $_.Exception.Message -ForegroundColor Green throw [System.Exception] "Python scrip XXX failed" } finally { Write-Host "This is the final block ..." } But this does not work. It will show: Running Python script ... Traceback (most recent call last): File "runThisScript.py", line 5, in &lt;module&gt; raise Exception("This Error is coming from Python") Exception: This Error is coming from Python What is that? This is the final block ... If I un-comment the line Write-Error -Message 'Oh no! An error!' this is what I want to see (the error is catch and handle by PowerShell). Oh no! An error! This is the final block ... Python scrip XXX failed At C:\Automation\general_stuff\tc\mainTestRunner.ps1:12 char:5 + throw [System.Exception] "Python scrip XXX failed" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], Exception + FullyQualifiedErrorId : Python scrip XXX failed Thank you in advance for your comments.
linked to: http://stackoverflow.com/q/11004666
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/89324394
type: Question
has comment: http://stackoverflow.com/comment/89306496
has comment: http://stackoverflow.com/comment/89281345
has comment: http://stackoverflow.com/comment/139483993
has comment: http://stackoverflow.com/comment/89268256
tagged with: powershell
has comment: http://stackoverflow.com/comment/89311190
has comment: http://stackoverflow.com/comment/89268088
has comment: http://stackoverflow.com/comment/137950140
has comment: http://stackoverflow.com/comment/89306248

http://stackoverflow.com/q/51068281
favorite count: 0
has comment: http://stackoverflow.com/comment/89126690
type: Question
has comment: http://stackoverflow.com/comment/89157417
score: 5
tagged with: python
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/89126770
has comment: http://stackoverflow.com/comment/89126629
has title: Decorator works for Function but not Class
has comment: http://stackoverflow.com/comment/89126605
upvote count: 5
has comment: http://stackoverflow.com/comment/89126645
has comment: http://stackoverflow.com/comment/89128112
has comment: http://stackoverflow.com/comment/89126721
tagged with: python-unittest
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51068490
tagged with: python-2.7
has body: Need a bit of help correcting a decorator for unittest. I'm not sure how to meet the requirements of unit test. The idea of this decorator is to mark the test as an expectedFailure IF True is passed in. Otherwise allow the test to simply run. This decorator works for test functions but doesn't work for class definitions import unittest def expectedFailureIf(expFailure): if expFailure: return unittest.expectedFailure return lambda func: func @expectedFailureIf(GetCurrentOS() == kPlatMac) # Fails on Class class someClass(unittest.TestCase): #@expectedFailureIf(GetCurrentOS() == kPlatMac) # Works on Function def test_sometestA(self): assert True def test_sometestB(self): assert False The error that I'm getting is test_sometest() takes exactly 1 argument. Removing the decorator allows the test to run. Moving the decorator to top of function allows the test to run. History... One of my platforms works fine and the other platform does not. I want to allow one platform to run all the tests while the other platform will be marked as expected failures. Of course I do not want to use skip or skip if. Since that won't allow the valid platform to run. Marking them as expected failure will also not work since one platform will return unexpected success. With the expectedFailureIf() in place each platform will correctly report and once things are fixed these tests will report as unexpected success. Which will notify ME when things are fixed. For me... this seems a better outcome.
has comment: http://stackoverflow.com/comment/89128805
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51105907
has title: class instance method takes exactly two args, one given
has comment: http://stackoverflow.com/comment/89199847
has comment: http://stackoverflow.com/comment/89200118
type: Question
has comment: http://stackoverflow.com/comment/89200076
has comment: http://stackoverflow.com/comment/89199874
answer count: 1
has body: I am having a bit of an issue. First off, I know that this code is able to stand alone and not be in a class but I would prefer that it is in a class. Second, when I run the code, I get this error TypeError: set_options() takes exactly 2 arguments (1 given) . Here is my code. If anyone could point me in the right direction, I would appreciate it. I'm assuming that the set_options method isn't getting my jobj instance. Am I correct in assuming that and how would one go about fixing this? ps. I do have the correct imports and here is my py command at terminal python test.py radar 127.0.0.1 hashNumber testplan:speed class TransferStuff(object): tool = sys.argv[1] target = sys.argv[2] hash = sys.argv[3] options = sys.argv[4] def set_options(self, test_options): option_arr = test_options.split(',') new_arr = [i + ':{}'.format(i) for i in option_arr if ':' not in i] for i in option_arr: if ':' in i: new_arr.append(i) d = {} for i in new_arr: temp = i.split(':') d[temp[0]] = temp[1] return d data = {'target': target, 'test': tool, 'HASH': hash, 'options': set_options(options)} def write_to_json(self): """Serialize cli args and tool options in json format. Write stream to json file. """ with open('envs.json', 'w') as fi: json.dump(TransferStuff.data, fi) if __name__ == "__main__": try: jobj = TransferStuff() jobj.write_to_json()
has comment: http://stackoverflow.com/comment/89199554
has comment: http://stackoverflow.com/comment/89199539
has answer: http://stackoverflow.com/a/51106083
has comment: http://stackoverflow.com/comment/89199649
has comment: http://stackoverflow.com/comment/89199733
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89200805
tagged with: python
has comment: http://stackoverflow.com/comment/89198862
tagged with: instance

http://stackoverflow.com/a/51023814
type: Answer
answers question: http://stackoverflow.com/q/51022485
has body: This also works: A = [1,2,0] answers = [[] for element in A] answers[0] = [[number,] for number in range(A[0]+1)] for i in range(len(A)-1): for possibility in answers[i]: for valid_number in range(A[i+1]+1): answers[i+1].append(possibility + [valid_number, ]) your_answer = answers[-1] It could probably be written in a more compact way.
score: 0

http://stackoverflow.com/comment/89155590
has text: @zwer I got you :) I was just looking out a way to get through without removing any module/sub module.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51082728

http://stackoverflow.com/q/51084028
tagged with: opencv
tagged with: ironpython
has title: Python3, OpenCV and C#
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/89214497
has body: I'd like to port my current python3 project with the use of opencv, numpy to Windows and integrated with C# projects. However, I found that IronPython only supports up to Python2. A few issues: What is the best way to do the integration as the python code depends on a number of external libraries and python3 wrapper? What is the way to integrate with C# if IronPython3 is not yet ready?
score: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89195990
tagged with: python

http://stackoverflow.com/q/51100546
has comment: http://stackoverflow.com/comment/89189367
accepted answer: http://stackoverflow.com/a/51105154
has comment: http://stackoverflow.com/comment/89189244
tagged with: selenium
has title: Selenium WebDriver cannot click element even though it seems to be visible
type: Question
has answer: http://stackoverflow.com/a/51105154
linked to: http://stackoverflow.com/q/51239512
tagged with: python-2.7
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51101010
has body: Using Python 2, Selenium using Firefox, on this page, I am trying have the driver click the following button (the magnifying glass): Search I use the following code for the XPath of the element, x = '//*[@id="search-btn"]': x = '//*[@id="search-btn"]' try: element = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, x))) except: print "Element not clickable" else: found_element = driver.find_element_by_xpath(x) try: found_element.click() except: raise Selenium's common exception EC.element_to_be_clickable doesn't identify the element, nor does visibility_of_element_located nor presence_of_element_located. Strangely however, at a few occasions the driver has actually been able to identify the element and then perform driver.find_element_by_xpath(x) which appears to find the XPath and .click() the element. At that point everything works. For a second I thought that the script was to quick to execute the operation before the page had loaded, but 5 seconds WebDriverWait is plenty to load the page, and I have an additional page-load-in sleep before that. The element doesn't seem to be in an IFrame. I have already passed through the "Accept Conditions"-buttons, etc. I am running the latest versions of Firefox (61.0), Selenium (3.13) and Geckodriver (0.21.0). What could be the problem here?
has answer: http://stackoverflow.com/a/51101010
tagged with: python
has comment: http://stackoverflow.com/comment/89189220
has answer: http://stackoverflow.com/a/51101938
tagged with: selenium-webdriver
type: AnsweredQuestion

http://stackoverflow.com/comment/89058322
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51032945
has text: project id and user id is alright. This still gave the same error.I am wondering is it because of my url ? @Ralf

http://stackoverflow.com/comment/89228846
type: QuestionComment
has text: show your traceback
comment on: http://stackoverflow.com/q/51121789
score: 0
type: Comment

http://stackoverflow.com/a/51167538
score: 0
accepted answer of: http://stackoverflow.com/q/51167007
type: AcceptedAnswer
type: Answer
has body: Here you go. awk -F, 'NR == 1 {print} NR &gt; 1 { printf $1; for (ii = 2; ii &lt;= NF; ii++){ printf(",%1.2e", $ii) } print ""}' input.txt The reference for printf may come in handy.
has comment: http://stackoverflow.com/comment/89326592
answers question: http://stackoverflow.com/q/51167007

http://stackoverflow.com/q/51054636
tagged with: python
has body: I0625 17:25:22.544378 3366 solver.cpp:229] Iteration 7120, loss = 8.79839 expected output : Iteration 7120 loss = 8.79839
has comment: http://stackoverflow.com/comment/89100307
tagged with: unix
has title: How to extract specific columns in log file to csv file
accepted answer: http://stackoverflow.com/a/51062173
downvote count: 3
has comment: http://stackoverflow.com/comment/89113520
answer count: 1
has comment: http://stackoverflow.com/comment/89102469
score: -3
tagged with: logfile
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51062173
favorite count: 0
tagged with: linux
type: Question
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/89363623
type: Comment
has text: So `id` column is not necessary? Only need Dataframe from `df.phone_numbers` column?
comment on: http://stackoverflow.com/a/51155291
score: 0
type: AnswerComment

http://stackoverflow.com/a/54773112
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/51133753
answers question: http://stackoverflow.com/q/51133753
type: Answer
has body: First I created a new conda virtual enviornment to use with multithreading: conda create -n nomkl_env python=3.7 numpy nomkl I activated this environment and ran this command via the conda MKL docs: conda install numpy scipy scikit-learn numexpr Now I am able to run multiple instances of Python at the same time. Earlier when I ran conda remove mkl mkl-service it somehow removed python from the bin of an existing virutal env. This was sub-optimal. I would up creating a dedicated conda env and this did the trick.
upvote count: 2
downvote count: 1

http://stackoverflow.com/comment/89236325
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51125676
has text: What python version?

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/51034252
type: Tag

http://stackoverflow.com/q/51056161
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89109645
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89109768
score: 1
accepted answer: http://stackoverflow.com/a/51057043
has comment: http://stackoverflow.com/comment/89106229
has title: Keras Dense Layer Output - Shape Error
type: Question
has comment: http://stackoverflow.com/comment/89112560
downvote count: 0
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/89109180
tagged with: lstm
has body: I was working on an NLP problem with LSTM. The problem is a multiclass classification with 3 classes (1,2 &amp; 3). So I converted the target classes with the following code: y_train=to_catgorical(y_train) and similarly for y_test. But in the output dense layer when I write model.add((Dense(3,activation='softmax')), I get the following error: Error when checking target: expected dense_1 to have shape (None, 3) but got array with shape (658118, 4) However when I fix it to model.add((Dense(4,activation='softmax')), i.e. n+1 (n=no. of classes to be predicted) it works. But in Keras examples they have worked with cifar10 dataset and have used number of classes as 10, not 11 and it works. Also in case of binary classification (2 classes to be predicted) we use just 1 ouptut, i.e. model.add(Dense(1,"sigmoid")). I've gone through this post but still not been able to find a convincing logic for this thing, so I want to get this concept cleared with the Dense layer output shape in Keras. P.S. What I've understood is, Keras considers classes from 0:num_classes, so we have to give one more transformation. But to ask one thing that '0' vector layer then has to remain unused right? And in case of cifar10 dataset, is it that the classes are 0:9, that's why num_classes=10 work? If that is the case then if we have to make a prediction of 3 classes say (0,1 &amp; 2) then we can use num_classes=3 right?
tagged with: deep-learning
has answer: http://stackoverflow.com/a/51057043
favorite count: 0
has comment: http://stackoverflow.com/comment/89109337

http://stackoverflow.com/q/51078276
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89145466
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89145580
has answer: http://stackoverflow.com/a/51078585
accepted answer: http://stackoverflow.com/a/51078585
has body: So I have been working abit with json and just improving the knowledge with it basically. What I want to do is that I save all these numbers that are available etc on a list or whatever you might think of. The Json: { "threads": [ { "seoTitle": "trucks", "other_crap": "it's a fox!" }, { "seoTitle": "rockets", "other_crap": "i'm rocket man" }, { "seoTitle": "helicopter", "other_crap": "for 007", "skus": [ { "Number": "7", "available": true }, { "Number": "7.5", "available": true }, { "Number": "8", "available": false }, { "Number": "8.5", "available": true }, { "Number": "9", "available": true }, { "Number": "9.5", "available": false }, { "Number": "10", "available": true }, { "Number": "10.5", "available": false }, { "Number": "11", "available": true }, { "Number": "11.5", "available": false }, { "Number": "12", "available": true }, { "Number": "12.5", "available": false }, { "Number": "13", "available": true } ], "restricted": false, "subtitle": "Stackoverflow" } ] } As you can see from the Json file there is skus and below that there is different Number and available and what I want to do is that I want to print all the NUMBERS based on IF it is available meaning if its available then print it out or save it into a list and then print it out when it has search all of the and if it is not available then just skip to next one. - That is what my goal is - The problem is that I don't know what I should do based through a json file, How can I possible make it so it knows what to save into a list based on available ? 1) what your expected output is, I expect a output that might look like: helicopter for 007 7 7.5 8.5 9 10 11 12 13 2) what you have tried so far, Right now I have only printed out seoTitle and other_crap print(threads['seoTitle']) print(threads['other_crap']) 3) why what you've tried isn't working I have tried to do a for loop which I totally failed with doing for element in threads['skus']: if element not 'available' basically failed :/ code that I am usi…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89145441
has title: Python - Save all 'available' elements in Json and print it afterwards when all search is finished?
favorite count: 0
has comment: http://stackoverflow.com/comment/89145237
has comment: http://stackoverflow.com/comment/89145300
tagged with: python
has comment: http://stackoverflow.com/comment/89145227
type: AnsweredQuestion

http://stackoverflow.com/a/51211233
type: Answer
answers question: http://stackoverflow.com/q/51069774
accepted answer of: http://stackoverflow.com/q/51069774
score: 0
has body: Okay, so I figured it out by avoiding keyboard completely. The problem was, as if pyinstaller couldn't include the module properly, so I just rewrote the code using canvas.bind() function.
type: AcceptedAnswer

http://stackoverflow.com/q/51166326
score: 1
linked to: http://stackoverflow.com/q/51147008
has comment: http://stackoverflow.com/comment/89316528
tagged with: sqlite
downvote count: 0
has comment: http://stackoverflow.com/comment/89316465
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89328938
tagged with: parallel-processing
has body: Is it possible to run django test cases in parallel with in memory sqlite3 with new database for each test case? Docs says: "--parallel" Runs tests in separate parallel processes. Each process gets its own database. # *settings_test.py DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'} When I run my test in single process, all goes well. python.exe manage.py test --settings=gbook.settings_test When i use --parallel param, DiscoverRunner.setup_databases called only one time. python.exe manage.py test --settings=gbook.settings_test --parallel=4 In result i reseive this: OperationalError("Problem installing fixture ...AirportInfo.json': Could not load order.AirportInfo(pk=2411): no such table: GB_AIRPORT_INFO",) Please, help me to understand, what am i doing wrong. multiprocessing.cpu_count() = 4 Django version 1.11.10 Python 3.6.5
answer count: 0
has comment: http://stackoverflow.com/comment/89348355
tagged with: django
upvote count: 1
has title: Run django test parallel with in memory sqlite3
type: Question
tagged with: testing

http://stackoverflow.com/q/51069226
answer count: 1
accepted answer: http://stackoverflow.com/a/51069904
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 0
downvote count: 2
type: Question
has title: Not saving graph to specified folder
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89128309
has comment: http://stackoverflow.com/comment/89128424
has answer: http://stackoverflow.com/a/51069904
has body: I am generating the graph and saving to the specified folder but no figure is saved in that specific destination. The graph is generated for one time only and I am getting an error after that. Here is my code import numpy as np import matplotlib.pyplot as plt final_obj=np.array([[ 8.31907313 , 0.17300669], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 ,0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 , 0.19566612], [ 8.50432396 ,0.19566612], [ 8.50432396 ,0.19566612], [ 8.50432396 ,0.19566612]]) print(final_obj) x1=[] y1=[] for z in range(0,5): for i in range(0,len(final_obj)): X=final_obj[i][0] x1.append(X) Y=final_obj[i][1] y1.append(Y) plt.plot(x1, y1, label = "line 1",marker='o',linestyle = 'None') plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.legend() plt.show() save_results_to = "C:\\Users\hp\PycharmProjects\SRMMEA\venv\IRIS_GRAPH" plt.savefig(save_results_to+'GRAPH_{}.png'.format(z), format="PNG") And it showing an error for the above code Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python36\silvspbm.py", line 35, in &lt;module&gt; plt.savefig(save_results_to+'GRAPH_{}.png'.format(z), format="PNG") File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\pyplot.py", line 710, in savefig res = fig.savefig(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\figure.py", line 2035, in savefig self.canvas.print_figure(fname, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\backend_bases.py", line 2263, in print_figure **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\backends\backend_agg.py", line 526, in print_png with cbook.open_file_cm(filename_or_obj, "wb") as fh: File "C:\Users\hp\AppData\Local\Programs\Python\Pyt…

http://stackoverflow.com/q/51109598
score: 2
tagged with: algorithm
upvote count: 3
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89206346
tagged with: python
has body: I am trying to find a more efficient solution to this question: https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem/0 The problem statement is: Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k. My solution(just the main logic): for i in range(0,n): for j in range(i+1,n): if((a[i]+a[j])%k==0 and j not in res): res[i]=a[i] res[j]=a[j] if(len(res)==n): print("True") else: print("False")` As evident, its a brute force solution that will work in O(n^2). I am basically adding the visited pairs to a list. But is there a more efficient solution than this? Thanks for your time!
favorite count: 0
has title: Check if the pair sum of elements is divisible
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51109672
downvote count: 1

http://stackoverflow.com/q/51117357
score: 1
has title: Python3 Sending Email with Smtplib [Yandex]
type: Question
tagged with: smtp-auth
accepted answer: http://stackoverflow.com/a/51117443
upvote count: 1
answer count: 1
tagged with: smtp
favorite count: 0
has answer: http://stackoverflow.com/a/51117443
tagged with: python-3.x
has body: I'm trying to send emails using yandex but my function doesn't work. It's just waiting forever there is no error either. Here is my function : def send_emails(title,msg): server = smtplib.SMTP('smtp.yandex.com.tr:465') server.ehlo() server.starttls() server.login(yandex_mail,yandex_pass) message = 'Subject: {}\n\n{}'.format(title,msg) server.sendmail(yandex_mail,send_to_email,message) server.quit() print('E-mails successfully sent!') send_emails('Test Mail', 'Yes its a test mail!')
tagged with: python
linked to: http://stackoverflow.com/q/39516200
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/89113469
has text: You must initialize an application context in Flask. `app = Flask(__name__)` and perform all these actions in an app route `@app.route('/')` which should render your html page or make an AJAX call. Finally, you should call this with `if __name__ == '__main__': app.run(debug=True)`. This will display any Traceback errors in the console when the app runs. Please paste that traceback error here.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51060433
type: QuestionComment

http://stackoverflow.com/comment/89166750
score: 0
has text: you are opening the file in `"w"` write mode, you should open in `"r"`read mode, or you are mixing csv_file names there....
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51089194

http://stackoverflow.com/a/51063623
answers question: http://stackoverflow.com/q/51049854
has comment: http://stackoverflow.com/comment/118267654
score: 0
has comment: http://stackoverflow.com/comment/89132406
type: Answer
has body: I got it figured out. I'm still not sure why I wasn't able to figure this out the first time, but it was an SELinux issue, as suspected. The problem was that everything under the virtual environment directory needed to have the httpd_sys_content_t context, except dynamically-loaded binary libraries, which need httpd_sys_script_exec_t. Once I did that, the python-home argument to WSGIDaemonProcess worked as expected.
has comment: http://stackoverflow.com/comment/118293577

http://stackoverflow.com/q/51146949
tagged with: binary-matrix
has comment: http://stackoverflow.com/comment/89668414
tagged with: matrix
has comment: http://stackoverflow.com/comment/89666952
tagged with: python
has body: I need to generate all possible 4x4 binary matrices that have zeros along the main diagonal, are symmetric, and have six entries equal to 1. Some examples: [[0,0,0,0], [0,0,1,1], [0,1,0,1], [0,1,1,0]], [[0,1,1,0], [1,0,1,0], [1,1,0,0], [0,0,0,0]], [[0,1,0,1], [1,0,0,1], [0,0,0,0], [1,1,0,0]] How could I do that in Python?
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51311172
has title: All possible binary matrices with some properties
score: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89026351
type: QuestionComment
comment on: http://stackoverflow.com/q/51016095
has text: @Selcuk Thanks so much! I've been searching all day and thought I saw just about every question related to this on stackoverflow but somehow missed that one. If you like, feel free to add something as an answer so I can accept it.
score: 0
type: Comment

http://stackoverflow.com/q/51110406
type: Question
has answer: http://stackoverflow.com/a/51112207
has title: How to add a FileTransport cleanly to Asyncio?
score: 0
answer count: 1
has body: I'm writing an application which reads text data and acts on it. The text data could come from a TCP port, or from a text file (which contains data earlier read from the TCP port and archived). I'm writing it in Python 3, and using asyncio seems like the obvious tool to use. It's straightforward to use the Streams API open_connection() to open the TCP port and read from it. The asyncio architecture has the concept a Transport and a Protocol for the lower and upper layers of input-output. So, it seems I should implement a Transport for reading text from a file, and pass it to the Protocol. That will let me keep the rest of my application decoupled from whether the text data came from the TCP port or the file. But I'm having a hard time figuring out how to tell asyncio to use my preferred Transport. the Streams API open_connection() has a parameter list which is all about the TCP port Transport, with no way to specify a different Transport, much less parameters like file path. open_connection() turns around and calls loop.create_connection(). This is just as specialised for the TCP Port Transport. Still now way to provide a different Transport. The implementation of loop.create_connection() gets its Transport object from either self._make_ssl_transport() or self._make_socket_transport(). These have alternative implementations in asyncio.selector_events.BaseSelectorEventLoop and asyncio.proactor_events.BaseProactorEventLoop, so we are clearly past the point where a File Transport ought to have been selected. Am I missing some place where asyncio lets me tell it what Transport to use? Or is asyncio really coded down to its roots to use its own TCP port and UDP datagram Transports, and nothing else? If I want to allow the possibility of using my own Transport with asyncio, it looks like I have to extend the event loop, or write more a flexible alternative create_connection() that is coded to a particular event loop implementation. That seems like a lot of work, and vulne…
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51068439
has comment: http://stackoverflow.com/comment/89126826
has comment: http://stackoverflow.com/comment/89133320
upvote count: 1
has comment: http://stackoverflow.com/comment/89126798
accepted answer: http://stackoverflow.com/a/51110100
has title: ImportError: cannot import name 'sync'
tagged with: telethon
type: AnsweredQuestion
score: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to run the following sample code from telethon: from telethon import TelegramClient, sync # These example values won't work. You must get your own api_id and # api_hash from https://my.telegram.org, under API Development. api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' client = TelegramClient('session_name', api_id, api_hash) client.start() But I'm getting the following error: [root@server cli]# python3.6 client.py Traceback (most recent call last): File "client.py", line 1, in &lt;module&gt; from telethon import TelegramClient, sync ImportError: cannot import name 'sync' I also have tried installing sync using the following command: pip3.6 install sync Any idea about the problem?
has comment: http://stackoverflow.com/comment/89127058
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51110100

http://stackoverflow.com/a/51028416
answers question: http://stackoverflow.com/q/51028091
type: Answer
score: 0
has body: As jonrsharpe suggested, list comrehension makes a copy of the list. So what stock_price() does is actually make a copy of the list, and only then iterating on it and calculating the sum. (note that the builtin sum function is actually more efficient than a for look, as it is implemented in C) On the other hand, stock_price2() does not copy the list, which saves a lot of time spent on allocations for the new list.

http://stackoverflow.com/q/51126475
type: Question
accepted answer: http://stackoverflow.com/a/51126548
tagged with: numpy
downvote count: 0
tagged with: pandas
answer count: 1
has body: I have two simple data frames: a = homes_in.copy() b = homes.copy() a['have'] = [True,]*a.shape[0] b['have'] = [True,]*b.shape[0] a = a['have'].to_frame() b = b['have'].to_frame() print(a.shape) print(b.shape) a.reset_index(inplace=True) b.reset_index(inplace=True) idx_cols = ['State', 'RegionName'] c = pd.merge(a, b, how='outer', left_on=idx_cols, right_on=idx_cols, suffixes=['_a', '_b']) print(c.shape) print(sum(c['have_a'])) print(sum(c['have_b'])) output (10730, 1) (10592, 1) (10730, 4) 10730 10730 Where a.head() is: have State RegionName NY New York True CA Los Angeles True IL Chicago True PA Philadelphia True AZ Phoenix True The problem: all values in columns have_a and have_b has True value. I've tried to replicate the behaviour with faked data but failed: col = ['first', 'second', 'third'] a = pd.DataFrame.from_records([('a','b',1), ('a','c',1), ('a','d', 1)], columns=col) b = pd.DataFrame.from_records([('a','b',2), ('a','c',2)], columns=col) pd.merge(a,b,how='outer',left_on=['first','second'],right_on=['first', 'second'])
score: 1
favorite count: 0
has title: Pandas' DataFrame merge unexpected values
has answer: http://stackoverflow.com/a/51126548
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/57852535
answers question: http://stackoverflow.com/q/51143881
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: I have found a solution for this particular problem which worked perfectly for me. [This is only for linux users] Open terminal and execute the following command: xhost +SI:localuser:root That's all. Thanks to mooze@github.com. I got this solution from there. Link: https://github.com/mooz/xkeysnail/commit/9f3a79ab77eea6c581414bbbcc3b90db5eff5c26

http://stackoverflow.com/comment/89060629
score: 0
type: Comment
type: QuestionComment
has text: Thanks Paul, I'll take a look at pandas. Zev I'm aware of how to do the above in excel, just in python i can't seem to do.
comment on: http://stackoverflow.com/q/51034233

http://stackoverflow.com/q/51121524
has comment: http://stackoverflow.com/comment/89229088
downvote count: 4
has comment: http://stackoverflow.com/comment/89228509
has title: Unsupported operand type(s) for *: 'function' and 'float'
answer count: 1
has answer: http://stackoverflow.com/a/51121549
favorite count: 0
linked to: http://stackoverflow.com/q/38723825
tagged with: pandas
has comment: http://stackoverflow.com/comment/89228376
tagged with: python
has body: I am trying to use lambda function to multiply the column values with a floating point value, but it is throwing the exception. Code snippet: m_forecasts['potential'] = m_forecasts['bnchmk_qty'].apply(lambda x: x * round((m_uio + 1) / (b_uio + 1))) Error: line 374, in &lt;lambda&gt; m_forecasts['potential'] = m_forecasts['bnchmk_qty'].apply(lambda x: x * round((m_uio + 1) / (b_uio + 1))) TypeError: unsupported operand type(s) for *: 'function' and 'float') What is the root cause for the error? Please help. Note: Working on Pandas 0.17 version head() of bnchmk_qty column: 0 &lt;function multiplier at 0x1135ae230&gt; 1 &lt;function multiplier at 0x1135ae230&gt; 2 &lt;function multiplier at 0x1135ae230&gt; 3 &lt;function multiplier at 0x1135ae230&gt; 4 &lt;function multiplier at 0x1135ae230&gt; Name: bnchmk_qty, dtype: object
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89228337
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89228359
has comment: http://stackoverflow.com/comment/89228470
has comment: http://stackoverflow.com/comment/89228346

http://stackoverflow.com/comment/89064009
has text: @WernfriedDomscheit - probably at the expense of all the other queries on that table which don't select on `col_5`. That's what I meant by *'the wider picture'*. We know nothing about the OP's situation, not least whether they are licensed to use Partitioning option.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51034507
score: 0

http://stackoverflow.com/a/51023250
has body: You can you this little snippet where the output will be processed in the res array. data = [1,2,3,4,5,6] res = [] for i in range(0, len(data), 2): res.append((data[i+1]/data[i])) print(res) I have a lot of experience with trading algorithms and I will say that your format is OK for starting out, but if you get into more complicated algorithms you should consider creating a transaction class to hold you transaction information.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89039244
answers question: http://stackoverflow.com/q/51022966
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51022966

http://stackoverflow.com/comment/89168797
type: QuestionComment
score: 0
has text: You might check that ODBC Tracing and similar debug functions are disabled on the client side, as these can slow things down massively.
type: Comment
comment on: http://stackoverflow.com/q/51035435

http://stackoverflow.com/comment/89315742
comment on: http://stackoverflow.com/q/51166266
type: Comment
type: QuestionComment
has text: @MatthewStory: Python 3.7 officially makes dict order retention part of the language spec.
score: 2

http://stackoverflow.com/comment/89156694
has text: I am with "Python 3.6.3 :: Intel Corporation" and "numba 0.38.0".
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51062850

http://stackoverflow.com/q/51074280
answer count: 2
tagged with: pyspark
tagged with: dataframe
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am trying to translate a numpy lambda function to its equivalent for a PySpark data frame. I have been struggling to find the correct functions/methods. I conduct the following operation on a Pandas dataframe to generate a new column, label, for panda_stack: panda_stack['label'] = panda_stack.groupby('id')['prob1'].transform(lambda x: 0.0 if all(np.isnan(x)) else 1.0) Basically, I have: id prob1 id1 NA id1 0.12 id2 NA and want: id label id1 1 id2 0 Can someone please help me translate the above code to something that does the same for a PySpark Data Frame?
has answer: http://stackoverflow.com/a/51080078
score: 1
has title: Translate `numpy` operation for Pandas DataFrame to equivalent for PySpark DataFrame
has answer: http://stackoverflow.com/a/51080381
type: Question

http://stackoverflow.com/comment/89281494
has text: I think it should be c['Slogan']
comment on: http://stackoverflow.com/a/51148761
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89175511
has text: I think we are both confused, the original behavior of the dropdown without the modification(what I am seeing) is that clicking on the `QLineEdit` (not the QPushbutton) is that it only opens the `MultiCheckComboBox`, clicking the `QLineEdit` again when it is open only refreshes it. Unlike the `QPushbutton` where it opens and closes it. The functionality that I am trying to add is to make the `QLineEdit` behave like the `QPushButton` when clicked.
comment on: http://stackoverflow.com/q/51093034
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89114546
type: Comment
type: QuestionComment
score: 1
has text: Er.. in the first version you set the seed once and then repeatedly request a random value, in the second you set the seed on every iteration and then request a random value which will be same every time, what are you expecting?
comment on: http://stackoverflow.com/q/51062412

http://stackoverflow.com/a/51124768
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/51124745
answers question: http://stackoverflow.com/q/51124745
type: Answer
has body: The integer is a file descriptor, the integer number the OS uses to talk about file handles assigned to a process. 0, 1 and 2 are stdin, stdout and stderr, 3 and up are further file descriptors used. You get the resource warning because you open the file handle, but never close it explicitly. You instead just call .readlines() or .readline() on the Python file object wrapper: sink_list = os.popen('pacmd list-sinks | grep "name:" | cut --delimiter=: -f2').readlines() This leaves the file object to be closed by the garbage collector, and you get the warning. You can use the open object as a context manager to have it closed for you: with os.popen('pacmd list-sinks | grep "name:" | cut --delimiter=: -f2') as list_sinks: sink_list = list_sinks.readlines() Personally, I'd use the subprocess module to handle external processes, and use Python to do the line selection. This lets you avoid spinning up a separate sh process and generally has much nicer exception handling: import subprocess # read list of sinks result = suprocess.run(['pacmd', 'list-sinks'], stdout=subprocess.STDOUT, encoding='UTF-8') sink_list = [l.split(':', 2) for l in result.stdout if 'name:' in l] # read default sink result = suprocess.run(['pacmd', 'list'], stdout=subprocess.STDOUT, encoding='UTF-8') default_sink = next((l.split(':', 2) for l in result.stdout if 'Default sink name' in l), None)
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89049887
has text: If you think about it, the rotation angle of the text is an absolute measure when the angle of the curve depends on the axis' scales. For a quick observation, change the size of the plot windows. So, I guess the calculus of the rotation angle should somehow involves information about the axis.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51028431

http://stackoverflow.com/q/51066651
has comment: http://stackoverflow.com/comment/89123870
accepted answer: http://stackoverflow.com/a/51067004
has title: At work, see python programmer define an empty class inside of a class to get "dot structure". Is this bad?
has comment: http://stackoverflow.com/comment/89123286
has comment: http://stackoverflow.com/comment/89123964
has body: I have seen this from a coworker, and want to know if this is legit. A class is defined in order to get the self.thing.morethings structure. import numpy as np class MyBigThing: def __init__(self): self.thing_builder() def compute(self): print(self.thing.morethings) def thing_builder(self): self.x = 2 self.y = 2 self.z1 = (2, 2) class thing: pass self.thing = thing self.thing.morethings = np.zeros(self.z1) Personally, I would define an entirely separate class. I think the first implementation is meaningless, and will be better formed like this. Meaning we can construct more Things later down the line rather than create them adhoc in the MyBigThing. import numpy as np class MyBigThing: def __init__(self): self.thing_builder() def compute(self): print(self.thing.morethings) def thing_builder(self): self.x = 2 self.y = 2 self.z1 = (2, 2) self.thing = Thing(self.z1) class Thing: def __init__(self, shape): self.morethings = np.zeros(shape) You can test either one with: import test x = test.MyBigThing() x.compute() You should get with either implementation: [[0. 0.] [0. 0.]]
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89123321
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51067004
has comment: http://stackoverflow.com/comment/89123704
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/51067594
type: Question
has answer: http://stackoverflow.com/a/51067594
answer count: 2
upvote count: 1

http://stackoverflow.com/q/51117351
type: UnansweredQuestion
has body: I am trying to define a custom loss function in Keras def yolo_loss(y_true, y_pred): Here the shape of y_true and y_pred are [batch_size,19,19,5]. for each image in the batch, I want to compute the loss as: loss = square(y_true[:,:,0] - y_pred[:,:,0]) + square(y_true[:,:,1] - y_pred[:,:,1]) + square(y_true[:,:,2] - y_pred[:,:,2]) + (sqrt(y_true[:,:,3]) - sqrt(y_pred[:,:,3])) + (sqrt(y_true[:,:,4]) - sqrt(y_pred[:,:,4])) I thought of a couple of ways of doing this, 1) using a for loop: def yolo_loss(y_true, y_pred): y_ret = tf.zeros([1,y_true.shape[0]]) for i in range(0,int(y_true.shape[0])): op1 = y_true[i,:,:,:] op2 = y_pred[i,:,:,:] class_error = tf.reduce_sum(tf.multiply((op1[:,:,0]-op2[:,:,0]),(op1[:,:,0]-op2[:,:,0]))) row_error = tf.reduce_sum(tf.multiply((op1[:,:,1]-op2[:,:,1]),(op1[:,:,1]-op2[:,:,1]))) col_error = tf.reduce_sum(tf.multiply((op1[:,:,2]-op2[:,:,2]),(op1[:,:,2]-op2[:,:,2]))) h_error = tf.reduce_sum(tf.abs(tf.sqrt(op1[:,:,3])-tf.sqrt(op2[:,:,3]))) w_error = tf.reduce_sum(tf.abs(tf.sqrt(op1[:,:,4])-tf.sqrt(op2[:,:,4]))) total_error = class_error + row_error + col_error + h_error + w_error y_ret[0,i] = total_error return y_ret This however gives me an error: ValueError: Cannot convert a partially known TensorShape to a Tensor: (1, ?) This is because I guess the batch size is undefined. 2) Another way is to apply the sqrt transformations to each of the image tensors in the batch and then subtract them and then apply the square transform. for e.g 1) sqrt(y_true[:,:,:,3]) 2) sqrt(y_pred[:,:,:,3]) 3) sqrt(y_true[:,:,:,4]) 4) sqrt(y_pred[:,:,:,4]) 5) y_new = y_true-y_pred 6) square(y_new[:,:,:,0]) 7) square(y_new[:,:,:,1]) 8) square(y_new[:,:,:,2]) 9) reduce_sum for each new tensor in the batch and return o/p in shape [1,batch_size] However I could not find a way to do this in Keras. Can someone suggest, what would be the best way to implement this loss function. I am using Keras with tensorflow at the backend.
tagged with: python
downvote count: 0
tagged with: tensorflow
type: Question
score: 5
has title: Keras custom loss function for YOLO
answer count: 1
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51117710
upvote count: 5

http://stackoverflow.com/comment/89252362
type: Comment
has text: @Zuma it will be through conda3, i wanted to do it through pip but doing it was horrible
comment on: http://stackoverflow.com/q/51133752
score: 0
type: QuestionComment

serial-port
tags question: http://stackoverflow.com/q/51069578
type: Tag
tags question: http://stackoverflow.com/q/51137165
tag name: serial-port
tags question: http://stackoverflow.com/q/51154886
tags question: http://stackoverflow.com/q/51061898
tags question: http://stackoverflow.com/q/51108994

http://stackoverflow.com/comment/89067443
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51037568
has text: it has been migrated, I add a picture of the migrations @HåkenLid
score: 0

http://stackoverflow.com/comment/89305864
type: QuestionComment
comment on: http://stackoverflow.com/q/51160403
type: Comment
has text: Alright, thanks for the reply i appreciate it. I posted the question on SuperUser.
score: 0

http://stackoverflow.com/a/51164913
has comment: http://stackoverflow.com/comment/89313744
accepted answer of: http://stackoverflow.com/q/51164849
score: 36
answers question: http://stackoverflow.com/q/51164849
upvote count: 36
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89314124
type: Answer
has comment: http://stackoverflow.com/comment/123612260
has body: Considering Entity1 maps to table1, and Entity2 maps to table2: rows = session .query(Entity1, Entity2) .join(Entity2, (Entity1.col1==Entity2.col1) &amp; (Entity1.col2==Entity2.col2)) .all() rows will be a list of tuples where rows[][0] is Entity1 and rows[][1] is Entity2. You can use .join() and then specify the join condition with the second param. If you omit the join condition, then the .query() method alone generates a cross join between table1 and table2.
has comment: http://stackoverflow.com/comment/89313931
has comment: http://stackoverflow.com/comment/89314180

http://stackoverflow.com/q/51028906
type: UnansweredQuestion
tagged with: python
has body: This is my python code: cursor = conn.cursor () cursor.execute("CREATE DATABASE IF NOT EXISTS my_db") cursor.execute("USE my_db") table = """CREATE TABLE IF NOT EXISTS `table1` ( `id` INT NOT NULL, `rank` INT NULL, PRIMARY KEY (`id`) )""" cursor.execute(table) It ran perfectly the first time when the db and table didn't exist. I ran it a second time to check if the IF NOT EXIST clause worked correctly. But it didn't! I got the following warnings: script.py:67: Warning: Can't create database 'my_db'; database exists cursor.execute("CREATE DATABASE IF NOT EXISTS my_db") script.py:79: Warning: Table 'table1' already exists cursor.execute(table) Did I format my query incorrectly somehow? It matches everything I'm finding online as far as I can tell.
has comment: http://stackoverflow.com/comment/89051233
answer count: 0
tagged with: mysql
linked to: http://stackoverflow.com/q/2102251
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89052184
linked to: http://stackoverflow.com/q/11599263
upvote count: 3
has title: 'create table if not exists' query still giving warning if table exists
linked to: http://stackoverflow.com/q/8935228
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/106256776

http://stackoverflow.com/comment/89254932
type: AnswerComment
type: Comment
has text: You are simply the best of the best, thank you for your answer. Anyone who is facing this issue i would suggest them to try this solution.
score: 1
comment on: http://stackoverflow.com/a/51135080

http://stackoverflow.com/comment/89036311
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51021929
has text: `yaml.load` returns a dictionary. The colons are not kept
type: Comment

http://stackoverflow.com/q/51055867
duplicate of: http://stackoverflow.com/q/30180241
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89102330
accepted answer: http://stackoverflow.com/a/51055927
score: 0
answer count: 1
has body: I know I can get the minimum value of a numpy matrix column-wise using: my_array.min(axis=0) But is there any way to efficiently get equivalent index/row instead of the values them-self? For instance: my_array = [[10, 2, 3], [1, 3, 10], [20, 19, 0]] I expect to get something like this: [1, 0, 2] >> location of minimum values instead of values.
has title: Numpy matrix column wise minimum value index
tagged with: python
linked to: http://stackoverflow.com/q/30180241
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51055927

http://stackoverflow.com/q/51056746
has answer: http://stackoverflow.com/a/51067699
tagged with: jquery
has body: I am trying to get a string data that is send from Ajax to Python. However, as I log the code, the data isn't sent. It's empty. Could you tell me why? p.s. the purpose of the code is to get the name of the submit button to validate in views.py javascript views.py def add_test(request): if request.method == 'POST': test_name = request.POST.get('test_name') test_type = request.POST.get('test_type') test_date = request.POST.get('test_date') test_obj = Test(test_name = test_name, test_type = test_type, test_date = test_date) test_obj.save() button_pressed = request.POST.get('button_pressed') #button_pressed = json.loads(button_pressed) print button_pressed ,"+++++++++++++++++++++++++++++" return HttpResponseRedirect('/test-management/test/') test_list.html {% csrf_token %} Add Test Name : Type : Date : Cancel Add & New Add I am new to Django, so sorry if the question is silly. Thank for helping!
tagged with: ajax
tagged with: django
has comment: http://stackoverflow.com/comment/89104309
tagged with: python
has comment: http://stackoverflow.com/comment/89104503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89104516
has comment: http://stackoverflow.com/comment/89104753
type: Question
has title: Django: data send from Ajax to Python is emptied
possible better answer: http://stackoverflow.com/a/51057141
has answer: http://stackoverflow.com/a/51057401
has answer: http://stackoverflow.com/a/51057141
has comment: http://stackoverflow.com/comment/89104253
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/51057401

http://stackoverflow.com/a/51065234
accepted answer of: http://stackoverflow.com/q/51064563
answers question: http://stackoverflow.com/q/51064563
has body: If you would use a regex, perhaps this would match your requirements: ^\d+(?: *- *\d+)?(?:, *\d+(?: *- *\d+)?)*$ Explanation ^ Assert start of the line \d+ Match one or more digits (?: Non capturing group *- *\d+ Match zero or more whitespaces followed by a hyphen, one or more whitespaces and one or more digits )? Close non capturing group and make it optional (?: Non capturing group , *\d+ Match a comma, zero or more whitespaces and one or more digits (?: Non capturing group *- *\d+ Match zero or more whitespaces followed by hyphen, zero or more whitespace characters and one or more digits )? Close non capturing group and make it optional )* Close non capturing group and repeat it zero or more times $ Assert the end of the line Demo
has comment: http://stackoverflow.com/comment/89123967
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89122790
score: 3

http://stackoverflow.com/comment/89051729
comment on: http://stackoverflow.com/q/51025716
has text: I've added a fully working example along with a screenshot.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/51044817
has body: I got the issue, It was related to proxy settings. Actually I am using two VMs (Both have different IPs) with two different micro services (First VM has User Registration service (Add User, Delete User, Get Users) and Second VM has a service to call the User Registration service using django rest framework). Now VMs are working in a local area network with some network permissions, So I have to set the proxy range and then I have to start the server. I am using below command for proxy setting before running the Django server: export no_proxy='my IP/range' Now it works fine.
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51043560
accepted answer of: http://stackoverflow.com/q/51043560

http://stackoverflow.com/q/51120947
has title: Javascript variable to json in Python
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89227345
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51121088
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51121088
has body: I have a string look as javascript variable '{name : "John" , age : 17}' in Python, how I can convert it to JSON like this { "name" : "John" , "age" : 17 } or how to add double quotes to field name and age. json.loads coudn`t help me, it return me string not json

http://stackoverflow.com/a/77240359
score: 0
has body: I also had the same problem, maybe you should after doing all the above, just continue your code and it will work. it did for me
type: Answer
answers question: http://stackoverflow.com/q/51114826
has comment: http://stackoverflow.com/comment/136198920

http://stackoverflow.com/comment/89221190
type: QuestionComment
score: 2
has text: The `var` in tk_version.py is entirely unrelated to the `var` in main.py - `global` in Python means "global to this module", not "global everywhere". After having done `import main`, `main.var` will refer to its variable.
comment on: http://stackoverflow.com/q/51117323
type: Comment

http://stackoverflow.com/q/51096714
has answer: http://stackoverflow.com/a/51096865
possible better answer: http://stackoverflow.com/a/51096795
favorite count: 0
has answer: http://stackoverflow.com/a/51096916
has answer: http://stackoverflow.com/a/51096795
has body: From the code below as you can see mysearch is called without arguments. How is this function call possible? How is it this technique called? Where does the method get it's argument (tag)? I'm sorry I can't find my answer anywhere... def myserach(tag): return tag.has_attr('ResultsAd') # and tag['li'] with open('index.html', 'rb') as file: soup = BeautifulSoup(file, "html.parser") elements1 = soup.find_all('div', attrs={"class": "ResultsAd"}) elements1 = soup.find_all(myserach)
accepted answer: http://stackoverflow.com/a/51096867
answer count: 4
has comment: http://stackoverflow.com/comment/89181171
tagged with: python
type: AnsweredQuestion
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51096867
has title: How can function which has arguments be called without arguments
downvote count: 0
score: 4

http://stackoverflow.com/a/51015341
type: AcceptedAnswer
has body: It boils down to whether you are creating new objects or not. It turns out approaches 1 to 3 do not create new objects, here is why. Approach 1 &amp; 3: ❌ While they look different, those two approaches are the same. When calling copy.deepcopy on an integer (or any immutable builtin type), the copy module uses the following method. def _deepcopy_atomic(x, memo): return x So whenever you deepcopy an integer, the same object is returned. Likewise, deepcopying an list of integers actually returns a shallow copy. from copy import deepcopy l = [1000] print(l[0] is deepcopy(l)[0]) # True Approach 2: ❌ By doing [x for x in a], you trivially make a new list with exactly the same objects. Here is a sanity check. l1 = [1000] l2 = [x for x in l1] print(l1[0] is l2[0]) # True Approach 4: ✅ Now this approach actually creates a new object for integers bigger than 256. x = 1000 print(x is x + 0) # False Final word While the last approach is the only one that actually creates a new object, I could not find anything in the doc stating that this is a property of the language. So keep in mind that this might be implementation specific and that it is not unlikely to encounter an interpret which optimizes x + 0 to always return the same object.
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51015245
answers question: http://stackoverflow.com/q/51015245
has comment: http://stackoverflow.com/comment/89023752
has comment: http://stackoverflow.com/comment/89023632
upvote count: 3

http://stackoverflow.com/comment/89309559
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51163052
has text: urlname just containing images name I am getting dynamically @Lemayzeur . AND THEN i APPEND IN THIS WITH BASEURL
score: 0

http://stackoverflow.com/a/54282726
answers question: http://stackoverflow.com/q/51134129
downvote count: 0
type: Answer
has body: This is old, so i'm sure you don't care anymore. But here's the answer. Your A4 pagesize is (8.27x11.69)in. In addtable you say create me a table with 13 columns (len(data[0])). And make them all 1 inch wide (colWidths = [1 * inch] * col). Since 13in + margin > 8.27in, reportlab draws items off the page. Hard to find documentation tip. colWidths=['*'] will set all columns equal width, filling only the usable page width.
upvote count: 1
score: 1

http://stackoverflow.com/q/51120555
has comment: http://stackoverflow.com/comment/89230704
has comment: http://stackoverflow.com/comment/89231706
score: 4
has comment: http://stackoverflow.com/comment/89231662
has comment: http://stackoverflow.com/comment/89232279
has comment: http://stackoverflow.com/comment/89231647
tagged with: regression
answer count: 3
has comment: http://stackoverflow.com/comment/89230747
has answer: http://stackoverflow.com/a/51123191
has body: I've recently started machine learning using python. Below is a dataset I picked up as an example along with the codes I've worked on till now. Chosen [2000....2015] as the test data and train data [2016, 2017]. Dataset Years Values 0 2000 23.0 1 2001 27.5 2 2002 46.0 3 2003 56.0 4 2004 64.8 5 2005 71.2 6 2006 80.2 7 2007 98.0 8 2008 113.0 9 2009 155.8 10 2010 414.0 11 2011 2297.8 12 2012 3628.4 13 2013 16187.8 14 2014 25197.8 15 2015 42987.8 16 2016 77555.5 17 2017 130631.9 import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier df = pd.DataFrame([[i for i in range(2000,2018)], [23.0,27.5,46.0,56.0,64.8,71.2,80.2,98.0,113.0,155.8,414.0,2297.8,3628.4,16187.8,25197.8,42987.8,77555.5,130631.9]]) df = df.T df.columns = ['Years', 'Values'] The above code creates the DataFrame. Another important thing to keep in mind is that my Years column is a TIME-SERIES and not just a continuous value. I haven't made any changes to accomodate this. I'm want to fit non-linear models that may help and print the plots like I've done for my linear model example. Here is what I've tried using a linear model. Also, in my own example, I do not seem to be accounting for the fact that my Years column is a time series and NOT continuous. Once, we've the model, would like to use that for predicting values for next couple of years atleast. X = df.iloc[:, :-1].values y = df.iloc[:, 1].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 0, shuffle = False) lm = LinearRegression() lm.fit(X_train, y_train) y_pred = lm.predict(X_test) plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, lm.predict(X_train), color = 'blue') plt.title('Years vs Values (training set)') plt.xlabel('Years') plt.ylabel('Values') plt.show()
has comment: http://stackoverflow.com/comment/89231721
has comment: http://stackoverflow.com/comment/89231555
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51123031
has title: Fitting a non-linear univariate regression to time-series data
has comment: http://stackoverflow.com/comment/89230729
has comment: http://stackoverflow.com/comment/89231122
tagged with: non-linear-regression
tagged with: statistics
upvote count: 4
linked to: http://stackoverflow.com/q/51122688
has comment: http://stackoverflow.com/comment/89230740
has comment: http://stackoverflow.com/comment/89230723
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89232246
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89231617
has comment: http://stackoverflow.com/comment/89230793
has answer: http://stackoverflow.com/a/51136392
has comment: http://stackoverflow.com/comment/89231690
tagged with: python

http://stackoverflow.com/a/51159923
answers question: http://stackoverflow.com/q/51159642
upvote count: 1
score: 1
downvote count: 0
has body: It is important to consider What makes a citation unique? Based on your example, it appears that the combination of authors, the title of the article, and what year it was published constitutes a unique citation. This means that you can parse the names, then compare how close they are (Because the third example lists the names differently). Parse the title, and it should match 100%. Parse the year, and it should also be a 100% match.
type: Answer

http://stackoverflow.com/q/51067932
has body: The program takes a list of English words written in the first column of an excel file named "List" using pandas, the headline of the column is "words" and the words are located in "Sheet1". The words are then stored as a list of strings. PyDictionary and Googletrans are utilized by creating dictionary and translator where the translator is called by translations in order to translate the words from the list into the destination language "Danish". A simple for loop is then created where every translation in the list of translated words is printed with its origin -> its destination and its definition. This is presented in the code below: from googletrans import Translator import pandas as pd from PyDictionary import PyDictionary # Load excel file and parse the list of words as strings file_location = "/Users/.../List.xlsx" xl_workbook = pd.ExcelFile(file_location) df = xl_workbook.parse("Sheet1") aList = df['words'].tolist() [str(i) for i in aList] # Use PyDictionary to load definitions of words dictionary = PyDictionary() # Translate the list of strings into target language and give definitions translator = Translator() translations = translator.translate(aList, dest='da') # Simple for-loop printing the words for translation in translations: print( translation.origin, ' -&gt; ', translation.text, dictionary.meaning(translation.origin) ) This program actually runs and produced the result I wished. However, the problem occurs in the next step as explained here: I wish to input the words into my favorite flash-card program Anki. Anki is written in Python and has an un-official distribution named Genanki. However, this is when I encounter my issues. I now add the following 4 things to my code above: I define my_model as proposed by genanki and create a simple model of a flashcard. This includes a random hardcoded number (which Anki requires), a name of the model, some fields and a template for the card type. I define my_deck as the specific deck of flashcards with a har…
answer count: 1
tagged with: anki
has title: Python script creating anki flashcards using genanki (Expected str instance, dict found ERROR)
has answer: http://stackoverflow.com/a/51414986
type: UnansweredQuestion
tagged with: google-translate
tagged with: pandas
downvote count: 0
tagged with: pydictionary
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89172340
type: Comment
has text: Side note: hex colors are hexadecimal. They go from 0 to F, not to Z.
score: 1
comment on: http://stackoverflow.com/q/51092015
type: QuestionComment

http://stackoverflow.com/q/51061196
has answer: http://stackoverflow.com/a/51066419
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89113337
has title: Matrix Multiplication using divide and conquer in Python
has comment: http://stackoverflow.com/comment/89113357
has comment: http://stackoverflow.com/comment/89113147
has body: I wrote a program in python3 to find out a product of 2 n*n matrices, (where n is a power of 2). Why the code below does not work out and shows IndexError: invalid index to scalar variable? import numpy as np def product(x, y, k): def fsum(p, q, m): r = [[p[i, j] + q[i, j] for j in range(m)] for i in range(m)] return r if k == 1: return x[0][0] * y[0][0] else: A = x[0:(k // 2), 0:(k // 2)] B = x[0:(k // 2), (k // 2):k] C = x[(k // 2):k, 0:(k // 2)] D = x[(k // 2):k, (k // 2):k] E = y[0:(k // 2), 0:(k // 2)] F = y[0:(k // 2), (k // 2):k] G = y[(k // 2):k, 0:(k // 2)] H = y[(k // 2):k, (k // 2):k] C00 = fsum(product(A, E, k // 2), product(B, G, k // 2), k // 2) C01 = fsum(product(A, F, k // 2), product(B, H, k // 2), k // 2) C10 = fsum(product(C, E, k // 2), product(D, G, k // 2), k // 2) C11 = fsum(product(C, F, k // 2), product(D, H, k // 2), k // 2) return np.array([[C00, C01], [C10, C11]]) n = int(input('Enter index(power of 2): ')) print('Input 1st matrix') a = np.array([[int(_) for _ in input().split()] for x in range(n)]) print('Input 2nd matrix') b = np.array([[int(_) for _ in input().split()] for x in range(n)]) print(product(a, b, n))
type: UnansweredQuestion
tagged with: numpy
has answer: http://stackoverflow.com/a/51062232
tagged with: python-3.x
type: Question
tagged with: python

http://stackoverflow.com/comment/89235809
type: Comment
comment on: http://stackoverflow.com/a/51125349
score: 1
has text: i think you need to add the check for `None` in `last_source`
type: AnswerComment

http://stackoverflow.com/a/51023194
accepted answer of: http://stackoverflow.com/q/51014407
answers question: http://stackoverflow.com/q/51014407
has body: Because iterparse() does not have a write function as it returns a tuple, you cannot write to a document in the same way as with .parse(). switching my code to use parse resolved the issue. root = tree.getroot() for way in root.findall(".//way"): kbool = False tbool = False for key in way.iterfind(".//tag"): if key.attrib['k'] == "tiger:name_base": kbool = True # print(key.attrib['v']) base = key.attrib['v'] if key.attrib['k'] == "tiger:name_type": tbool = True ttype = key.attrib['v'] if kbool == True and tbool == True: ET.SubElement(way, 'tag k="addr:street" v="{} {}"'.format(base, ttype)) elif kbool == True and tbool == False: ET.SubElement(way, 'tag k="addr:street" v="{}"'.format(base)) tree.write('maps')
type: AcceptedAnswer
score: 0
type: Answer

cucumber
tags question: http://stackoverflow.com/q/51141878
type: Tag
tag name: cucumber

http://stackoverflow.com/q/51154052
has comment: http://stackoverflow.com/comment/89295396
has title: python - tkinter - delete canvas
tagged with: canvas
duplicate of: http://stackoverflow.com/q/5767228
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89295410
has body: I wanted to delete everything on a canvas. And i thought canvas.delete(tk.ALL) is a good way to go. But its not working. Why? The accelerators are also not working. import tkinter as tk class Graphy(tk.Frame): def __init__(self,parent): tk.Frame.__init__(self,parent) self.parent = parent self.parent.title("Graphy 0.1") self.initialize() def initialize(self): #Toolbar toolbar = tk.Frame(self.parent) toolbar.pack(side=tk.TOP, fill=tk.X) knotbtn=tk.Button(toolbar, text="o") knotbtn.pack(side=tk.LEFT, padx=2, pady=2) edgebtn=tk.Button(toolbar, text="/") edgebtn.pack(side=tk.LEFT, padx=2, pady=2) #Canvas self.canvas = tk.Canvas(self.parent, height=600, width=600, bg="white") self.canvas.pack() #Menue menu = tk.Menu(self.parent) self.parent.config(menu=menu) filemenu = tk.Menu(menu) menu.add_cascade(label="Datei", menu=filemenu) filemenu.add_command(label= "Neu", command=self.canvas.delete(tk.ALL), accelerator="Strg+N") filemenu.add_separator() filemenu.add_command(label="Beenden", command=root.quit, accelerator="Strg+Q") sightmenu = tk.Menu(menu) menu.add_cascade(label="Ansicht", menu=sightmenu) sightmenu.add_command(label="Farbe waehlen") helpmenu = tk.Menu(menu) menu.add_cascade(label="Hilfe", menu=helpmenu) helpmenu.add_command(label="Ueber") root.bind_all("&lt;Ctrl-N&gt;",self.canvas.delete(tk.ALL)) root.bind_all("&lt;Ctrl-Q&gt;",root.quit()) self.state = 0 self.selected = None self.start_x = 0 self.start_y = 0 def newKnotornewEdge(event): #if button "o" is pressed, every click on the canvas results in a circle if self.state == 0: self.canvas.create_oval(event.x-25,event.y-25,event.x+25, event.y+25, fill="blue") self.canvas.create_text(event.x, event.y, text="A", fill="white") #if button "/" is pressed, and two circles are selected, draw a line between them elif self.state == 1: if self.canvas.itemcget(self.canvas.find_overlapping(event.x, event.y, event.x, event.y), "fill") == "blue" and self.selected == None: self.selected = 1 self.start_x = event.x self.start_y = …
type: Question
has comment: http://stackoverflow.com/comment/89293499
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89292801
score: 0
has comment: http://stackoverflow.com/comment/89295907
has comment: http://stackoverflow.com/comment/89297684
has comment: http://stackoverflow.com/comment/89294896
linked to: http://stackoverflow.com/q/5767228

http://stackoverflow.com/comment/89117822
score: 0
has text: You can either downgrade `cx_Oracle` version in your `dev` env or you can somehow update it in `prod` env
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51063883

http://stackoverflow.com/a/51047602
has body: I use multiIndex, reindex, and interpolate: data = {'A Prime': {0: 3.26, 1: 3.24, 2: 3.22, 3: 3.2, 4: 3.18, 5: 3.16, 6: 3.14, 7: 1.52, 8: 1.5, 9: 1.48, 10: 1.46, 11: 1.44, 12: 1.42}, 'B': {0: 0.16608, 1: 0.16575, 2: 0.1654, 3: 0.16505999999999998, 4: 0.1647, 5: 0.16434, 6: 0.16398, 7: 0.10759, 8: 0.10687, 9: 0.10614000000000001, 10: 0.10540999999999999, 11: 0.10469, 12: 0.10396}, 'Proto Name': {0: 'Alpha', 1: 'Alpha', 2: 'Alpha', 3: 'Alpha', 4: 'Alpha', 5: 'Alpha', 6: 'Alpha', 7: 'Bravo', 8: 'Bravo', 9: 'Bravo', 10: 'Bravo', 11: 'Bravo', 12: 'Bravo'}} df = pd.DataFrame(data) df_ranges = df'Proto Name', 'A Prime'.groupby(['Proto Name']).agg(['min', 'max']) df =df.set_index(['Proto Name','A Prime']) print df_ranges A Prime min max Proto Name Alpha 3.1400 3.2600 Bravo 1.4200 1.5200 l_idx = [] for i in range(len(df_ranges)): PN = df_ranges.index[i] min = df_ranges.iloc[i][0] max = df_ranges.iloc[i][1] l_idx.extend([(PN,i) for i in np.array(range(int(min*100),int(max*100)+1,1))/100.]) # make tuples to reindex with idx = pd.MultiIndex.from_tuples(l_idx) df = df.reindex(idx) print df print df.interpolate() which gives B Alpha 3.14 0.16398 3.15 NaN 3.16 0.16434 3.17 NaN 3.18 0.16470 3.19 NaN 3.20 0.16506 3.21 NaN 3.22 0.16540 3.23 NaN 3.24 0.16575 3.25 NaN 3.26 0.16608 Bravo 1.42 0.10396 1.43 NaN 1.44 0.10469 1.45 NaN 1.46 0.10541 1.47 NaN 1.48 0.10614 1.49 NaN 1.50 0.10687 1.51 NaN 1.52 0.10759 B Alpha 3.14 0.163980 3.15 0.164160 3.16 0.164340 3.17 0.164520 3.18 0.164700 3.19 0.164880 3.20 0.165060 3.21 0.165230 3.22 0.165400 3.23 0.165575 3.24 0.165750 3.25 0.165915 3.26 0.166080 Bravo 1.42 0.103960 1.43 0.104325 1.44 0.104690 1.45 0.105050 1.46 0.105410 1.47 0.105775 1.48 0.106140 1.49 0.106505 1.50 0.106870 1.51 0.107230 1.52 0.107590
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89134674
score: 1
answers question: http://stackoverflow.com/q/51046122
has comment: http://stackoverflow.com/comment/89129492
has comment: http://stackoverflow.com/comment/89091379

http://stackoverflow.com/comment/89352371
comment on: http://stackoverflow.com/q/51113429
score: 0
type: Comment
type: QuestionComment
has text: I have solved it. A more recent version of Cycler than the one I had did the trick.

http://stackoverflow.com/comment/89128380
type: Comment
has text: One line of code is worth a thousand words spent for describing it :) Please share what you've tried as it is. Btw, welcome.
comment on: http://stackoverflow.com/q/51069029
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89209420
has text: Seems like a `dtype` conversion. np.mean gives you a `dtype = float32`. Is the `dtype` for `X_train_reshaped` `float64`??
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51111080

http://stackoverflow.com/q/51045222
has comment: http://stackoverflow.com/comment/89250624
has comment: http://stackoverflow.com/comment/89290943
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89291271
has comment: http://stackoverflow.com/comment/89260714
tagged with: python
has comment: http://stackoverflow.com/comment/89257630
favorite count: 0
type: UnansweredQuestion
tagged with: scapy
upvote count: 1
has comment: http://stackoverflow.com/comment/89285131
has comment: http://stackoverflow.com/comment/89289107
tagged with: network-programming
has body: When playing with scapy I observed the following behavior. The scapy manual page suggests as an example something like a=sniff(filter="tcp port 110") ... sendp(a) to re-inject captured packets. However, when I tried this myself, wireshark tells me ETHERNET FRAME CHECK SEQUENCE INCORRECT on all re-injected packets. (It does not matter which packets I capture and re-inject.) When I examined the packets interactively with scapy, I noticed that the Ethernet trailer (and the checksum) is not displayed. Moreover, there is no method to modify or set the trailer. Apparently, scapy does not work as I expect - what am I missing? How can I re-inject a copy of an ethernet frame such that it appears as valid? Detailed Example For this example I consider an ARP packet. However, the issue is present with other packet types as well. This is what wireshark recorded (dumped by tcpdump -v -XX -r ...): 14:05:39.517932 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.141.150 tell 192.168.140.193, length 46 0x0000: ffff ffff ffff 90b1 1c47 c81e 0806 0001 .........G...... 0x0010: 0800 0604 0001 90b1 1c47 c81e c0a8 8cc1 .........G...... 0x0020: 0000 0000 0000 c0a8 8d96 0000 0000 0000 ................ 0x0030: 0000 0000 0000 0000 0000 0000 ............ This is how scapy3 saw it: &gt;&gt;&gt; x = sniff(count=1, filter='arp') &gt;&gt;&gt; bytes(x[0]) b'\xff\xff\xff\xff\xff\xff\x90\xb1\x1cG\xc8\x1e\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01\x90\xb1\x1cG\xc8\x1e\xc0\xa8\x8c\xc1\x00\x00\x00\x00\x00\x00\xc0\xa8\x8d\x96\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' &gt;&gt;&gt; x[0].show() ###[ Ethernet ]### dst= ff:ff:ff:ff:ff:ff src= 90:b1:1c:47:c8:1e type= ARP ###[ ARP ]### hwtype= 0x1 ptype= 0x800 hwlen= 6 plen= 4 op= who-has hwsrc= 90:b1:1c:47:c8:1e psrc= 192.168.140.193 hwdst= 00:00:00:00:00:00 pdst= 192.168.141.150 ###[ Padding ]### load= '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' And then... &gt;&gt;&gt; sendp(x[0]) . Sent …
has answer: http://stackoverflow.com/a/51089744
score: 1
has title: re-injection of captured packets results in incorrect ethernet checksum
has comment: http://stackoverflow.com/comment/89291186
type: Question

http://stackoverflow.com/q/51062715
type: Question
tagged with: pypyodbc
tagged with: teradata
tagged with: python
upvote count: 2
tagged with: pyodbc
answer count: 1
has body: I am trying to run Teradata sql code in Python. The code involves building volatile tables but I still get error message when trying to create the second volatile table. Error Message below： [Teradata][ODBC Teradata Driver][Teradata Database] Only an ET or null statement is legal after a DDL Statement. (-3932) (SQLExecDirectW)') My code is below: sql1="""CREATE MULTISET VOLATILE TABLE A AS(......)WITH DATA PRIMARY INDEX(CUSTOMER_ID) ON COMMIT PRESERVE ROWS;""" sql2="""CREATE MULTISET VOLATILE TABLE B AS(......)WITH DATA PRIMARY INDEX(CUSTOMER_ID) ON COMMIT PRESERVE ROWS;""" cursor.execute(sql1) cursor.execute(sql2) Error shows when executing sql2 despite I tried making the two sql paragraphs into one and/or adding BT; and ET; I also tried switching TMODE in pyodbc.connect but it does not work as well. Is there a way for python to handle multiple volatile tables like teradata did or is there another approach? Thanks.
score: 2
has title: How to create multiple volatile tables in Python from Teradata using pyodbc
downvote count: 0
has answer: http://stackoverflow.com/a/72818055
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89119451
favorite count: 0

http://stackoverflow.com/comment/89536745
has text: You're understanding correctly @saitejapakalapati. If you are using DRF your backend is an API and you will fetch resources from it . Your client (in this case made with Angular) will consume resources from your API. :-)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51159301

http://stackoverflow.com/comment/89303465
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51160046
has text: `NAN` != `NaN`. did you typo the case on that `A`?

http://stackoverflow.com/comment/89309361
score: 0
type: Comment
type: AnswerComment
has text: thanks for this. I have a question about `poly__degree`: is this the standard format for accessing the specific parameters of steps in the pipeline? For example, what if I also want to find the optimal regularization coefficient `C`? Would I simply add `params = {'poly__degree' : np.arange(1,4), 'logreg__C' : np.logspace(-5, 8, 15)}`? In other words, do I simply use the double-underscore notation to create the GridSearch parameters `step__paramater`?
comment on: http://stackoverflow.com/a/51162705

http://stackoverflow.com/comment/89274958
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51145058
score: 0
has text: @RavinderSingh13 updated the post

http://stackoverflow.com/a/53748185
accepted answer of: http://stackoverflow.com/q/51027717
downvote count: 0
upvote count: 8
has body: Here a solution using Seaborn, which gives shorter code but gives up some flexibility compared to using Matplotlib directly: import seaborn as sns, matplotlib.pyplot as plt sns.set(style="whitegrid") tips = sns.load_dataset("tips") sns.barplot(x="day", y="total_bill", data=tips, capsize=.1, ci="sd") sns.swarmplot(x="day", y="total_bill", data=tips, color="0", alpha=.35) plt.show() And here the result:
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51027717
score: 8

http://stackoverflow.com/q/51111982
favorite count: 0
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/759201
upvote count: 1
has answer: http://stackoverflow.com/a/51112008
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89210877
has title: Pandas Convert float column containing nan values to int for merge operation
has body: Attempt #1 s["order_id"].apply(lambda x: int(x) if pd.notnull(x) else np.nan) Attempt #2 def to_int(x): if(pd.notnull(x)): return int(x) Attempt #3 s["order_id"] = s.loc[pd.notnull(s["order_id"]),"order_id].astype(int) All of these return a series where the values are still formatted as floats. I'm wondering if I could use the update function or take advantage of reindexing. Leveraging Indexing solution attempt: null = np.nan data = {"time":{"0":1528971021539,"1":1529289904697,"2":1529572773525,"3":1529892602301,"4":1530082881098,"5":1530069453264,"6":1528985491630,"7":1529236762719,"8":1529475504491,"9":1529814085541,"10":1529906568681,"11":1530160346468,"12":1529833559160,"13":1530051985183,"14":1530240956273,"15":1529794554495,"16":1529892989425,"17":1529386510176,"18":1529118607780,"19":1529404958912,"20":1529812956409,"21":1530012703548,"22":1527815420250,"23":1527826735070,"24":1527832343938,"25":1527853694229,"26":1527889066223,"27":1527986243670,"28":1528070794031,"29":1528149294729,"30":1528158483701,"31":1528172242288,"32":1528173686892,"33":1528174729282,"34":1528175624472,"35":1528184014365,"36":1528184994544,"37":1528199211274,"38":1528204822424,"39":1528236692102,"40":1528246124079,"41":1528251449061,"42":1528254158311,"43":1528324045380,"44":1528409837346,"45":1528429172972,"46":1528453372400,"47":1528525996756,"48":1528530493509,"49":1528539093472},"user_id":{"0":1754627236948496,"1":4702200191313171,"2":4778254911976758,"3":8293985621789157,"4":5156436454415407,"5":4445821205748907,"6":6872300957263521,"7":579402494860,"8":2010389994610194,"9":3378398685582335,"10":2923987501904097,"11":7254681572754712,"12":2280706641994510,"13":5853777483445659,"14":1790488830140089,"15":4649841298300342,"16":8296801793054868,"17":6074985077237804,"18":7512067556495704,"19":7449962479289671,"20":931159100938705,"21":4303206141550631,"22":4931136210605885,"23":910152652690726,"24":213367265258802,"25":59665205254502,"26":7375134691043656,"27":5112755499047871,"28":…
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51112008

http://stackoverflow.com/comment/127016685
has text: This question is not related to the question it allegedly duplicates. This question doesn't ask how a generator works, it asks *why a generator can only be used once*. Although @MartijnPieters says, "Because side-effects", I would appreciate a more in-depth reason/answer.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51032155

http://stackoverflow.com/comment/89046524
comment on: http://stackoverflow.com/q/51026315
has text: What is the result of `echo $LANG` ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51077769
has body: @RahulVerma looks pretty tough from first principles. The external edges should be pretty easy with Gaussian + Sobel + Canny. The inside is a mess due to uneven lighting and surfaces. I'm thinking shape index, but I expect that it will also be quite noisy. In your place I would try a machine learning based tool like Ilastik.
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89151911
answers question: http://stackoverflow.com/q/51056148
downvote count: 0

http://stackoverflow.com/comment/89111236
comment on: http://stackoverflow.com/q/51059993
has text: Yeah, that's correct
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51182742
has comment: http://stackoverflow.com/comment/89377273
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89372436
type: Answer
has body: Per my experience, we have no permission to modify D:\home environment. So , It's better to use python extension. Please follow the steps in this case: Azure Flask Routes Not found and use command python -m pip install newspaper to install additional packages in python extension. Please make sure the package you want to install must match with version of python extension. Otherwise, it will throw error as follows. Hope it helps you.
score: 1
accepted answer of: http://stackoverflow.com/q/51118110
answers question: http://stackoverflow.com/q/51118110

http://stackoverflow.com/q/51115442
has title: django get token and userid after successful registration
has comment: http://stackoverflow.com/comment/89217140
has comment: http://stackoverflow.com/comment/89218239
has comment: http://stackoverflow.com/comment/89217916
score: 0
has comment: http://stackoverflow.com/comment/89218652
answer count: 1
tagged with: django-rest-framework
has body: I'm building a server with custom registration pages using rest and django (latest versions). I have 3 fields required (username unique, phone_number unique, password) and 1 optional. Schema is: User sends phone-number to server, we check if user exists and if don't - ask for registration. In both cases I want to send token and user_id as answer if credentials are correct. The topics from 2016's are not working in my case, i think because of latest framework and python updates. That's what i have now in view.py: class RegisterView(APIView): renderer_classes = [renderers.JSONRenderer] def post(self, request): phone = request.POST.get('phone') username = request.POST.get('username') password = request.POST.get('password') name = request.POST.get('name', '') try: ChatUser.objects.create_user(username, phone, password, name) return Response({'success': True, 'token': """THERE SHOULD BE TOKEN"""}) except Exception: return Response({'success': False}) class CheckPhone(APIView): # works fine renderer_classes = [renderers.JSONRenderer] def post(self, request): phone_number = request.POST.get('phone_number') try: User.objects.get(phone=phone_number) return Response("""asks for login""") except User.DoesNotExist: return Response("""asks for registration""") models.py: class ChatUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, username, phone, password, name, **extra_fields): """Create and save a User with the given phone and password.""" if not phone: raise ValueError('The given phone must be set') if not username: raise ValueError('The given username must be set') username = self.model.normalize_username(username) user = self.model(phone=phone, username=username, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return username def create_user(self, username, phone, password, name, **extra_fields): """Create and save a regular User with the given ph…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89217808
tagged with: django
has comment: http://stackoverflow.com/comment/89217170
tagged with: python
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/51116334
accepted answer: http://stackoverflow.com/a/51116334
type: Question

http://stackoverflow.com/comment/89168856
type: Comment
type: QuestionComment
has text: ok, that clears it up... thanks
score: 0
comment on: http://stackoverflow.com/q/51089741

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/51077590
tags question: http://stackoverflow.com/q/51119368
tags question: http://stackoverflow.com/q/51140575
tags question: http://stackoverflow.com/q/51106292
tags question: http://stackoverflow.com/q/51138465
tags question: http://stackoverflow.com/q/51102615
tags question: http://stackoverflow.com/q/51039441
tags question: http://stackoverflow.com/q/51036402
tags question: http://stackoverflow.com/q/51058953
tags question: http://stackoverflow.com/q/51072427
tags question: http://stackoverflow.com/q/51020928

http://stackoverflow.com/comment/89115575
type: QuestionComment
comment on: http://stackoverflow.com/q/51062760
type: Comment
has text: What should happen if two `choice_text`s are the same (for different choices). If that can not happen, I would enforce that on the model level.
score: 0

http://stackoverflow.com/a/51024082
type: Answer
has comment: http://stackoverflow.com/comment/89041736
downvote count: 0
has comment: http://stackoverflow.com/comment/89040894
accepted answer of: http://stackoverflow.com/q/51023968
has body: You are dealing with a regression problem: predicting a price. So switching from KNeighborsClassifier to KNeighborsRegressor will solve this issue.
answers question: http://stackoverflow.com/q/51023968
has comment: http://stackoverflow.com/comment/89041634
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89041628
upvote count: 5

http://stackoverflow.com/comment/89218060
comment on: http://stackoverflow.com/q/51106254
type: QuestionComment
score: 0
type: Comment
has text: Maybe you can post process the output to round the number

http://stackoverflow.com/comment/89345572
type: Comment
has text: Also, you may want to code a method `inverse_transform()` to recover the values
comment on: http://stackoverflow.com/a/51164055
score: 1
type: AnswerComment

http://stackoverflow.com/q/51086323
has comment: http://stackoverflow.com/comment/89195520
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89187225
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/89177378
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89176608
tagged with: python
answer count: 0
tagged with: celery
has comment: http://stackoverflow.com/comment/89178489
has title: Argument error while running chord in Celery
type: Question
tagged with: chord
has body: Here's my directory structure: app |-- automate-scan.py |-- helpers | |-- __init__.py | |-- __init__.pyc | |-- tasks.py | `-- tasks.pyc |-- __init__.py `-- __init__.pyc Now here's what I am trying to run: atuomate_scan.py import os from configobj import ConfigObj from celery import Celery from celery.result import AsyncResult from kombu import Queue celapp=Celery(backend='redis://localhost:6379/0', broker='amqp://user:pass@localhost/my_vhost') CELERY_CONFIG = { 'CELERY_DEFAULT_QUEUE': 'default', 'CELERY_QUEUES': (Queue('initialScanning'),), 'CELERY_TASK_SERIALIZER': 'pickle', 'CELERY_ACCEPT_CONTENT': ['json','pickle'] } celapp.conf.update(**CELERY_CONFIG) config_file = '/home/myuser/config.cfg' config_obj = ConfigObj(config_file) repo_list_file = config_obj.get('files').get('repo_file') @celapp.task() def run_scan(repo): print repo os.system("git clone " + repo) repo_to_scan = repo.split('/')[1].split('.')[0] os.system("python /home/someuser/myscript.py file:///home/someuser/repo_collection/" + repo_to_scan + " --json --regex") @celapp.task() def final_task(): print "hakuna matata" repositories - in the below code is a list of strings tasks.py import os from configobj import ConfigObj from celery import Celery from celery.result import AsyncResult from kombu import Queue from celery import chord from helpers import tasks f = open('/home/someuser/repositories.lst') os.system("mkdir /home/someuser/repo_collection") repositories = f.read().splitlines() f.close() print repositories print "\n\n" created_task = (tasks.run_scan.subtask((repo)) for (repo) in repositories) finaltask = tasks.final_task.subtask() res = chord(created_task,queue='initialScanning')(finaltask) When I run automate-scan.py I get the following error: Traceback (most recent call last): File "app/automate-scan.py", line 20, in &lt;module&gt; res = chord(created_task,queue='initialScanning')(finaltask) File "/usr/local/lib/python2.7/dist-packages/celery/canvas.py", line 1189, in __call__ return self.app…

http://stackoverflow.com/a/51119889
accepted answer of: http://stackoverflow.com/q/51112373
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89438807
has comment: http://stackoverflow.com/comment/89232041
answers question: http://stackoverflow.com/q/51112373
type: Answer
has body: First, we want some object that stores the state of a particular session. We can just call this object Game. We'll maintain a mapping of discord.Users to Games. A User existing in this mapping means that they are playing the game. Some basics would look something like: from discord.ext import commands class Game: def __init__(self): self.points = 0 self.inventory = [] bot = commands.Bot('/') sessions = {} @bot.command(pass_context=True) async def play(ctx): if ctx.message.author.id in sessions: await bot.say("You're already playing") return sessions[ctx.message.author.id] = Game() await bot.say("Welcome to the game!") @bot.command(pass_context=True) async def quit(ctx): if ctx.message.author.id not in sessions: await bot.say("You're not playing the game") return del sessions[ctx.message.author.id] await bot.say("Game Over") @bot.command(pass_context=True) async def examine(ctx): session = sessions.get(ctx.message.author.id, None) if session is None: await bot.say("You're not playing the game") return session.inventory.append("A rock") await bot.say("You examined the rock and well, got a rock!") bot.run("TOKEN") Some things you could do to extend this: make use of checks and CommandErrors to avoid having to repeat the code for checking sessions; make sure that Games are pickleable, and write code for saving games using pickle; write a game that's more fun than collecting rocks.
has comment: http://stackoverflow.com/comment/89452278
has comment: http://stackoverflow.com/comment/89231978
has comment: http://stackoverflow.com/comment/89452505
has comment: http://stackoverflow.com/comment/89443871
has comment: http://stackoverflow.com/comment/89439163
score: 0

http://stackoverflow.com/a/51115125
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51114987
downvote count: 0
has body: for m in MyList : for k in SearchStrings : if k.lower() in m.lower() : print 'found', k, 'in', m, 'result', SearchStrings[k]
type: Answer

http://stackoverflow.com/comment/89137552
type: Comment
has text: Hi, Thank you for your help, but I still have 2 questions and could you share more advices? 1. Does Lua works well when in concurrency? I get some info that when Lua s cript is using, nothing else can run concurrently, is it right? 2. How about using watch()? I mean, pipe.watch(hkey); pipe.exists(hkey); pipe.unwatch(); then, the other parts. I tested it on my laptop, it works, but the bad news is when WATCH is used, every pipe.exists() cost time to connect and get the result from redis server. So, my question is: is there any risk to use WATCH in this way, not in a transaction?
comment on: http://stackoverflow.com/a/51061341
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89120267
type: Comment
has text: you don't need to assign anything to `raw_input` in your exception block
type: AnswerComment
comment on: http://stackoverflow.com/a/51065152
score: 0

http://stackoverflow.com/comment/89202804
score: 0
has text: multiline strings are no different from one line strings. Can you explain why triple quotes won't work? `print`ing it should give you a multiline paragraph just the way it was stored. It will only look different on the command line due to how \_\_repr\_\_ is implemented for strings
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51107411

http://stackoverflow.com/q/51124667
has comment: http://stackoverflow.com/comment/90194326
tagged with: http://stackoverflow.com/tag/r
score: 1
favorite count: 0
has title: Calculating the area and overlapping area of data points in ternary plot?
tagged with: geometry
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
type: Question
tagged with: ternary
downvote count: 0
has body: The data below illustrates flower part mass proportions of iris flower. The issue that I am struggling with is calculating the area of overlap and area of the data points in ternary plot. I thought of approaching this problem using geom_mean_ellipse thereafter finding the confidence ellipse of sunlight exposed yes or no. Then determining the % area which each ellipse occupies within the triangular plot and thereafter determining the % area of overlap between the two ellipses. I need guidance and help with coding % area and % area overlap and potential packages I could use. Sunlight Species Sepal.mass Petal.mass Pistil.mass Yes Iris 0.19 0.35 0.49 Yes Iris 0.26 0.31 0.42 Yes Iris 0.10 0.38 0.66 Yes Iris 0.52 0.20 0.28 Yes Iris 0.15 0.44 0.48 Yes Iris 0.27 0.30 0.43 Yes Iris 0.23 0.22 0.61 Yes Iris 0.30 0.13 0.57 Yes Iris 0.18 0.14 0.68 Yes Iris 0.25 0.23 0.52 Yes Iris 0.16 0.31 0.57 Yes Iris 0.13 0.30 0.57 Yes Iris 0.15 0.38 0.57 Yes Iris 0.10 0.30 0.60 Yes Iris 0.07 0.16 0.28 Yes Iris 0.13 0.15 0.73 Yes Iris 0.17 0.30 1.65 Yes Iris 0.16 0.20 0.64 Yes Iris 0.15 0.20 0.66 Yes Iris 0.12 0.18 0.71 Yes Iris 0.15 0.40 0.58 No Iris 0.16 0.15 0.69 No Iris 0.14 0.30 0.57 No Iris 0.39 0.22 0.40 No Iris 0.22 0.14 0.55 No Iris 0.24 0.10 0.65 No Iris 0.27 0.24 0.45 No Iris 0.28 0.18 0.54 No Iris 0.22 0.21 0.56 No Iris 0.18 0.18 0.65 No Iris 0.16 0.13 0.66 No Iris 0.23 0.22 0.66 No Iris 0.30 0.13 0.57 No Iris 0.18 0.14 0.68 No Iris 0.25 0.23 0.52 No Iris 0.16 0.31 0.57 No Iris 0.13 0.30 0.57 No Iris 0.15 0.38 0.57 No Iris 0.32 0.16 0.47 No Iris 0.31 0.20 0.49 No Iris 0.12 0.41 0.55 No Iris 0.23 0.41 0.37 Ternary plot of the above dataset of flower parts. ggtern(data=dat3,aes(x=Petal.mass,y=Sepal.mass,z=Pistil.mass,color=Sunlight))+ geom_point()+geom_mean_ellipse Ternary plot of flower parts:

http://stackoverflow.com/comment/89038188
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51022870
has text: Can you please post your CSV file and the expected output?

http://stackoverflow.com/q/51135944
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89256706
downvote count: 2
has body: I have an excel sheet and there is a column ID. In that column there are more than 100 000 IDs. I want to assign these IDs randomly to 10 parts; which will have 10 entries. For example. ID's: 2341, 2432, 2923.... These need to be randomly distributed to 10 parts which can have any name. Lets say the ten parts are A-J. So, random distribution means 2341 goes to C, 2923 goes to A and so on (randomly); all the 1 Lac ID's go randomly to A-J. And then I have work on it on Python. (Visualization and stuff) The parts (A-H) should be able to contain letters and numerals.
answer count: 1
has answer: http://stackoverflow.com/a/51136227
favorite count: 0
tagged with: python
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has title: Allocate given data randomly to 10 parts

http://stackoverflow.com/comment/89279716
comment on: http://stackoverflow.com/q/51147751
score: 0
type: Comment
type: QuestionComment
has text: Can you please post the relevant part of your model code, relevant migration file?

http://stackoverflow.com/comment/89199327
type: QuestionComment
comment on: http://stackoverflow.com/q/51105988
type: Comment
has text: I don't want to escape them. I want to inject things into the html code...
score: 0

http://stackoverflow.com/comment/89069434
score: 0
has text: Then you should give us more information on your data. We can only work with what you throw at us.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51038633

http://stackoverflow.com/q/51148385
score: 1
tagged with: tensorflow
type: Question
has title: Tensorboard Audio Summary Files Empty
answer count: 1
downvote count: 0
tagged with: keras
tagged with: tensorboard
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I'm trying to periodically add audio samples to Tensorboard, which are independent of the computation graph. I'm working in Keras, and have created a custom callback to log audio files at the end of each epoch. Everything seems to be working fine, except that the audio files are empty, that is, they have a length of zero and nothing plays. Below is a minimum viable example of the Callback which reproduces the problem. class TensorBoardAudio(Callback): def on_epoch_end(self, epoch, logs=None): writer = tf.summary.FileWriter(LOG_DIR) data, fs = sf.read('/path/to/wavfile.wav', dtype='float32') audio = tf.Summary.Audio(encoded_audio_string=data.tobytes(), content_type='audio/wav', sample_rate=fs, length_frames=len(data)) summary = tf.Summary(value=[tf.Summary.Value(tag='test', audio=audio)]) writer.add_summary(summary, epoch) writer.flush() writer.close() I can reproduce audio from the data.tobytes(), so I know there's data being passed in, I just can't see what I'm doing wrong.
has answer: http://stackoverflow.com/a/72565994

http://stackoverflow.com/q/51030552
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89079083
has body: Everything seems to be working fine when I am trying to turn a wav file into a dataset (csv file) When I attempt to FFT it, it seems to work fine with the exception of it being off by a factor of 6, is this something I ought to worry about? Furthermore another question I have is regarding a wav file, so I found the data inside and got ints out of them. They are 2 byte signed shorts, so I am aware that they have limits of -32767-32767 and are the amplitude. However I am confused on how do these convert into actual volume? Code import pyaudio import wave import time import sys import struct import csv # all files and stuffs need to contain their tags ('potatos.wav') def wavToData(wavName): stream = wave.open(wavName) num_channels = stream.getnchannels() sample_rate = stream.getframerate() sample_width = stream.getsampwidth() num_frames = stream.getnframes() raw_data = stream.readframes( num_frames ) # Returns byte data stream.close() total_samples = num_frames * num_channels if sample_width == 1: fmt = "%iB" % total_samples # read unsigned chars elif sample_width == 2: fmt = "%ih" % total_samples # read signed 2 byte shorts else: raise ValueError("Only supports 8 and 16 bit audio formats.") total_samples = num_frames * num_channels integer_data = struct.unpack(fmt, raw_data) # this is amplitude return integer_data, num_frames, sample_rate def dataToWav(wavName,data): # IMPORTANT hard coded standard values, refenced from the audiocheck.net files stream = wave.open(wavName,"wb") stream.setnchannels(1) stream.setframerate(44100) stream.setsampwidth(2) numFrames = len(data) stream.setnframes(numFrames) fmt = "%ih" % numFrames data = struct.pack(fmt,*data) #unpacks all stream.writeframes(data) def wavToCsv(wavName,csvName): with open(csvName, 'wb') as csvfile: #contain all data in 1 row # x = time (1 frame) # y = freq filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) #get data integer_data, num_frames, sample_rate = wavToData(wavName…
tagged with: audio
score: 1
type: Question
has title: Should I be worried about FFT being off by a factor of 6
downvote count: 0
tagged with: fft
favorite count: 0
has comment: http://stackoverflow.com/comment/89057044
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89207692
comment on: http://stackoverflow.com/q/51110161
score: 0
has text: Possible duplicate of [How do I change the string representation of a Python class?](https://stackoverflow.com/questions/4912852/how-do-i-change-the-string-representation-of-a-python-class)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/75467300
score: 0
answers question: http://stackoverflow.com/q/51107319
type: Answer
has body: type this in shell: py -m pip install -U pygame --user user is your cmd user.
has comment: http://stackoverflow.com/comment/133221016

http://stackoverflow.com/comment/89071226
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51039756
score: 1
has text: Are you sure it is python 3.6?

http://stackoverflow.com/comment/89154836
has text: is the data which is filtered out based on score?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51083286
type: Comment

http://stackoverflow.com/a/51162741
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89309101
upvote count: 2
has comment: http://stackoverflow.com/comment/89313418
answers question: http://stackoverflow.com/q/51162636
has comment: http://stackoverflow.com/comment/89309162
has body: There's likely no problem with your code, but rather a problem with IDLE. If you run the same code from the console, or from a different IDE like PyCharm or Spyder, it will work just fine. As of 3.7, IDLE internally handles all strings as UCS-2, an obsolete encoding that can only handle the first 65536 characters in Unicode.1 So, what happens when you try to pass it a string that has an "astral character", a character outside that range? Well, it depends on various details, but usually it's a UnicodeEncodeError like this one. Which means that if you have a client whose name includes, say, a character from the supplemental CJK range—which many Chinese last names do—or an Emoji, this line will raise that exception: print("I am the" + client.user.name) … as IDLE tries to take the print output and convert it to display on is tkinter output. To work around the problem, you need to do something to explicitly remove or substitute any astral characters before printing them: def clean_remove(s): return ''.join(c for c in s if ord(c) &lt; 65536) def clean_replace_question(s): return ''.join(c if ord(c) &lt; 65536 else '?' for c in s) def clean_replace_unicode(s): return ''.join(c if ord(c) &lt; 65536 else '\ufffd' for c in s) print("I am the" + clean_whichever(client.user.name)) You can write this a bit more efficiently, but it's unlikely to matter (displaying text in tkinter windows is much slower anyway), and hopefully this way is easy to understand. You can also monkeypatch Python with a custom print function that does this filtering before passing through to the builtin, or a custom replacement for sys.stdout that filters things for you. Or you can just not run your code in IDLE. 1. UCS-2 has been replaced by UTF-16, many years back in fact, but IDLE can't be updated until someone can fix the string-handling code interfacing with every supported GUI platform (mainly Windows) and every supported Tcl/Tk version, which hasn't happened yet.

http://stackoverflow.com/a/51133947
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51133892
has body: convert labelled_docs.append(templist + labels[i]) this line into labelled_docs.append(templist + [labels[i]]). This will concatenate two list instead of concatenation of one list and one int value.
accepted answer of: http://stackoverflow.com/q/51133892

http://stackoverflow.com/comment/89173130
comment on: http://stackoverflow.com/q/51092428
type: Comment
type: QuestionComment
has text: wait so your array only contains strings with 'a_' and 'b_' prefixes??
score: 0

http://stackoverflow.com/a/51249113
has body: @Daniel Hepper Thanks for the clean explanation.In the case of Python3.x the execfile is not supported. you can refer to https://stackoverflow.com/a/437857/1790603
answers question: http://stackoverflow.com/q/51102161
score: 0
type: Answer

http://stackoverflow.com/comment/89303267
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51159836
type: AnswerComment
has text: @AChampion Damn. I tried ["1", "2"] as well as ["0", "1", ... "99"], both are correct. But that was only a coincidence. You guys are right. Sorry. Thanks Gabriel, I see it now.

http://stackoverflow.com/q/51013977
has comment: http://stackoverflow.com/comment/89020700
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89022829
score: 0
has comment: http://stackoverflow.com/comment/89022932
has comment: http://stackoverflow.com/comment/89022772
has comment: http://stackoverflow.com/comment/89022686
has comment: http://stackoverflow.com/comment/89022788
tagged with: scoring
has title: python pandas -use WECO rule to score groupby and output groupby score
has body: So I have all th WECO rules I wrote and it works--on a column of data. But now I want to group by 'name' and then score the 'score' column. and my problem is using groupby and trying to output to new df2 -This will be for a many datasets with 5 - 40+ names -This is one of the rules: WECO_A = ["N"] UCL = .2 lastPoint=df.groupby('name').iloc[0]['score'] if lastPoint &gt; UCL: WECO_A = "Y" if WECO_A == "Y": df2['weco'] = df.groupby('name') + 'RULE_A' else: df2['weco'] = df.groupby('name') + 'OK' df: name score bob 0.2849 sue 0.1960 ken 0.8427 bob 0.2844 sue 0.2507 ken 0.9904 ...etc and I am looking for this df2: name weco bob RULE_A sue OK ken RULE_A OR even a single column, df2: weco bob RULE_A sue OK ken RULE_A -just an example not sure what real scores would be?? AND, thanks in advance as always..
answer count: 0
has comment: http://stackoverflow.com/comment/89022766
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89022646
type: Question

http://stackoverflow.com/q/51033964
has title: Maximizing space in a list
has body: So I want to see if there is a possible way for me to maximize space in a list. For example: lists = [3, 3, 3, 3, 3] Maximum Value = 4 #from user input Output = [3, 0, 4, 4, 4] Process in each step: Start: [3, 3, 3, 3, 3] #start [3, 3, 3, 2, 4] #takes 1 number from lists[3] and puts it in lists[4] so that that is equal to 4 [3, 3, 1, 4, 4] #takes 2 numbers from(since 4 - lists[3] = 2 lists[2] and puts it in lists[3] Finish:[3, 0, 1, 4, 4] #puts 3 numbers from lists[1] and puts them in lists[2](4 - lists[2] = 3) and now that there is a zero it should stop the program Basically, the code should start at the back and fill in space in each value going down the list until one of the values is equal to 4 or 0 or until it reaches the start of the list. 1 last thing: This should work with any list length and even if there are 0's after the last number. For example: list = [3, 3, 5, 2, 7, 2, 3, 0, 0, 0, 0, 4] MaximumValue = 4 Step 1: [3, 3, 5, 2, 7, 2, 3, 0, 0, 0, 0, 4] [3, 3, 5, 2, 7, 1, 4, 0, 0, 0, 0, 4] [3, 3, 5, 2, 4, 4, 4, 0, 0, 0, 0, 4] [3, 3, 3, 4, 4, 4, 4, 0, 0, 0, 0, 4] [3, 2, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4] Finish: [1, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4] #reached lists[0] so stop program
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51034072
tagged with: list
has comment: http://stackoverflow.com/comment/89060154
downvote count: 3
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/89060060
score: -3
favorite count: 0
has answer: http://stackoverflow.com/a/51034131
has comment: http://stackoverflow.com/comment/89060160
has comment: http://stackoverflow.com/comment/89060137

http://stackoverflow.com/comment/89168645
type: AnswerComment
has text: Yeah, I realised that and posted the answer :) thank you
comment on: http://stackoverflow.com/a/51044663
score: 0
type: Comment

http://stackoverflow.com/q/51133991
has answer: http://stackoverflow.com/a/51363283
accepted answer: http://stackoverflow.com/a/51363283
has title: Proxmoxer : how to create LXC container specifying disk size
type: Question
has body: I'm running version 5.2 of proxmox, and 1.0.2 of proxmoxer python library. Latest as of today. So far I didn't manage to create a LXC container specifying a disk size and will always default to 4G. I didn't find this option in Proxmox documentation... I am using : node.lxc.create(vmid=204, ostemplate='local:vztmpl/jessie-TM-v0.3.tar.gz', hostname='helloworld', storage='raid0', memory=2048, swap=2048, cores=2, password='secret', net0='name=eth0,bridge=vmbr0,ip=dhcp') Adding something like rootfs='raid0:204/vm-204-disk-1.raw,size=500G' will disable disk image creation and look for an already existing image. Anyway, I don't really know where to go next. Am I supposed to create a disk image before hand? I didn't find how to do this for LXC. No problems with qemu. Thanks for any help.
possible better answer: http://stackoverflow.com/a/51334058
score: 0
answer count: 2
tagged with: lxc
has answer: http://stackoverflow.com/a/51334058
tagged with: python
type: AnsweredQuestion
tagged with: proxmox

http://stackoverflow.com/a/51065519
downvote count: 0
has comment: http://stackoverflow.com/comment/125066559
has body: I'd use a Counter: from collections import Counter def get_all_subsequence(seq): return [seq[i:j] for i in range(len(seq)) for j in range(i + 2, len(seq) + 1)] input = ["ABCD", "ACD", "ADB"] counter = Counter() for entry in input: counter.update(get_all_subsequence(entry)) print(counter.most_common()) [('CD', 2), ('AB', 1), ('ABC', 1), ('ABCD', 1), ('BC', 1), ('BCD', 1), ('AC', 1), ('ACD', 1), ('AD', 1), ('ADB', 1), ('DB', 1)]
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51060627
score: 2

http://stackoverflow.com/a/51053923
accepted answer of: http://stackoverflow.com/q/51053911
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92246975
answers question: http://stackoverflow.com/q/51053911
has comment: http://stackoverflow.com/comment/89098792
has comment: http://stackoverflow.com/comment/110644505
score: 10
has body: You can do with max on level=0 matches.groupby(["FeatureID", "gene"]).count().max(level=0) If keep both level df.groupby(["FeatureID", "gene"]).count().sort_values().groupby(level=0).tail(1)
upvote count: 10

http://stackoverflow.com/comment/89141193
comment on: http://stackoverflow.com/a/51076150
score: 0
type: AnswerComment
has text: Hi @neverwalkaloner, it returns `page not found error`
type: Comment

autoformatting
tags question: http://stackoverflow.com/q/51130546
type: Tag
tag name: autoformatting

http://stackoverflow.com/comment/89252889
score: 1
has text: Can you please work on [minimal working code example](https://stackoverflow.com/help/mcve)? The one you provided is much to long to quickly understand and to try to find issue.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51134105

http://stackoverflow.com/comment/89057952
type: QuestionComment
comment on: http://stackoverflow.com/q/51032814
has text: data[data.CityLocation.str.startswith('Bang')]
score: 0
type: Comment

http://stackoverflow.com/a/51018581
answers question: http://stackoverflow.com/q/51018332
has comment: http://stackoverflow.com/comment/89032976
upvote count: 1
has body: 734094 / 365.25 = 2009.8398. That's a very suggestive number for a date that, from your example, I assume is 2010-11-18. It looks like your date information is expressed as a floating-point number, where the difference of 1.0 corresponds to one day: and, the reference date for the value 0.0 is January 1, 1 AD. You could try to write a function that counts from 01-01-1, or maybe you could find one in a library. Alternately, you could look at the converted value for a date you know, and work from there.
has comment: http://stackoverflow.com/comment/89031966
score: 1
accepted answer of: http://stackoverflow.com/q/51018332
has comment: http://stackoverflow.com/comment/89031848
has comment: http://stackoverflow.com/comment/89031297
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89033206
type: Answer

python-multithreading
tags question: http://stackoverflow.com/q/51123971
tags question: http://stackoverflow.com/q/51025433
tags question: http://stackoverflow.com/q/51151487
tags question: http://stackoverflow.com/q/51116129
tags question: http://stackoverflow.com/q/51049586
type: Tag
tags question: http://stackoverflow.com/q/51017468
tags question: http://stackoverflow.com/q/51117268
tags question: http://stackoverflow.com/q/51146279
tags question: http://stackoverflow.com/q/51140188
tag name: python-multithreading
tags question: http://stackoverflow.com/q/51158280
tags question: http://stackoverflow.com/q/51090555
tags question: http://stackoverflow.com/q/51038793

http://stackoverflow.com/comment/89264962
comment on: http://stackoverflow.com/q/51135419
type: Comment
type: QuestionComment
has text: I've re-run `python3 -mpip install -ve .` and it worked. Thanks!
score: 0

http://stackoverflow.com/q/51061113
tagged with: list
has comment: http://stackoverflow.com/comment/89112865
type: Question
has answer: http://stackoverflow.com/a/51061267
has answer: http://stackoverflow.com/a/51061283
has comment: http://stackoverflow.com/comment/89112342
has title: Summation from sub list
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51061400
has comment: http://stackoverflow.com/comment/89112955
has comment: http://stackoverflow.com/comment/89112371
tagged with: sublist
has body: If n = 4, m = 3, I have to select 4 elements (basically n elements) from a list from start and end. From below example lists are [17,12,10,2] and [2,11,20,8]. Then between these two lists I have to select the highest value element and after this the element has to be deleted from the original list. The above step has to be performed m times and take the summation of the highest value elements. A = [17,12,10,2,7,2,11,20,8], n = 4, m = 3 O/P: 20+17+12=49 I have written the following code. However, the code performance is not good and giving time out for larger list. Could you please help? A = [17,12,10,2,7,2,11,20,8] m = 3 n = 4 scoreSum = 0 count = 0 firstGrp = [] lastGrp = [] while(count&lt;m): firstGrp = A[:n] lastGrp = A[-n:] maxScore = max(max(firstGrp), max(lastGrp)) scoreSum = scoreSum + maxScore if(maxScore in firstGrp): A.remove(maxScore) else: ai = len(score) - 1 - score[::-1].index(maxScore) A.pop(ai) count = count + 1 firstGrp.clear() lastGrp.clear() print(scoreSum )
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89113153

http://stackoverflow.com/comment/89277021
type: QuestionComment
comment on: http://stackoverflow.com/q/51143858
has text: I know what your saying about loop. Just not there in knowledge yet on how to do it. I know I can make one list , have it sort it. Just went this direction and am not sure why it wouldn't work.
score: 0
type: Comment

http://stackoverflow.com/comment/89158194
comment on: http://stackoverflow.com/q/51077486
type: QuestionComment
type: Comment
has text: version of tensorflow is :1.3.0
score: 0

http://stackoverflow.com/a/51151549
downvote count: 0
answers question: http://stackoverflow.com/q/51145994
has comment: http://stackoverflow.com/comment/89286736
type: Answer
has body: I choose to use HTMLParser to parse HTML instead of preprocessing HTML and using ElementTree to parse HTML as XML.
upvote count: 1
score: 1

http://stackoverflow.com/a/51077390
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51077239
has body: You can use string slicing. Ex: import datetime s = 'TrackLog_20160315_123456.csv' print( datetime.datetime.strptime(s[9:17], '%Y%m%d') ) In your case: dst_exist_dates = [datetime.strptime(f[9:17], '%Y%m%d') for f in s3.list_files_as_list(s3_profile, src_path, recursive=True)] Output: 2016-03-15 00:00:00
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51077239
type: AcceptedAnswer

http://stackoverflow.com/q/51042870
score: 12
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/68656731
downvote count: 0
tagged with: spectrogram
favorite count: 0
has answer: http://stackoverflow.com/a/52756497
has title: Wrong spectrogram when using scipy.signal.spectrogram
answer count: 3
possible better answer: http://stackoverflow.com/a/68656731
tagged with: python
has comment: http://stackoverflow.com/comment/99897670
has answer: http://stackoverflow.com/a/51044443
has body: When I use the plt.specgram from matplotlib by using the following code, the spectrogram generated is correct import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile import numpy as np sample_rate, samples = wavfile.read('.\\Wav\\test.wav') Pxx, freqs, bins, im = plt.specgram(samples[:,1], NFFT=1024, Fs=44100, noverlap=900) However, if I generate the spectrogram by using the example code given by in the scipy page with the following code, I get something like this: import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile import numpy as np sample_rate, samples = wavfile.read('.\\Wav\\test.wav') frequencies, times, spectrogram = signal.spectrogram(samples[:,1],sample_rate,nfft=1024,noverlap=900, nperseg=1024) plt.pcolormesh(times, frequencies, spectrogram) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') To debug what's going on, I tried using the Pxx, freqs, bins, generated by the first method, and then use the second method to plot out the data: plt.pcolormesh(bins, freqs, Pxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') The graph generated is almost the same as the graph generated by the second method. So, it seems there is no problem with the scipy.signal.spectrogram after all. The problem is the way that we plot the graph. I wonder if plt.pcolormesh is the correct way to plot the spectrogram despite the fact that this method is suggested in the scipy document A similar question has been asked here, but there's no solution to the question yet.
accepted answer: http://stackoverflow.com/a/51044443
tagged with: audio
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48598994
tagged with: scipy

http://stackoverflow.com/comment/89395558
type: Comment
comment on: http://stackoverflow.com/q/51134155
has text: It is better to use python 3.5 version because python 3.6 not supported for windows iis.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51084036
downvote count: 0
has comment: http://stackoverflow.com/comment/89156948
has body: I read a sentence in the official handbook of Python. If a lambda or def defined within a function is nested inside a loop, and the >nested function references an enclosing scope variable that is changed by that >loop, all functions generated within the loop will have the same value—the value >the referenced variable had in the last loop iteration. In such cases, you must >still use defaults to save the variable’s current value instead. As for the script: def makeActions(): acts=[] for i in range(5): acts.append(lambda x: i**x) return acts acts=makeActions() print(acts) I know how the problem looks like and how to solve it. But I just can not understand reason. please have a look at my interpretations: def makeActions(): acts=[] for i in range(5): acts.append(lambda x: i**x) #step2-step6: each lambda would be stored #in the list, however, with its own "i" return acts acts=makeActions() #step1: when the function is called, the list would be #created. And lambda would be called as well. print(acts) My point is that in each iteration, each lambda would be called even if the parameter x is not given. Thus, in the list "acts", each element (namely each lambda) has different "i". I know I am wrong, but could you tell me why? Thx!
type: Question
has answer: http://stackoverflow.com/a/51084148
has comment: http://stackoverflow.com/comment/89156560
has answer: http://stackoverflow.com/a/51084600
upvote count: 3
has comment: http://stackoverflow.com/comment/89156647
has comment: http://stackoverflow.com/comment/89156507
answer count: 2
has comment: http://stackoverflow.com/comment/89156588
has comment: http://stackoverflow.com/comment/89158085
has comment: http://stackoverflow.com/comment/89158385
has comment: http://stackoverflow.com/comment/89157952
has comment: http://stackoverflow.com/comment/89157070
favorite count: 0
has title: Scope Variable with a Loop
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89156830
has comment: http://stackoverflow.com/comment/89157395
has comment: http://stackoverflow.com/comment/89156781
tagged with: python
has comment: http://stackoverflow.com/comment/89156692
has comment: http://stackoverflow.com/comment/89156643
has comment: http://stackoverflow.com/comment/89156891
score: 3
has comment: http://stackoverflow.com/comment/89157277

http://stackoverflow.com/q/51162949
answer count: 0
type: UnansweredQuestion
tagged with: pip
upvote count: 1
tagged with: python
type: Question
has body: I am trying to install a robotframework library called ImageHorizonLibrary. However, I am running into an issue. I am trying to install it using pip in the jython environment: /Users/nimam/jython2.7.0/Lib/site-packages I do the following: sudo -H pip install robotframework-imagehorizonlibrary And I get the following error: Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle, invalid path: __pyclasspath__/pip/_vendor/certifi/cacert.pem If I try to install the library without sudo, i get the following error: Exception: Traceback (most recent call last): File "__pyclasspath__/pip/_internal/basecommand$py.class", line 228, in main File "__pyclasspath__/pip/_internal/commands/install$py.class", line 291, in run File "__pyclasspath__/pip/_internal/commands/install$py.class", line 291, in run File "__pyclasspath__/pip/_internal/resolve$py.class", line 102, in resolve File "__pyclasspath__/pip/_internal/resolve$py.class", line 102, in resolve File "__pyclasspath__/pip/_internal/resolve$py.class", line 257, in _resolve_one File "__pyclasspath__/pip/_internal/resolve$py.class", line 208, in _get_abstract_dist_for File "__pyclasspath__/pip/_internal/operations/prepare$py.class", line 245, in prepare_linked_requirement File "__pyclasspath__/pip/_internal/req/req_install$py.class", line 307, in populate_link File "__pyclasspath__/pip/_internal/index$py.class", line 484, in find_requirement File "__pyclasspath__/pip/_internal/index$py.class", line 442, in find_all_candidates File "__pyclasspath__/pip/_internal/index$py.class", line 587, in _get_pages File "__pyclasspath__/pip/_internal/index$py.class", line 705, in _get_page File "__pyclasspath__/pip/_internal/index$py.class", line 810, in get_page File "__pyclasspath__/pip/_internal/index$py.class", line 810, in get_page File "__pyclasspath__/pip/_vendor/requests/sessions$py.class", line 521, in get File "__pyclasspath__/pip/_internal/download$py.class", line 397, in request…
tagged with: jython
has title: Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle
has comment: http://stackoverflow.com/comment/91599466
has comment: http://stackoverflow.com/comment/91682894
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/94295571

http://stackoverflow.com/a/51032629
has body: You can use the ".quantile" method : quintiles = df'AAPL','NFLX','INTC'.quantile(q=[0.2,0.4,0.6,0.8]) quintiles = quintiles.to_dict()
has comment: http://stackoverflow.com/comment/89057762
type: Answer
answers question: http://stackoverflow.com/q/51032552
score: 0

http://stackoverflow.com/comment/89154569
comment on: http://stackoverflow.com/a/51082968
type: Comment
score: 0
type: AnswerComment
has text: As I said above, your initial data doesn't make sense -- you've excluded that user from the queryset.

http://stackoverflow.com/a/51065834
score: 1
accepted answer of: http://stackoverflow.com/q/51065473
upvote count: 1
has comment: http://stackoverflow.com/comment/89123051
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51065473
has body: Here is sample code you can use: from dateutil.parser import parse from datetime import datetime, timedelta data = [ ("2014/01/01 09:16:00",6365.2001953125,6369.89990234375,6355,6355,0), ("2014/01/01 09:17:00",6355.64990234375,6359.9501953125,6355.5498046875,6359.5498046875,0), ("2014/01/01 09:20:00",6359,6359,6355.64990234375,6356.5,0), ] def insert_into_db(date, open, high, low, close, zero): print('inserting {} {} {} {} {} {}'.format(date, open, high, low, close, zero)) prev_date = None for date, open, high, low, close, zero in data: date = parse(date) if prev_date is not None and date - prev_date &gt; timedelta(minutes=1): for i in reversed(range((date - prev_date).seconds // 60 - 1)): date_between = date - timedelta(minutes=1 * i + 1) insert_into_db(date_between, open, high, low, close, zero) insert_into_db(date, open, high, low, close, zero) prev_date = date The output is: inserting 2014-01-01 09:16:00 6365.2001953125 6369.89990234375 6355 6355 0 inserting 2014-01-01 09:17:00 6355.64990234375 6359.9501953125 6355.5498046875 6359.5498046875 0 inserting 2014-01-01 09:18:00 6358.9501953125 6359.4501953125 6357.5498046875 6359 0 inserting 2014-01-01 09:19:00 6358.9501953125 6359.4501953125 6357.5498046875 6359 0 inserting 2014-01-01 09:20:00 6359 6359 6355.64990234375 6356.5 0 But you should make sure start and end minutes present (or adapt the code). Update: fixed case if multiple minutes missing
type: Answer
has comment: http://stackoverflow.com/comment/89122018
downvote count: 0
has comment: http://stackoverflow.com/comment/89122807
has comment: http://stackoverflow.com/comment/89123357
has comment: http://stackoverflow.com/comment/89122406
has comment: http://stackoverflow.com/comment/89122536

missing-data
tags question: http://stackoverflow.com/q/51151852
tags question: http://stackoverflow.com/q/51044411
type: Tag
tags question: http://stackoverflow.com/q/51101891
tag name: missing-data

http://stackoverflow.com/q/51068498
has comment: http://stackoverflow.com/comment/89127539
has comment: http://stackoverflow.com/comment/89128439
has body: I do not understand why I am receiving the error listed in the title, the value that I am intending to return is the number 30 import csv import os import pandas as pd os.chdir('C:\\Users\\khalha\\Desktop\\RealExcel') filename = 'sales.csv' Sales = pd.read_csv('sales.csv') iFlowStatus = Sales[Sales['Product'].str.contains('iFlow')]['Status'] print(iFlowStatus)
has comment: http://stackoverflow.com/comment/89128410
has comment: http://stackoverflow.com/comment/89127104
answer count: 2
has comment: http://stackoverflow.com/comment/89127592
upvote count: 35
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/89127678
has answer: http://stackoverflow.com/a/51969304
favorite count: 0
has comment: http://stackoverflow.com/comment/89127501
score: 35
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/60571905
has comment: http://stackoverflow.com/comment/89127492
tagged with: python
has answer: http://stackoverflow.com/a/60571905
has comment: http://stackoverflow.com/comment/89127225
has title: ValueError: cannot index with vector containing NA / NaN values
linked to: http://stackoverflow.com/q/28311655
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51969304
tagged with: excel
type: Question

http://stackoverflow.com/a/51072645
accepted answer of: http://stackoverflow.com/q/51072613
has comment: http://stackoverflow.com/comment/89134999
has comment: http://stackoverflow.com/comment/89134988
type: Answer
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/51072613
has body: Press enter once after defining your function (that is, enter one blank line). Essentially, this lets Python know that you are done defining your function. Once you see &gt;&gt;&gt; again, you can call your function. See the picture for how it should look when done right:
downvote count: 0
has comment: http://stackoverflow.com/comment/89135009
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89135046

http://stackoverflow.com/a/51162472
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51162397
score: 2
upvote count: 2
has body: I would create a dictionary for a little bit of hierarchy. teams = {"home": home, "away": away} This way you could reference them with the same variable, but they maintain their distinctiveness. print(teams["home"] + " vs. " + teams["away"])

http://stackoverflow.com/a/51015619
has body: I think you need lookup here df1.applymap(lambda x : df2.lookup([x[0]],[x[1]])[0]) Out[289]: M1 M2 M3 0 -1.0 2.5 2.0 1 8.0 5.5 5.0
type: Answer
has comment: http://stackoverflow.com/comment/89027204
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89315461
has comment: http://stackoverflow.com/comment/89042250
has comment: http://stackoverflow.com/comment/89042264
downvote count: 0
answers question: http://stackoverflow.com/q/51015583
has comment: http://stackoverflow.com/comment/89025208

http://stackoverflow.com/a/51081454
has comment: http://stackoverflow.com/comment/89151693
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89151747
has comment: http://stackoverflow.com/comment/89151608
has body: You have a list of dicts. You want to iterate over the list as you are doing, but you don't want to iterate over each dict itself; you just want to check its currency key. So: for curr in result_bal_qrp: if curr['currency'] == 'AUD': print(curr['balance']) Note, if you're going to be iterating over this list multiple times to find different currencies, it may be worth converting it to a simple dict of currency to balance: curr_dict = {d['currency']: d['balance'] for d in result_bal_qrp} and now you can do curr_dict['AUD'] to get the Australian balance.
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/51081291

http://stackoverflow.com/comment/89141961
type: AnswerComment
has text: @changjc On stackOverflow questions are considered solved when they have an accepted answer. This shows other people all is well with the question and allows them to move to unaswered ones. So consider marking this as an accepted answer if it solved your problem (tick the green mark). Also consider doing this for your previous questions
score: 0
comment on: http://stackoverflow.com/a/51063413
type: Comment

http://stackoverflow.com/q/51160386
has comment: http://stackoverflow.com/comment/89304850
has comment: http://stackoverflow.com/comment/89304695
favorite count: 0
has answer: http://stackoverflow.com/a/51160697
has comment: http://stackoverflow.com/comment/89304899
has comment: http://stackoverflow.com/comment/89304775
tagged with: tensor
tagged with: pytorch
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89305080
downvote count: 1
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/89304561
has comment: http://stackoverflow.com/comment/89304748
type: Question
has comment: http://stackoverflow.com/comment/89304991
has comment: http://stackoverflow.com/comment/89304633
has comment: http://stackoverflow.com/comment/89304773
has comment: http://stackoverflow.com/comment/89304789
has comment: http://stackoverflow.com/comment/89304931
has comment: http://stackoverflow.com/comment/89305097
has comment: http://stackoverflow.com/comment/89304643
has comment: http://stackoverflow.com/comment/89304827
has comment: http://stackoverflow.com/comment/89304800
has comment: http://stackoverflow.com/comment/89304921
has title: Unable to create a tensor using torch.Tensor
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/89304866
has comment: http://stackoverflow.com/comment/89304545
linked to: http://stackoverflow.com/q/51129043
has body: i was trying to create a tensor as below. import torch t = torch.tensor(2,3) i got the following error. TypeError Traceback (most recent call last) in () ----> 1 a=torch.tensor(2,3) TypeError: tensor() takes 1 positional argument but 2 were given so, i tried the following import torch t = torch.Tensor(2,3) # No error while creating the tensor # When i print i get an error print(t) i get the following error RuntimeError Traceback (most recent call last) in () ----> 1 print(a) D:\softwares\anaconda\lib\site-packages\torch\tensor.py in repr(self) 55 # characters to replace unicode characters with. 56 if sys.version_info > (3,): ---> 57 return torch._tensor_str._str(self) 58 else: 59 if hasattr(sys.stdout, 'encoding'): D:\softwares\anaconda\lib\site-packages\torch_tensor_str.py in _str(self) 216 suffix = ', dtype=' + str(self.dtype) + suffix 217 --> 218 fmt, scale, sz = _number_format(self) 219 if scale != 1: 220 prefix = prefix + SCALE_FORMAT.format(scale) + ' ' * indent D:\softwares\anaconda\lib\site-packages\torch_tensor_str.py in _number_format(tensor, min_sz) 94 # TODO: use fmod? 95 for value in tensor: ---> 96 if value != math.ceil(value.item()): 97 int_mode = False 98 break RuntimeError: Overflow when unpacking long But, according to This SO Post, he was able to create a tensor. Am i missing something here. Also, why was i able to create a tensor with Tensor(capital T) and not with tensor(small t)
answer count: 1
has comment: http://stackoverflow.com/comment/89304592

http://stackoverflow.com/comment/89206654
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51109491
has text: No, the encoding is standard (AFAIK); the file contains only numbers and the letters `Ti` and `O`.

http://stackoverflow.com/a/51094276
has comment: http://stackoverflow.com/comment/89231155
has comment: http://stackoverflow.com/comment/89180170
accepted answer of: http://stackoverflow.com/q/51091547
answers question: http://stackoverflow.com/q/51091547
score: 0
has comment: http://stackoverflow.com/comment/89181009
has comment: http://stackoverflow.com/comment/89180905
type: AcceptedAnswer
has body: I am unable to do the same with cx_freeze, and my code works perfectly without the .exe. I have tried a few things on the internet, to solve the issue but in vain. But, if you really want to make a .exe, one of the best options out there is pyinstaller. I use it all the time. To install: sudo -H pip3 install pyinstaller To use: pyinstaller test_file.py After that is done, go to the "dist" directory and enter the folder named after your project. In there, there will be quite a lot of files. But, there will be one .exe file, the one that you need. So, click on it to run. If you want to input the address of a file don't use an entry, use the following (it looks good, and there will be no errors): from tkinter import filedialog as fd filename = fd.askopenfilename() if filename: print (filename) Hope this helps.
type: Answer

http://stackoverflow.com/q/51025752
type: AnsweredQuestion
score: 7
has answer: http://stackoverflow.com/a/51025986
upvote count: 7
type: Question
tagged with: duplicates
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51025986
possible better answer: http://stackoverflow.com/a/51025932
has body: I have a data frame like this and I'm trying reshape my data frame using Pivot from Pandas in a way that I can keep some values from the original rows while making the duplicates row into columns and renaming them. Sometimes I have rows with 5 duplicates I have been trying, but I don't get it. import pandas as pd df = pd.read_csv("C:dummy") df = df.pivot(index=["ID"], columns=["Zone","PTC"], values=["Zone","PTC"]) # Rename columns and reset the index. df.columns = [["PTC{}","Zone{}"],.format(c) for c in df.columns] df.reset_index(inplace=True) # Drop duplicates df.drop(["PTC","Zone"], axis=1, inplace=True) Input ID Agent OV Zone Value PTC 1 10 26 M1 10 100 2 26.5 8 M2 50 95 2 26.5 8 M1 6 5 3 4.5 6 M3 4 40 3 4.5 6 M4 6 60 4 1.2 0.8 M1 8 100 5 2 0.4 M1 6 10 5 2 0.4 M2 41 86 5 2 0.4 M4 2 4 Output ID Agent OV Zone1 Value1 PTC1 Zone2 Value2 PTC2 Zone3 Value3 PTC3 1 10 26 M_1 10 100 0 0 0 0 0 0 2 26.5 8 M_2 50 95 M_1 6 5 0 0 0 3 4.5 6 M_3 4 40 M_4 6 60 0 0 0 4 1.2 0.8 M_1 8 100 0 0 0 0 0 0 5 2 0.4 M_1 6 10 M_2 41 86 M_4 2 4
downvote count: 0
has answer: http://stackoverflow.com/a/51025932
favorite count: 0
has title: Pivot duplicates rows into new columns Pandas
tagged with: python
tagged with: merge

http://stackoverflow.com/q/51078314
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89145699
tagged with: python
has answer: http://stackoverflow.com/a/53212071
accepted answer: http://stackoverflow.com/a/53212071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89146479
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/93312255
has title: What happened internally during dict unpacking?
tagged with: iterable-unpacking
has comment: http://stackoverflow.com/comment/89146076
has comment: http://stackoverflow.com/comment/89145827
has body: I'm trying to figure out what methods are called when a dict is unpacked, so that I can customize the process? I suppose the following hack would have shown me the methods called during any method access of Dict instances: class Dict(dict): def __getattribute__(self, name): print(name) return super().__getattribute__(name) But the following session shows that no method is called to perform dict unpacking? In [1]: d = Dict(a=1) __class__ __class__ In [2]: {**d} Out[2]: {'a': 1} So what is actually happening here? How can I customize the unpacking process? Edit I don't think the question is a duplicate of the other one. Even implementing all the special methods mentioned in answers of that question, no of them are called during dict unpacking. In [66]: class Dict(dict): ...: def __getattribute__(self, name): ...: print(name) ...: return super().__getattribute__(name) ...: def keys(self): ...: print("hello") ...: return super().keys() ...: def __getitem__(self, key): ...: print("hello") ...: return super().__getitem__(key) ...: def __len__(self): ...: print("hello") ...: return super().__len__() ...: def __iter__(self): ...: print("hello") ...: return super().__iter__() ...: In [67]: d = Dict(a=1) __class__ __class__ In [68]: {**d} Out[68]: {'a': 1} You can see no print line is called whatsoever. So my question remains unanswered. FWIW, the python version is Python 3.6.5.
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/8601268

http://stackoverflow.com/a/51133401
upvote count: 2
has comment: http://stackoverflow.com/comment/89262427
has comment: http://stackoverflow.com/comment/89261936
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51124015
has body: First of all, optimizing the mean of the differences is the same as optimizing the sum of the differences. If you model you problem as directed graph, this can be solved: Let your lists be A, B, C. Every entry of your lists is a vertex of the graph v_ai where a is the list and i the index. For every index i in A, j in B, add an edge v_ai -&gt; v_bj with weigth abs(A(i) - B(j)) For every index i in B, j in C, add an edge v_bi -&gt; v_cj with weigth abs(B(i) - C(j)) For every index i in C, j in A, add an edge v_ci -&gt; v_aj with weigth abs(C(i) - A(j)) What you are looking for now is the minimum cycle in this graph. Use this answer for an O(n^3) algorithm. (a modified Floyd-Warshall algorithm)
has comment: http://stackoverflow.com/comment/89262388
score: 2
has comment: http://stackoverflow.com/comment/89262647

soundcard
tags question: http://stackoverflow.com/q/51123730
tag name: soundcard
type: Tag

http://stackoverflow.com/comment/89243651
has text: Yes I checked it. I tried the things said there, but it didn't work. I tried 'pip install ez_setup', and it seemed to work, but then I got an error while setting up pyzmq.
comment on: http://stackoverflow.com/q/51101181
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/126384032
comment on: http://stackoverflow.com/a/51161398
has text: This ruins boundaries.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51091056
type: Answer
score: 3
has body: Use cProfile.runctx: def foo(): def bar(): # do something here return 1 cProfile.runctx('bar()', None, locals=locals())
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51029366
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51029366

http://stackoverflow.com/comment/89073101
type: QuestionComment
has text: Don't iterate through each line of the file, as you will overwrite `tweet` each time. You should be able to open it as you are (using `with open("path/to/file", "r") as f`), and then use `tweets = json.loads(f)`. `tweets` will then be a Python dictionary, so you can find key:value pairs in it as you would normally with a dictionary.
type: Comment
comment on: http://stackoverflow.com/q/51040988
score: 2

http://stackoverflow.com/q/51045305
score: 4
has answer: http://stackoverflow.com/a/51045384
accepted answer: http://stackoverflow.com/a/51045384
has title: Numpy indexing: first (varying) number of elements from each row in 2d array
has body: (short version of my question: In numpy, is there an elegant way of emulating tf.sequence_mask from tensorflow?) I have a 2d array a (each row represents a sequence of different length). Next, there is a 1d array b (representing sequence lengths). Is there an elegant way to get a (flattened) array that would contain only such elements of a that belong to the sequences as specified by their length b: a = np.array([ [1, 2, 3, 2, 1], # I want just [:3] from this row [4, 5, 5, 5, 1], # [:2] from this row [6, 7, 8, 9, 0] # [:4] from this row ]) b = np.array([3,2,4]) # 3 elements from the 1st row, 2 from the 2nd, 4 from the 4th row the desired result: [1, 2, 3, 4, 5, 6, 7, 8, 9] By elegant way I mean something that avoids loops.
tagged with: python
favorite count: 0
downvote count: 0
upvote count: 4
tagged with: vectorization
type: AnsweredQuestion
type: Question
tagged with: numpy
answer count: 1

http://stackoverflow.com/comment/89288848
comment on: http://stackoverflow.com/a/51144345
type: AnswerComment
has text: syntonym I have been talking to Bryan Van de Ven @bryevdv on Gitter. He proposed a solution which worked for me with vbar_stack itself. you are correct with vbar it might have been easier.
score: 0
type: Comment

http://stackoverflow.com/comment/89194827
comment on: http://stackoverflow.com/q/51103616
type: QuestionComment
has text: @kosnik Yes, that works superbly thank you but only for one game result in the JSON. How can I loop through and obtain all match IDs for all games in the JSON feed please?
score: 0
type: Comment

xpath
tags question: http://stackoverflow.com/q/51044182
tags question: http://stackoverflow.com/q/51106207
tags question: http://stackoverflow.com/q/51149507
tag name: xpath
tags question: http://stackoverflow.com/q/51018483
tags question: http://stackoverflow.com/q/51119896
tags question: http://stackoverflow.com/q/51129628
tags question: http://stackoverflow.com/q/51049546
tags question: http://stackoverflow.com/q/51133132
tags question: http://stackoverflow.com/q/51050262
tags question: http://stackoverflow.com/q/51052422
tags question: http://stackoverflow.com/q/51159965
tags question: http://stackoverflow.com/q/51040835
tags question: http://stackoverflow.com/q/51076102
tags question: http://stackoverflow.com/q/51030767
type: Tag
tags question: http://stackoverflow.com/q/51052735
tags question: http://stackoverflow.com/q/51011754
tags question: http://stackoverflow.com/q/51042841
tags question: http://stackoverflow.com/q/51164890
tags question: http://stackoverflow.com/q/51160246
tags question: http://stackoverflow.com/q/51117082

http://stackoverflow.com/comment/89089137
score: 4
type: Comment
type: QuestionComment
has text: Don't post images, post text
comment on: http://stackoverflow.com/q/51049005

http://stackoverflow.com/q/51099630
type: Question
has comment: http://stackoverflow.com/comment/89194909
has comment: http://stackoverflow.com/comment/89205033
has body: A few months ago I wrote this skeleton package for linking a C library to Python using NumPy and Cython. When I created it compilation worked fine and I was able to use the C code from Python. However it now seems that my Python, Cython, or NumPy versions have changed in a way that the package won't compile anymore. Was there an API change in one of these packages that I'm not aware of? My .pxd header file isn't found and I get a number of compilation errors regarding the use of with nogil, such as: Error compiling Cython file: ------------------------------------------------------------ ... cdef long total cdef long n = x.shape[0] # If we want to use "nogil", we have to use "x.data", not "x". with nogil: total = sum_array(x.data, n) ^ ------------------------------------------------------------ src/cython_wrapper.pyx:32:25: Coercion from Python not allowed without the GIL But importantly these errors don't occur with the previous versions of Cython (0.27.1) and NumPy (1.13.3). Here are the steps to reproduce this: Old Environment virtualenv -p python3.6 old cd old source bin/activate pip install cython==0.27.1 numpy==1.13.3 git clone https://github.com/GjjvdBurg/NumPy_C_Extension cd NumPy_C_Extension rm src/cython_wrapper.c python setup.py build_ext -i # Compilation proceeds without errors New Environment virtualenv -p python3.6 new cd new source bin/activate pip install cython==0.28.3 numpy==1.14.5 git clone https://github.com/GjjvdBurg/NumPy_C_Extension cd NumPy_C_Extension rm src/cython_wrapper.c python setup.py build_ext -i # Compilation fails Any help would be greatly appreciated!
tagged with: numpy
has comment: http://stackoverflow.com/comment/89202989
tagged with: cythonize
has comment: http://stackoverflow.com/comment/89190080
downvote count: 0
has comment: http://stackoverflow.com/comment/89191792
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Cython Numpy Extension compilation fails with newer versions
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/89187156
tagged with: cython
upvote count: 1

http://stackoverflow.com/comment/109602906
has text: As someone pointed out on another thread, if you find yourself going to this much trouble then it's probably better to just use a normal class...
type: Comment
score: 1
comment on: http://stackoverflow.com/a/61480946
type: AnswerComment

http://stackoverflow.com/comment/89272846
comment on: http://stackoverflow.com/a/51014814
score: 0
type: AnswerComment
type: Comment
has text: @AdrianC Yes that's what a hash general is. But for the custom implementation `__hash__` in Python you can return really anything. Whether it makes sense is up to you. Hash collisions can always happen [even for sophisticated algorithms](https://arstechnica.com/information-technology/2017/02/watershed-sha1-collision-just-broke-the-webkit-repository-others-may-follow). The point of `__eq__` is to really distinguish objects (even, or especially, for hash collisions). This is what e.g. `dict` or `set` check when the hashes are the same. They want to assess whether the objects are really the same.

http://stackoverflow.com/comment/89188930
type: QuestionComment
has text: @fhdrsdg Thanks, that did it! It's quite simple, intuitively I thought I needed to `pack` the GUI to update it, as I've seen before in other frameworks in similar ways. And using `self.pack()` did work, the image showed up! It's probably though because the exception it caused hindered garbage collection...
comment on: http://stackoverflow.com/q/51097419
score: 0
type: Comment

http://stackoverflow.com/comment/89030330
comment on: http://stackoverflow.com/q/51018628
score: 0
has text: Why would you want to fill in an empty dataframe instead of creating a new one via `read_csv` ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/103524984
type: AnswerComment
type: Comment
has text: @SamYu If it returns after a timeout, that still means you will only get as many bytes as were received. A `bytearray` of length 24 initially contains 24 null bytes. If `readinto` reads less, the remaining bytes just won't be overwritten.
comment on: http://stackoverflow.com/a/51165187
score: 0

http://stackoverflow.com/a/51013269
score: 1
downvote count: 0
type: Answer
has body: Your direct_manager field needs to be a relationship, not a text field. This is a recursive relationship, where an instance of Hierarchy points to another instance which is its manager. So: direct_manager = models.ForeignKey('self', related_name='direct_reports') Now, given an instance of Hierarchy which is a manager, you can get all associates via the reverse relation: associates = my_manager.direct_reports.all()
upvote count: 1
answers question: http://stackoverflow.com/q/51013028

http://stackoverflow.com/a/51118570
has comment: http://stackoverflow.com/comment/89224631
answers question: http://stackoverflow.com/q/51118195
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/98404489
has body: For the decision rules of the nodes using the iris dataset: from sklearn.datasets import load_iris from sklearn import tree import graphviz iris = load_iris() clf = tree.DecisionTreeClassifier() clf = clf.fit(iris.data, iris.target) dot_data = tree.export_graphviz(clf, out_file=None, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) #this will create an iris.pdf file with the rule path graph.render("iris") For sample based paths use: import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0) estimator.fit(X_train, y_train) # The decision estimator has an attribute called tree_ which stores the entire # tree structure and allows access to low level attributes. The binary tree # tree_ is represented as a number of parallel arrays. The i-th element of each # array holds information about the node `i`. Node 0 is the tree's root. NOTE: # Some of the arrays only apply to either leaves or split nodes, resp. In this # case the values of nodes of the other type are arbitrary! # # Among those arrays, we have: # - left_child, id of the left child of the node # - right_child, id of the right child of the node # - feature, feature used for splitting the node # - threshold, threshold value at the node n_nodes = estimator.tree_.node_count children_left = estimator.tree_.children_left children_right = estimator.tree_.children_right feature = estimator.tree_.feature threshold = estimator.tree_.threshold # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes, dtype=np.int64) is_leaves …
downvote count: 1
upvote count: 9

http://stackoverflow.com/comment/89294816
has text: You have `a.txt` and open `text.txt` file to read?! Can you please clear your question?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51154851

http://stackoverflow.com/comment/89098030
type: Comment
type: QuestionComment
has text: Do you need to use the index at all? Or do you simply want to iterate through each row one after the other?
comment on: http://stackoverflow.com/q/51053301
score: 0

http://stackoverflow.com/a/51065155
upvote count: 2
answers question: http://stackoverflow.com/q/51064959
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51064959
has body: You can, but generally, don't. I would say be careful with exec. But other than that, there is not much stopping you really from doing this &gt;&gt;&gt; class MyClass: ... def __init__(self): ... exec('MyClass.foo = lambda self, x: x*x') ... &gt;&gt;&gt; c = MyClass() &gt;&gt;&gt; c.foo(3) 9 ALTHOUGH, my suggestion is that you do not do this since it is highly impractical and there is no convention for it.
type: Answer
score: 2

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/51033429
tags question: http://stackoverflow.com/q/51159849
tags question: http://stackoverflow.com/q/51015240
tags question: http://stackoverflow.com/q/51039202
tag name: c
type: Tag
tags question: http://stackoverflow.com/q/51029111
tags question: http://stackoverflow.com/q/51148129
tags question: http://stackoverflow.com/q/51110318
tags question: http://stackoverflow.com/q/51037769
tags question: http://stackoverflow.com/q/51160830
tags question: http://stackoverflow.com/q/51100805
tags question: http://stackoverflow.com/q/51156221
tags question: http://stackoverflow.com/q/51023663
tags question: http://stackoverflow.com/q/51164980
tags question: http://stackoverflow.com/q/51044122

http://stackoverflow.com/comment/89061202
comment on: http://stackoverflow.com/q/51034526
type: QuestionComment
has text: I realize that the mark_safe function that gets returned won't put the the items into the correct format but I'll figure that out once I learned how to change the list tags to table tags.
score: 0
type: Comment

http://stackoverflow.com/comment/89087129
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51047932
has text: Welcome to Stack Overflow! Please, read the [ask] page and update your question.

http://stackoverflow.com/q/51015259
tagged with: keras
accepted answer: http://stackoverflow.com/a/51015462
favorite count: 0
has comment: http://stackoverflow.com/comment/89047430
has comment: http://stackoverflow.com/comment/89057299
has comment: http://stackoverflow.com/comment/89093941
has body: Given a time series of 3D vectors, [x, y, z] where x, y, and z are arbitrary integers, I'd like to build a model that predicts the next vector in the series and captures patterns in each of the dimensions x, y, z. So if X = [[0, 0, 6], [1, 0, 0], [9, 9, 9], [3, 0, 3], [1, 2, 3]] and I give my model the 4-element sequence [[0, 0, 6], [1, 0, 0], [9, 9, 9], [3, 0, 3]] it would predict [1, 2, 3] I can't just one-hot encode each vector since the numbers can have arbitrary values, so I'm wondering how I can accomplish this. Any insight is greatly appreciated, thank you!
tagged with: python
has comment: http://stackoverflow.com/comment/89048473
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51145007
has comment: http://stackoverflow.com/comment/89303133
upvote count: 3
has title: LSTMs with multi-dimensional output targets
has comment: http://stackoverflow.com/comment/89086673
has comment: http://stackoverflow.com/comment/89023472
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89057399
has comment: http://stackoverflow.com/comment/89086743
tagged with: tensorflow
linked to: http://stackoverflow.com/q/51014044
type: Question
has comment: http://stackoverflow.com/comment/89056111
tagged with: lstm
has comment: http://stackoverflow.com/comment/89076655
has comment: http://stackoverflow.com/comment/89056246
has answer: http://stackoverflow.com/a/51015462
score: 3
has comment: http://stackoverflow.com/comment/89083590
has comment: http://stackoverflow.com/comment/89162766
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89100696
has text: @jlaur Do you really think that is possible with beautifulsoup or bs4 library? I can guarantee you that values on the is not possible. If it is at all possible then please share the result for understanding. You login to IQoption and then try this link and let me know: https://iqoption.com/traderoom
comment on: http://stackoverflow.com/q/51038842
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89304706
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51153905
type: AnswerComment
has text: @Chunkylump, Just a minor point, the only issue with your code is the ordering is not guaranteed, `set` is unordered, any ordering you obtain which you expect should be considered a coincidence.

http://stackoverflow.com/q/51136750
has body: I have a tensor (shape=[batchsize]). I want to reshape the tensor in a specific order and into shape=[-1,2]. I want to have that specific order: Element at [0,0] Element at [1,1] Element at [0,1] Element at [1,0] Element at [2,0] Element at [3,1] Element at [2,1] Element at [3,0] and so on for an unknow batchsize. Here is an example code with a tensor range=(0 to input=8). import tensorflow as tf import numpy as np batchsize = tf.placeholder(shape=[], dtype=tf.int32) x = tf.range(0, batchsize, 1) x = tf.reshape(x, shape=[2, -1]) y = tf.transpose(x) z = tf.reshape(y, shape=[-1, 2]) input = 8 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) msg = sess.run([z], feed_dict={batchsize: input}) print(msg) Now my output is: [array([[0, 4], [1, 5], [2, 6], [3, 7]], dtype=int32)] But I want the output to be: [array([[0, 2], [3, 1], [4, 6], [7, 5]], dtype=int32)] In general: The important thing is that, looking only at the transformation of a 4x1 block to a 2x2 block, the first 2 elements of the input tensor are on one diagonal and the remaining 2 elements on the counter diagonal. Keep in mind I do not know how big batchsize is, I just set input=8 for exemplary reason. In my real code the tensor ´x´ is no range array but complex random numbers, so you cannot sort in any way w.r.t. the values. I just made this code for a demonstration purpose. This question is related to this question but with different order or this question, after doing the normal reshape with transpose just to swap elements every 2nd row.
favorite count: 0
type: UnansweredQuestion
tagged with: reshape
tagged with: python
answer count: 0
score: 1
has title: Tensorflow: Reshape and swap elements from tensor(shape=[batchsize]) in a tensor(shape=[batchsize, 2]) with specific order
upvote count: 1
tagged with: tensorflow
linked to: http://stackoverflow.com/q/38212205
type: Question
linked to: http://stackoverflow.com/q/50899488
downvote count: 0
tagged with: swap

http://stackoverflow.com/q/51062096
type: UnansweredQuestion
has title: Extracting MNIST in tensorflow: zlib.error: Error -3 while decompressing data: invalid distance too far back
tagged with: python
has body: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) When using MNIST from tensorflow, I got the following issue: Extracting MNIST_data/train-images-idx3-ubyte.gz Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tianqing/.conda/envs/python35/lib/python3.5/site- packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 229, in read_data_sets train_images = extract_images(f) File "/home/tianqing/.conda/envs/python35/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 53, in extract_images magic = _read32(bytestream) File "/home/tianqing/.conda/envs/python35/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 35, in _read32 return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] File "/home/tianqing/.conda/envs/python35/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/home/tianqing/.conda/envs/python35/lib/python3.5/_compression.py", line 68, in readinto data = self.read(len(byte_view)) File "/home/tianqing/.conda/envs/python35/lib/python3.5/gzip.py", line 469, in read uncompress = self._decompressor.decompress(buf, size) zlib.error: Error -3 while decompressing data: invalid distance too far back I found it is the zlib problem, but can't get any help in stack overflow. Is there any possible solutions?
tagged with: tensorflow
type: Question
tagged with: zlib
tagged with: mnist
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51062213